mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-05-30 08:11:03 +00:00
Initial version of bridging pallets as git subtree (#2458)
* Initial version of bridges pallet as subtree of https://github.com/paritytech/parity-bridges-common Added `Bridges subtree files` pr review rule * Squashed 'bridges/' content from commit d30927c08 git-subtree-dir: bridges git-subtree-split: d30927c089bd9e73092d1ec1a62895603cb277a3 * Updated REAMDE.md and BRIDGES.md (inspired by original https://github.com/paritytech/polkadot/blob/d22eb62fe40e55e15eb91d375f48cc540d83a47e/BRIDGES.md) * Squashed 'bridges/' changes from d30927c08..d3970944b d3970944b Small simplifications (#2050) git-subtree-dir: bridges git-subtree-split: d3970944b0cfc4ea5226225e1ca07dab234c3556 * Squashed 'bridges/' changes from d3970944b..2180797fb 2180797fb Removed CODEOWNERS (#2051) git-subtree-dir: bridges git-subtree-split: 2180797fbf8a990490c67853dcffd81bc8dd083c * Squashed 'bridges/' changes from 2180797fbf..4850aac8ce 4850aac8ce Removed relayer_account: &AccountId from MessageDispatch (#2080) 8c8adafd54 Revert "Fix max-size messages at test chains (#2064)" (#2077) c01a63efd8 Fixed off-by-one when confirming rewards in messages pallet (#2075) a298be96aa Update subxt dependencies (#2072) c0eef51eab Fix max-size messages at test chains (#2064) 3a658e3697 Messages relay fixes (#2073) 0022b5ab22 Slash relayers for invalid transactions (#2025) 198104007f Bump enumflags2 from 0.7.5 to 0.7.7 9229b257e5 [ci] Fix rules for docker build (#2069) 660d791390 [ci] Update buildah command and version (#2058) e4535c0ca4 fix the way latest_confirmed_nonce_at_source is "calculated" (#2067) dbc2d37590 select nothing if we have already selected nonces to submit or have submitted something (#2065) a7eedd21fe [relay-substrate-client] Bump jsonrpsee (#2066) 8875d5aeae Bump clap from 4.2.2 to 4.2.4 25f9cf55e2 Another use of RangeInclusiveExt::checked_len() (#2060) 4942c12a5f submit lane unblock transactions from relay (#2030) c0325d3c9c Test deployments fixes (#2057) fc7b9b7ed7 Use the new matrix server (#2056) 63bcb5c10b Fixed delivery alert rule (#2052) git-subtree-dir: bridges git-subtree-split: 4850aac8ce6c34e5ca6246b88cd14c873a879cba * Squashed 'bridges/' changes from 4850aac8ce..66aaf0dd23 66aaf0dd23 Nits (#2083) git-subtree-dir: bridges git-subtree-split: 66aaf0dd239dde40b64264061a77c921e2c82568 * Squashed 'bridges/' changes from 66aaf0dd23..557ecbcecc 557ecbcecc Fix sized messages (Follow-up on #2064) (#2103) 54f587a066 Add weight of refund extension post_dispatch to the weights of messages pallet (#2089) 5b1626f8c4 fix pallet param for nightly benchmarks check (#2099) ae44c6b7a1 Add millau specific messages weights (#2097) 6ad0bd1f1e Add integrity tests to rialto parachain runtiime (#2096) 6919556de5 Bump tokio from 1.27.0 to 1.28.0 58795fcb75 Bump clap from 4.2.4 to 4.2.5 01bf31085b Bump scale-info from 2.5.0 to 2.6.0 8fe383240d Bump anyhow from 1.0.70 to 1.0.71 8d94e82ad5 deployments: add new BEEFY metrics and alarms (#2090) e9a4749e7e Bump wasmtime from 6.0.1 to 6.0.2 9d9936c0d9 Bump wasmtime from 6.0.1 to 6.0.2 in /tools/runtime-codegen 5d77cd7bee Add more logs to relayer and message pallets (#2082) 75fbb9d3ef Update comment (#2081) 9904d09cf6 Benchmarks for new relayers pallet calls (#2040) git-subtree-dir: bridges git-subtree-split: 557ecbcecc585547b744a5ac9fb8d7f3b9de4521 * fmt * Squashed 'bridges/' changes from 557ecbcecc..04b3dda6aa 04b3dda6aa Remove from subtree (#2111) f8ff15e7e7 Add `MessagesPalletInstance` for integrity tests (#2107) 92ccef58e6 Use generated runtimes for BHR/BHW (#2106) b33e0a585b Fix comment (#2105) git-subtree-dir: bridges git-subtree-split: 04b3dda6aa38599e612ff637710b6d2cff275ef3 * ".git/.scripts/commands/fmt/fmt.sh" --------- Co-authored-by: parity-processbot <>
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
[package]
|
||||
name = "bp-bridge-hub-cumulus"
|
||||
description = "Primitives of BridgeHubRococo parachain runtime."
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2021"
|
||||
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
|
||||
|
||||
[dependencies]
|
||||
# Bridge Dependencies
|
||||
|
||||
bp-polkadot-core = { path = "../../primitives/polkadot-core", default-features = false }
|
||||
bp-messages = { path = "../../primitives/messages", default-features = false }
|
||||
bp-runtime = { path = "../../primitives/runtime", default-features = false }
|
||||
|
||||
# Substrate Based Dependencies
|
||||
|
||||
frame-system = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
frame-support = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-api = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-std = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
|
||||
# Polkadot Dependencies
|
||||
polkadot-primitives = { git = "https://github.com/paritytech/polkadot", branch = "master", default-features = false }
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"bp-polkadot-core/std",
|
||||
"bp-messages/std",
|
||||
"bp-runtime/std",
|
||||
"frame-system/std",
|
||||
"frame-support/std",
|
||||
"sp-api/std",
|
||||
"sp-std/std",
|
||||
"polkadot-primitives/std",
|
||||
]
|
||||
@@ -0,0 +1,216 @@
|
||||
// Copyright 2022 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Parity Bridges Common is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
pub use bp_polkadot_core::{
|
||||
AccountId, AccountInfoStorageMapKeyProvider, AccountPublic, Balance, BlockNumber, Hash, Hasher,
|
||||
Hashing, Header, Index, Nonce, Perbill, Signature, SignedBlock, UncheckedExtrinsic,
|
||||
EXTRA_STORAGE_PROOF_SIZE, TX_EXTRA_BYTES,
|
||||
};
|
||||
|
||||
use bp_messages::*;
|
||||
use bp_runtime::extensions::{
|
||||
BridgeRejectObsoleteHeadersAndMessages, ChargeTransactionPayment, CheckEra, CheckGenesis,
|
||||
CheckNonZeroSender, CheckNonce, CheckSpecVersion, CheckTxVersion, CheckWeight,
|
||||
GenericSignedExtension, RefundBridgedParachainMessagesSchema,
|
||||
};
|
||||
use frame_support::{
|
||||
dispatch::DispatchClass,
|
||||
parameter_types,
|
||||
sp_runtime::{MultiAddress, MultiSigner},
|
||||
weights::constants,
|
||||
};
|
||||
use frame_system::limits;
|
||||
use sp_std::time::Duration;
|
||||
|
||||
/// Average block interval in Cumulus-based parachains.
|
||||
///
|
||||
/// Corresponds to the `MILLISECS_PER_BLOCK` from `parachains_common` crate.
|
||||
pub const AVERAGE_BLOCK_INTERVAL: Duration = Duration::from_secs(12);
|
||||
|
||||
/// All cumulus bridge hubs allow normal extrinsics to fill block up to 75 percent.
|
||||
///
|
||||
/// This is a copy-paste from the cumulus repo's `parachains-common` crate.
|
||||
pub const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
|
||||
|
||||
/// All cumulus bridge hubs chains allow for 0.5 seconds of compute with a 6-second average block
|
||||
/// time.
|
||||
///
|
||||
/// This is a copy-paste from the cumulus repo's `parachains-common` crate.
|
||||
const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(constants::WEIGHT_REF_TIME_PER_SECOND, 0)
|
||||
.saturating_div(2)
|
||||
.set_proof_size(polkadot_primitives::v4::MAX_POV_SIZE as u64);
|
||||
|
||||
/// All cumulus bridge hubs assume that about 5 percent of the block weight is consumed by
|
||||
/// `on_initialize` handlers. This is used to limit the maximal weight of a single extrinsic.
|
||||
///
|
||||
/// This is a copy-paste from the cumulus repo's `parachains-common` crate.
|
||||
pub const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(5);
|
||||
|
||||
parameter_types! {
|
||||
pub BlockLength: limits::BlockLength = limits::BlockLength::max_with_normal_ratio(
|
||||
5 * 1024 * 1024,
|
||||
NORMAL_DISPATCH_RATIO,
|
||||
);
|
||||
|
||||
/// Importing a block with 0 Extrinsics.
|
||||
pub const BlockExecutionWeight: Weight = Weight::from_parts(constants::WEIGHT_REF_TIME_PER_NANOS, 0)
|
||||
.saturating_mul(5_000_000);
|
||||
/// Executing a NO-OP `System::remarks` Extrinsic.
|
||||
pub const ExtrinsicBaseWeight: Weight = Weight::from_parts(constants::WEIGHT_REF_TIME_PER_NANOS, 0)
|
||||
.saturating_mul(125_000);
|
||||
|
||||
pub BlockWeights: limits::BlockWeights = limits::BlockWeights::builder()
|
||||
.base_block(BlockExecutionWeight::get())
|
||||
.for_class(DispatchClass::all(), |weights| {
|
||||
weights.base_extrinsic = ExtrinsicBaseWeight::get();
|
||||
})
|
||||
.for_class(DispatchClass::Normal, |weights| {
|
||||
weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
|
||||
})
|
||||
.for_class(DispatchClass::Operational, |weights| {
|
||||
weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
|
||||
// Operational transactions have an extra reserved space, so that they
|
||||
// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.
|
||||
weights.reserved = Some(
|
||||
MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT,
|
||||
);
|
||||
})
|
||||
.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
|
||||
.build_or_panic();
|
||||
}
|
||||
|
||||
/// Public key of the chain account that may be used to verify signatures.
|
||||
pub type AccountSigner = MultiSigner;
|
||||
|
||||
/// The address format for describing accounts.
|
||||
pub type Address = MultiAddress<AccountId, ()>;
|
||||
|
||||
// Note about selecting values of two following constants:
|
||||
//
|
||||
// Normal transactions have limit of 75% of 1/2 second weight for Cumulus parachains. Let's keep
|
||||
// some reserve for the rest of stuff there => let's select values that fit in 50% of maximal limit.
|
||||
//
|
||||
// Using current constants, the limit would be:
|
||||
//
|
||||
// `75% * WEIGHT_REF_TIME_PER_SECOND * 1 / 2 * 50% = 0.75 * 1_000_000_000_000 / 2 * 0.5 =
|
||||
// 187_500_000_000`
|
||||
//
|
||||
// According to (preliminary) weights of messages pallet, cost of additional message is zero and the
|
||||
// cost of additional relayer is `8_000_000 + db read + db write`. Let's say we want no more than
|
||||
// 4096 unconfirmed messages (no any scientific justification for that - it just looks large
|
||||
// enough). And then we can't have more than 4096 relayers. E.g. for 1024 relayers is (using
|
||||
// `RocksDbWeight`):
|
||||
//
|
||||
// `1024 * (8_000_000 + db read + db write) = 1024 * (8_000_000 + 25_000_000 + 100_000_000) =
|
||||
// 136_192_000_000`
|
||||
//
|
||||
// So 1024 looks like good approximation for the number of relayers. If something is wrong in those
|
||||
// assumptions, or something will change, it shall be caught by the
|
||||
// `ensure_able_to_receive_confirmation` test.
|
||||
|
||||
/// Maximal number of unrewarded relayer entries at inbound lane for Cumulus-based parachains.
|
||||
pub const MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX: MessageNonce = 1024;
|
||||
|
||||
/// Maximal number of unconfirmed messages at inbound lane for Cumulus-based parachains.
|
||||
pub const MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX: MessageNonce = 4096;
|
||||
|
||||
/// Extra signed extension data that is used by all bridge hubs.
|
||||
pub type SignedExtra = (
|
||||
CheckNonZeroSender,
|
||||
CheckSpecVersion,
|
||||
CheckTxVersion,
|
||||
CheckGenesis<Hash>,
|
||||
CheckEra<Hash>,
|
||||
CheckNonce<Index>,
|
||||
CheckWeight,
|
||||
ChargeTransactionPayment<Balance>,
|
||||
BridgeRejectObsoleteHeadersAndMessages,
|
||||
RefundBridgedParachainMessagesSchema,
|
||||
);
|
||||
|
||||
/// Signed extension that is used by all bridge hubs.
|
||||
pub type SignedExtension = GenericSignedExtension<SignedExtra>;
|
||||
|
||||
/// Helper trait to define some extra methods on bridge hubs signed extension (and
|
||||
/// overcome Rust limitations).
|
||||
pub trait BridgeHubSignedExtension {
|
||||
/// Create signed extension from its components.
|
||||
fn from_params(
|
||||
spec_version: u32,
|
||||
transaction_version: u32,
|
||||
era: bp_runtime::TransactionEra<BlockNumber, Hash>,
|
||||
genesis_hash: Hash,
|
||||
nonce: Index,
|
||||
tip: Balance,
|
||||
) -> Self;
|
||||
|
||||
/// Return transaction nonce.
|
||||
fn nonce(&self) -> Index;
|
||||
|
||||
/// Return transaction tip.
|
||||
fn tip(&self) -> Balance;
|
||||
}
|
||||
|
||||
impl BridgeHubSignedExtension for SignedExtension {
|
||||
/// Create signed extension from its components.
|
||||
fn from_params(
|
||||
spec_version: u32,
|
||||
transaction_version: u32,
|
||||
era: bp_runtime::TransactionEra<BlockNumber, Hash>,
|
||||
genesis_hash: Hash,
|
||||
nonce: Index,
|
||||
tip: Balance,
|
||||
) -> Self {
|
||||
GenericSignedExtension::new(
|
||||
(
|
||||
(), // non-zero sender
|
||||
(), // spec version
|
||||
(), // tx version
|
||||
(), // genesis
|
||||
era.frame_era(), // era
|
||||
nonce.into(), // nonce (compact encoding)
|
||||
(), // Check weight
|
||||
tip.into(), // transaction payment / tip (compact encoding)
|
||||
(), // bridge reject obsolete headers and msgs
|
||||
(), // bridge reward to relayer for message passing
|
||||
),
|
||||
Some((
|
||||
(),
|
||||
spec_version,
|
||||
transaction_version,
|
||||
genesis_hash,
|
||||
era.signed_payload(genesis_hash),
|
||||
(),
|
||||
(),
|
||||
(),
|
||||
(),
|
||||
(),
|
||||
)),
|
||||
)
|
||||
}
|
||||
|
||||
/// Return transaction nonce.
|
||||
fn nonce(&self) -> Index {
|
||||
self.payload.5 .0
|
||||
}
|
||||
|
||||
/// Return transaction tip.
|
||||
fn tip(&self) -> Balance {
|
||||
self.payload.7 .0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
[package]
|
||||
name = "bp-bridge-hub-kusama"
|
||||
description = "Primitives of BridgeHubRococo parachain runtime."
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2021"
|
||||
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
|
||||
|
||||
[dependencies]
|
||||
# Bridge Dependencies
|
||||
|
||||
bp-bridge-hub-cumulus = { path = "../chain-bridge-hub-cumulus", default-features = false }
|
||||
bp-runtime = { path = "../../primitives/runtime", default-features = false }
|
||||
bp-messages = { path = "../../primitives/messages", default-features = false }
|
||||
|
||||
# Substrate Based Dependencies
|
||||
|
||||
frame-support = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-api = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-std = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"bp-bridge-hub-cumulus/std",
|
||||
"bp-messages/std",
|
||||
"bp-runtime/std",
|
||||
"frame-support/std",
|
||||
"sp-api/std",
|
||||
"sp-std/std",
|
||||
]
|
||||
@@ -0,0 +1,84 @@
|
||||
// Copyright 2022 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Parity Bridges Common is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Module with configuration which reflects BridgeHubKusama runtime setup (AccountId, Headers,
|
||||
//! Hashes...)
|
||||
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
pub use bp_bridge_hub_cumulus::*;
|
||||
use bp_messages::*;
|
||||
use bp_runtime::{
|
||||
decl_bridge_finality_runtime_apis, decl_bridge_messages_runtime_apis, Chain, Parachain,
|
||||
};
|
||||
use frame_support::{
|
||||
dispatch::DispatchClass,
|
||||
sp_runtime::{MultiAddress, MultiSigner},
|
||||
RuntimeDebug,
|
||||
};
|
||||
use sp_std::prelude::*;
|
||||
|
||||
/// BridgeHubKusama parachain.
|
||||
#[derive(RuntimeDebug)]
|
||||
pub struct BridgeHubKusama;
|
||||
|
||||
impl Chain for BridgeHubKusama {
|
||||
type BlockNumber = BlockNumber;
|
||||
type Hash = Hash;
|
||||
type Hasher = Hasher;
|
||||
type Header = Header;
|
||||
|
||||
type AccountId = AccountId;
|
||||
type Balance = Balance;
|
||||
type Index = Index;
|
||||
type Signature = Signature;
|
||||
|
||||
fn max_extrinsic_size() -> u32 {
|
||||
*BlockLength::get().max.get(DispatchClass::Normal)
|
||||
}
|
||||
|
||||
fn max_extrinsic_weight() -> Weight {
|
||||
BlockWeights::get()
|
||||
.get(DispatchClass::Normal)
|
||||
.max_extrinsic
|
||||
.unwrap_or(Weight::MAX)
|
||||
}
|
||||
}
|
||||
|
||||
impl Parachain for BridgeHubKusama {
|
||||
const PARACHAIN_ID: u32 = BRIDGE_HUB_KUSAMA_PARACHAIN_ID;
|
||||
}
|
||||
|
||||
/// Public key of the chain account that may be used to verify signatures.
|
||||
pub type AccountSigner = MultiSigner;
|
||||
|
||||
/// The address format for describing accounts.
|
||||
pub type Address = MultiAddress<AccountId, ()>;
|
||||
|
||||
/// Identifier of BridgeHubKusama in the Kusama relay chain.
|
||||
pub const BRIDGE_HUB_KUSAMA_PARACHAIN_ID: u32 = 1002;
|
||||
|
||||
/// Name of the With-BridgeHubKusama messages pallet instance that is deployed at bridged chains.
|
||||
// TODO: check me (https://github.com/paritytech/parity-bridges-common/issues/1945)
|
||||
pub const WITH_BRIDGE_HUB_KUSAMA_MESSAGES_PALLET_NAME: &str = "BridgeKusamaMessages";
|
||||
|
||||
/// Name of the With-BridgeHubKusama bridge-relayers pallet instance that is deployed at bridged
|
||||
/// chains.
|
||||
// TODO: check me (https://github.com/paritytech/parity-bridges-common/issues/1945)
|
||||
pub const WITH_BRIDGE_HUB_KUSAMA_RELAYERS_PALLET_NAME: &str = "BridgeRelayers";
|
||||
|
||||
decl_bridge_finality_runtime_apis!(bridge_hub_kusama);
|
||||
decl_bridge_messages_runtime_apis!(bridge_hub_kusama);
|
||||
@@ -0,0 +1,32 @@
|
||||
[package]
|
||||
name = "bp-bridge-hub-polkadot"
|
||||
description = "Primitives of BridgeHubWococo parachain runtime."
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2021"
|
||||
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
|
||||
|
||||
[dependencies]
|
||||
|
||||
# Bridge Dependencies
|
||||
|
||||
bp-bridge-hub-cumulus = { path = "../chain-bridge-hub-cumulus", default-features = false }
|
||||
bp-runtime = { path = "../../primitives/runtime", default-features = false }
|
||||
bp-messages = { path = "../../primitives/messages", default-features = false }
|
||||
|
||||
# Substrate Based Dependencies
|
||||
|
||||
frame-support = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-api = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-std = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"bp-bridge-hub-cumulus/std",
|
||||
"bp-runtime/std",
|
||||
"bp-messages/std",
|
||||
"frame-support/std",
|
||||
"sp-api/std",
|
||||
"sp-std/std",
|
||||
]
|
||||
@@ -0,0 +1,75 @@
|
||||
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Parity Bridges Common is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Module with configuration which reflects BridgeHubPolkadot runtime setup
|
||||
//! (AccountId, Headers, Hashes...)
|
||||
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
pub use bp_bridge_hub_cumulus::*;
|
||||
use bp_messages::*;
|
||||
use bp_runtime::{
|
||||
decl_bridge_finality_runtime_apis, decl_bridge_messages_runtime_apis, Chain, Parachain,
|
||||
};
|
||||
use frame_support::{dispatch::DispatchClass, RuntimeDebug};
|
||||
use sp_std::prelude::*;
|
||||
|
||||
/// BridgeHubPolkadot parachain.
|
||||
#[derive(RuntimeDebug)]
|
||||
pub struct BridgeHubPolkadot;
|
||||
|
||||
impl Chain for BridgeHubPolkadot {
|
||||
type BlockNumber = BlockNumber;
|
||||
type Hash = Hash;
|
||||
type Hasher = Hasher;
|
||||
type Header = Header;
|
||||
|
||||
type AccountId = AccountId;
|
||||
type Balance = Balance;
|
||||
type Index = Index;
|
||||
type Signature = Signature;
|
||||
|
||||
fn max_extrinsic_size() -> u32 {
|
||||
*BlockLength::get().max.get(DispatchClass::Normal)
|
||||
}
|
||||
|
||||
fn max_extrinsic_weight() -> Weight {
|
||||
BlockWeights::get()
|
||||
.get(DispatchClass::Normal)
|
||||
.max_extrinsic
|
||||
.unwrap_or(Weight::MAX)
|
||||
}
|
||||
}
|
||||
|
||||
impl Parachain for BridgeHubPolkadot {
|
||||
const PARACHAIN_ID: u32 = BRIDGE_HUB_POLKADOT_PARACHAIN_ID;
|
||||
}
|
||||
|
||||
/// Identifier of BridgeHubPolkadot in the Polkadot relay chain.
|
||||
// TODO: check me (https://github.com/paritytech/parity-bridges-common/issues/1945)
|
||||
pub const BRIDGE_HUB_POLKADOT_PARACHAIN_ID: u32 = 1002;
|
||||
|
||||
/// Name of the With-BridgeHubPolkadot messages pallet instance that is deployed at bridged chains.
|
||||
// TODO: check me (https://github.com/paritytech/parity-bridges-common/issues/1945)
|
||||
pub const WITH_BRIDGE_HUB_POLKADOT_MESSAGES_PALLET_NAME: &str = "BridgePolkadotMessages";
|
||||
|
||||
/// Name of the With-BridgeHubPolkadot bridge-relayers pallet instance that is deployed at bridged
|
||||
/// chains.
|
||||
// TODO: check me (https://github.com/paritytech/parity-bridges-common/issues/1945)
|
||||
pub const WITH_BRIDGE_HUB_POLKADOT_RELAYERS_PALLET_NAME: &str = "BridgeRelayers";
|
||||
|
||||
decl_bridge_finality_runtime_apis!(bridge_hub_polkadot);
|
||||
decl_bridge_messages_runtime_apis!(bridge_hub_polkadot);
|
||||
@@ -0,0 +1,31 @@
|
||||
[package]
|
||||
name = "bp-bridge-hub-rococo"
|
||||
description = "Primitives of BridgeHubRococo parachain runtime."
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2021"
|
||||
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
|
||||
|
||||
[dependencies]
|
||||
# Bridge Dependencies
|
||||
|
||||
bp-bridge-hub-cumulus = { path = "../chain-bridge-hub-cumulus", default-features = false }
|
||||
bp-runtime = { path = "../../primitives/runtime", default-features = false }
|
||||
bp-messages = { path = "../../primitives/messages", default-features = false }
|
||||
|
||||
# Substrate Based Dependencies
|
||||
|
||||
frame-support = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-api = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-std = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"bp-bridge-hub-cumulus/std",
|
||||
"bp-messages/std",
|
||||
"bp-runtime/std",
|
||||
"frame-support/std",
|
||||
"sp-api/std",
|
||||
"sp-std/std",
|
||||
]
|
||||
@@ -0,0 +1,82 @@
|
||||
// Copyright 2022 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Parity Bridges Common is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Module with configuration which reflects BridgeHubRococo runtime setup (AccountId, Headers,
|
||||
//! Hashes...)
|
||||
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
pub use bp_bridge_hub_cumulus::*;
|
||||
use bp_messages::*;
|
||||
use bp_runtime::{
|
||||
decl_bridge_finality_runtime_apis, decl_bridge_messages_runtime_apis, Chain, Parachain,
|
||||
};
|
||||
use frame_support::{
|
||||
dispatch::DispatchClass,
|
||||
sp_runtime::{MultiAddress, MultiSigner},
|
||||
RuntimeDebug,
|
||||
};
|
||||
use sp_std::prelude::*;
|
||||
|
||||
/// BridgeHubRococo parachain.
|
||||
#[derive(RuntimeDebug)]
|
||||
pub struct BridgeHubRococo;
|
||||
|
||||
impl Chain for BridgeHubRococo {
|
||||
type BlockNumber = BlockNumber;
|
||||
type Hash = Hash;
|
||||
type Hasher = Hasher;
|
||||
type Header = Header;
|
||||
|
||||
type AccountId = AccountId;
|
||||
type Balance = Balance;
|
||||
type Index = Index;
|
||||
type Signature = Signature;
|
||||
|
||||
fn max_extrinsic_size() -> u32 {
|
||||
*BlockLength::get().max.get(DispatchClass::Normal)
|
||||
}
|
||||
|
||||
fn max_extrinsic_weight() -> Weight {
|
||||
BlockWeights::get()
|
||||
.get(DispatchClass::Normal)
|
||||
.max_extrinsic
|
||||
.unwrap_or(Weight::MAX)
|
||||
}
|
||||
}
|
||||
|
||||
impl Parachain for BridgeHubRococo {
|
||||
const PARACHAIN_ID: u32 = BRIDGE_HUB_ROCOCO_PARACHAIN_ID;
|
||||
}
|
||||
|
||||
/// Public key of the chain account that may be used to verify signatures.
|
||||
pub type AccountSigner = MultiSigner;
|
||||
|
||||
/// The address format for describing accounts.
|
||||
pub type Address = MultiAddress<AccountId, ()>;
|
||||
|
||||
/// Identifier of BridgeHubRococo in the Rococo relay chain.
|
||||
pub const BRIDGE_HUB_ROCOCO_PARACHAIN_ID: u32 = 1013;
|
||||
|
||||
/// Name of the With-BridgeHubRococo messages pallet instance that is deployed at bridged chains.
|
||||
pub const WITH_BRIDGE_HUB_ROCOCO_MESSAGES_PALLET_NAME: &str = "BridgeRococoMessages";
|
||||
|
||||
/// Name of the With-BridgeHubRococo bridge-relayers pallet instance that is deployed at bridged
|
||||
/// chains.
|
||||
pub const WITH_BRIDGE_HUB_ROCOCO_RELAYERS_PALLET_NAME: &str = "BridgeRelayers";
|
||||
|
||||
decl_bridge_finality_runtime_apis!(bridge_hub_rococo);
|
||||
decl_bridge_messages_runtime_apis!(bridge_hub_rococo);
|
||||
@@ -0,0 +1,32 @@
|
||||
[package]
|
||||
name = "bp-bridge-hub-wococo"
|
||||
description = "Primitives of BridgeHubWococo parachain runtime."
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2021"
|
||||
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
|
||||
|
||||
[dependencies]
|
||||
|
||||
# Bridge Dependencies
|
||||
|
||||
bp-bridge-hub-cumulus = { path = "../chain-bridge-hub-cumulus", default-features = false }
|
||||
bp-runtime = { path = "../../primitives/runtime", default-features = false }
|
||||
bp-messages = { path = "../../primitives/messages", default-features = false }
|
||||
|
||||
# Substrate Based Dependencies
|
||||
|
||||
frame-support = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-api = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-std = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"bp-bridge-hub-cumulus/std",
|
||||
"bp-runtime/std",
|
||||
"bp-messages/std",
|
||||
"frame-support/std",
|
||||
"sp-api/std",
|
||||
"sp-std/std",
|
||||
]
|
||||
@@ -0,0 +1,72 @@
|
||||
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Parity Bridges Common is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Module with configuration which reflects BridgeHubWococo runtime setup
|
||||
//! (AccountId, Headers, Hashes...)
|
||||
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
pub use bp_bridge_hub_cumulus::*;
|
||||
use bp_messages::*;
|
||||
use bp_runtime::{
|
||||
decl_bridge_finality_runtime_apis, decl_bridge_messages_runtime_apis, Chain, Parachain,
|
||||
};
|
||||
use frame_support::{dispatch::DispatchClass, RuntimeDebug};
|
||||
use sp_std::prelude::*;
|
||||
|
||||
/// BridgeHubWococo parachain.
|
||||
#[derive(RuntimeDebug)]
|
||||
pub struct BridgeHubWococo;
|
||||
|
||||
impl Chain for BridgeHubWococo {
|
||||
type BlockNumber = BlockNumber;
|
||||
type Hash = Hash;
|
||||
type Hasher = Hasher;
|
||||
type Header = Header;
|
||||
|
||||
type AccountId = AccountId;
|
||||
type Balance = Balance;
|
||||
type Index = Index;
|
||||
type Signature = Signature;
|
||||
|
||||
fn max_extrinsic_size() -> u32 {
|
||||
*BlockLength::get().max.get(DispatchClass::Normal)
|
||||
}
|
||||
|
||||
fn max_extrinsic_weight() -> Weight {
|
||||
BlockWeights::get()
|
||||
.get(DispatchClass::Normal)
|
||||
.max_extrinsic
|
||||
.unwrap_or(Weight::MAX)
|
||||
}
|
||||
}
|
||||
|
||||
impl Parachain for BridgeHubWococo {
|
||||
const PARACHAIN_ID: u32 = BRIDGE_HUB_WOCOCO_PARACHAIN_ID;
|
||||
}
|
||||
|
||||
/// Identifier of BridgeHubWococo in the Wococo relay chain.
|
||||
pub const BRIDGE_HUB_WOCOCO_PARACHAIN_ID: u32 = 1014;
|
||||
|
||||
/// Name of the With-BridgeHubWococo messages pallet instance that is deployed at bridged chains.
|
||||
pub const WITH_BRIDGE_HUB_WOCOCO_MESSAGES_PALLET_NAME: &str = "BridgeWococoMessages";
|
||||
|
||||
/// Name of the With-BridgeHubWococo bridge-relayers pallet instance that is deployed at bridged
|
||||
/// chains.
|
||||
pub const WITH_BRIDGE_HUB_WOCOCO_RELAYERS_PALLET_NAME: &str = "BridgeRelayers";
|
||||
|
||||
decl_bridge_finality_runtime_apis!(bridge_hub_wococo);
|
||||
decl_bridge_messages_runtime_apis!(bridge_hub_wococo);
|
||||
@@ -0,0 +1,30 @@
|
||||
[package]
|
||||
name = "bp-kusama"
|
||||
description = "Primitives of Kusama runtime."
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2021"
|
||||
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
|
||||
|
||||
[dependencies]
|
||||
|
||||
# Bridge Dependencies
|
||||
|
||||
bp-header-chain = { path = "../header-chain", default-features = false }
|
||||
bp-polkadot-core = { path = "../polkadot-core", default-features = false }
|
||||
bp-runtime = { path = "../runtime", default-features = false }
|
||||
|
||||
# Substrate Based Dependencies
|
||||
|
||||
frame-support = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-api = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"bp-header-chain/std",
|
||||
"bp-polkadot-core/std",
|
||||
"bp-runtime/std",
|
||||
"frame-support/std",
|
||||
"sp-api/std",
|
||||
]
|
||||
@@ -0,0 +1,65 @@
|
||||
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Parity Bridges Common is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
// RuntimeApi generated functions
|
||||
#![allow(clippy::too_many_arguments)]
|
||||
|
||||
pub use bp_polkadot_core::*;
|
||||
|
||||
use bp_header_chain::ChainWithGrandpa;
|
||||
use bp_runtime::{decl_bridge_finality_runtime_apis, Chain};
|
||||
use frame_support::weights::Weight;
|
||||
|
||||
/// Kusama Chain
|
||||
pub struct Kusama;
|
||||
|
||||
impl Chain for Kusama {
|
||||
type BlockNumber = <PolkadotLike as Chain>::BlockNumber;
|
||||
type Hash = <PolkadotLike as Chain>::Hash;
|
||||
type Hasher = <PolkadotLike as Chain>::Hasher;
|
||||
type Header = <PolkadotLike as Chain>::Header;
|
||||
|
||||
type AccountId = <PolkadotLike as Chain>::AccountId;
|
||||
type Balance = <PolkadotLike as Chain>::Balance;
|
||||
type Index = <PolkadotLike as Chain>::Index;
|
||||
type Signature = <PolkadotLike as Chain>::Signature;
|
||||
|
||||
fn max_extrinsic_size() -> u32 {
|
||||
PolkadotLike::max_extrinsic_size()
|
||||
}
|
||||
|
||||
fn max_extrinsic_weight() -> Weight {
|
||||
PolkadotLike::max_extrinsic_weight()
|
||||
}
|
||||
}
|
||||
|
||||
impl ChainWithGrandpa for Kusama {
|
||||
const WITH_CHAIN_GRANDPA_PALLET_NAME: &'static str = WITH_KUSAMA_GRANDPA_PALLET_NAME;
|
||||
const MAX_AUTHORITIES_COUNT: u32 = MAX_AUTHORITIES_COUNT;
|
||||
const REASONABLE_HEADERS_IN_JUSTIFICATON_ANCESTRY: u32 =
|
||||
REASONABLE_HEADERS_IN_JUSTIFICATON_ANCESTRY;
|
||||
const MAX_HEADER_SIZE: u32 = MAX_HEADER_SIZE;
|
||||
const AVERAGE_HEADER_SIZE_IN_JUSTIFICATION: u32 = AVERAGE_HEADER_SIZE_IN_JUSTIFICATION;
|
||||
}
|
||||
|
||||
/// Name of the parachains pallet in the Kusama runtime.
|
||||
pub const PARAS_PALLET_NAME: &str = "Paras";
|
||||
|
||||
/// Name of the With-Kusama GRANDPA pallet instance that is deployed at bridged chains.
|
||||
pub const WITH_KUSAMA_GRANDPA_PALLET_NAME: &str = "BridgeKusamaGrandpa";
|
||||
|
||||
decl_bridge_finality_runtime_apis!(kusama);
|
||||
@@ -0,0 +1,30 @@
|
||||
[package]
|
||||
name = "bp-polkadot"
|
||||
description = "Primitives of Polkadot runtime."
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2021"
|
||||
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
|
||||
|
||||
[dependencies]
|
||||
|
||||
# Bridge Dependencies
|
||||
|
||||
bp-header-chain = { path = "../header-chain", default-features = false }
|
||||
bp-polkadot-core = { path = "../polkadot-core", default-features = false }
|
||||
bp-runtime = { path = "../runtime", default-features = false }
|
||||
|
||||
# Substrate Based Dependencies
|
||||
|
||||
frame-support = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-api = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"bp-header-chain/std",
|
||||
"bp-polkadot-core/std",
|
||||
"bp-runtime/std",
|
||||
"frame-support/std",
|
||||
"sp-api/std",
|
||||
]
|
||||
@@ -0,0 +1,65 @@
|
||||
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Parity Bridges Common is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
// RuntimeApi generated functions
|
||||
#![allow(clippy::too_many_arguments)]
|
||||
|
||||
pub use bp_polkadot_core::*;
|
||||
|
||||
use bp_header_chain::ChainWithGrandpa;
|
||||
use bp_runtime::{decl_bridge_finality_runtime_apis, Chain};
|
||||
use frame_support::weights::Weight;
|
||||
|
||||
/// Polkadot Chain
|
||||
pub struct Polkadot;
|
||||
|
||||
impl Chain for Polkadot {
|
||||
type BlockNumber = <PolkadotLike as Chain>::BlockNumber;
|
||||
type Hash = <PolkadotLike as Chain>::Hash;
|
||||
type Hasher = <PolkadotLike as Chain>::Hasher;
|
||||
type Header = <PolkadotLike as Chain>::Header;
|
||||
|
||||
type AccountId = <PolkadotLike as Chain>::AccountId;
|
||||
type Balance = <PolkadotLike as Chain>::Balance;
|
||||
type Index = <PolkadotLike as Chain>::Index;
|
||||
type Signature = <PolkadotLike as Chain>::Signature;
|
||||
|
||||
fn max_extrinsic_size() -> u32 {
|
||||
PolkadotLike::max_extrinsic_size()
|
||||
}
|
||||
|
||||
fn max_extrinsic_weight() -> Weight {
|
||||
PolkadotLike::max_extrinsic_weight()
|
||||
}
|
||||
}
|
||||
|
||||
impl ChainWithGrandpa for Polkadot {
|
||||
const WITH_CHAIN_GRANDPA_PALLET_NAME: &'static str = WITH_POLKADOT_GRANDPA_PALLET_NAME;
|
||||
const MAX_AUTHORITIES_COUNT: u32 = MAX_AUTHORITIES_COUNT;
|
||||
const REASONABLE_HEADERS_IN_JUSTIFICATON_ANCESTRY: u32 =
|
||||
REASONABLE_HEADERS_IN_JUSTIFICATON_ANCESTRY;
|
||||
const MAX_HEADER_SIZE: u32 = MAX_HEADER_SIZE;
|
||||
const AVERAGE_HEADER_SIZE_IN_JUSTIFICATION: u32 = AVERAGE_HEADER_SIZE_IN_JUSTIFICATION;
|
||||
}
|
||||
|
||||
/// Name of the parachains pallet in the Polkadot runtime.
|
||||
pub const PARAS_PALLET_NAME: &str = "Paras";
|
||||
|
||||
/// Name of the With-Polkadot GRANDPA pallet instance that is deployed at bridged chains.
|
||||
pub const WITH_POLKADOT_GRANDPA_PALLET_NAME: &str = "BridgePolkadotGrandpa";
|
||||
|
||||
decl_bridge_finality_runtime_apis!(polkadot);
|
||||
@@ -0,0 +1,30 @@
|
||||
[package]
|
||||
name = "bp-rococo"
|
||||
description = "Primitives of Rococo runtime."
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2021"
|
||||
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
|
||||
|
||||
[dependencies]
|
||||
|
||||
# Bridge Dependencies
|
||||
|
||||
bp-header-chain = { path = "../header-chain", default-features = false }
|
||||
bp-polkadot-core = { path = "../polkadot-core", default-features = false }
|
||||
bp-runtime = { path = "../runtime", default-features = false }
|
||||
|
||||
# Substrate Based Dependencies
|
||||
|
||||
sp-api = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
frame-support = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"bp-header-chain/std",
|
||||
"bp-polkadot-core/std",
|
||||
"bp-runtime/std",
|
||||
"frame-support/std",
|
||||
"sp-api/std",
|
||||
]
|
||||
@@ -0,0 +1,76 @@
|
||||
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Parity Bridges Common is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
// RuntimeApi generated functions
|
||||
#![allow(clippy::too_many_arguments)]
|
||||
|
||||
pub use bp_polkadot_core::*;
|
||||
|
||||
use bp_header_chain::ChainWithGrandpa;
|
||||
use bp_runtime::{decl_bridge_finality_runtime_apis, Chain};
|
||||
use frame_support::{parameter_types, weights::Weight};
|
||||
|
||||
/// Rococo Chain
|
||||
pub struct Rococo;
|
||||
|
||||
impl Chain for Rococo {
|
||||
type BlockNumber = <PolkadotLike as Chain>::BlockNumber;
|
||||
type Hash = <PolkadotLike as Chain>::Hash;
|
||||
type Hasher = <PolkadotLike as Chain>::Hasher;
|
||||
type Header = <PolkadotLike as Chain>::Header;
|
||||
|
||||
type AccountId = <PolkadotLike as Chain>::AccountId;
|
||||
type Balance = <PolkadotLike as Chain>::Balance;
|
||||
type Index = <PolkadotLike as Chain>::Index;
|
||||
type Signature = <PolkadotLike as Chain>::Signature;
|
||||
|
||||
fn max_extrinsic_size() -> u32 {
|
||||
PolkadotLike::max_extrinsic_size()
|
||||
}
|
||||
|
||||
fn max_extrinsic_weight() -> Weight {
|
||||
PolkadotLike::max_extrinsic_weight()
|
||||
}
|
||||
}
|
||||
|
||||
impl ChainWithGrandpa for Rococo {
|
||||
const WITH_CHAIN_GRANDPA_PALLET_NAME: &'static str = WITH_ROCOCO_GRANDPA_PALLET_NAME;
|
||||
const MAX_AUTHORITIES_COUNT: u32 = MAX_AUTHORITIES_COUNT;
|
||||
const REASONABLE_HEADERS_IN_JUSTIFICATON_ANCESTRY: u32 =
|
||||
REASONABLE_HEADERS_IN_JUSTIFICATON_ANCESTRY;
|
||||
const MAX_HEADER_SIZE: u32 = MAX_HEADER_SIZE;
|
||||
const AVERAGE_HEADER_SIZE_IN_JUSTIFICATION: u32 = AVERAGE_HEADER_SIZE_IN_JUSTIFICATION;
|
||||
}
|
||||
|
||||
parameter_types! {
|
||||
pub const SS58Prefix: u8 = 42;
|
||||
}
|
||||
|
||||
/// Name of the parachains pallet in the Rococo runtime.
|
||||
pub const PARAS_PALLET_NAME: &str = "Paras";
|
||||
|
||||
/// Name of the With-Rococo GRANDPA pallet instance that is deployed at bridged chains.
|
||||
pub const WITH_ROCOCO_GRANDPA_PALLET_NAME: &str = "BridgeRococoGrandpa";
|
||||
|
||||
/// Maximal size of encoded `bp_parachains::ParaStoredHeaderData` structure among all Rococo
|
||||
/// parachains.
|
||||
///
|
||||
/// It includes the block number and state root, so it shall be near 40 bytes, but let's have some
|
||||
/// reserve.
|
||||
pub const MAX_NESTED_PARACHAIN_HEAD_DATA_SIZE: u32 = 128;
|
||||
|
||||
decl_bridge_finality_runtime_apis!(rococo);
|
||||
@@ -0,0 +1,32 @@
|
||||
[package]
|
||||
name = "bp-wococo"
|
||||
description = "Primitives of Wococo runtime."
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2021"
|
||||
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
|
||||
|
||||
[dependencies]
|
||||
|
||||
# Bridge Dependencies
|
||||
|
||||
bp-header-chain = { path = "../header-chain", default-features = false }
|
||||
bp-polkadot-core = { path = "../polkadot-core", default-features = false }
|
||||
bp-runtime = { path = "../runtime", default-features = false }
|
||||
bp-rococo = { path = "../chain-rococo", default-features = false }
|
||||
|
||||
# Substrate Based Dependencies
|
||||
|
||||
frame-support = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-api = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"bp-header-chain/std",
|
||||
"bp-polkadot-core/std",
|
||||
"bp-runtime/std",
|
||||
"bp-rococo/std",
|
||||
"frame-support/std",
|
||||
"sp-api/std",
|
||||
]
|
||||
@@ -0,0 +1,65 @@
|
||||
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Parity Bridges Common is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
// RuntimeApi generated functions
|
||||
#![allow(clippy::too_many_arguments)]
|
||||
|
||||
pub use bp_polkadot_core::*;
|
||||
pub use bp_rococo::{
|
||||
SS58Prefix, MAX_AUTHORITIES_COUNT, MAX_NESTED_PARACHAIN_HEAD_DATA_SIZE, PARAS_PALLET_NAME,
|
||||
};
|
||||
|
||||
use bp_header_chain::ChainWithGrandpa;
|
||||
use bp_runtime::{decl_bridge_finality_runtime_apis, Chain};
|
||||
use frame_support::weights::Weight;
|
||||
|
||||
/// Wococo Chain
|
||||
pub struct Wococo;
|
||||
|
||||
impl Chain for Wococo {
|
||||
type BlockNumber = <PolkadotLike as Chain>::BlockNumber;
|
||||
type Hash = <PolkadotLike as Chain>::Hash;
|
||||
type Hasher = <PolkadotLike as Chain>::Hasher;
|
||||
type Header = <PolkadotLike as Chain>::Header;
|
||||
|
||||
type AccountId = <PolkadotLike as Chain>::AccountId;
|
||||
type Balance = <PolkadotLike as Chain>::Balance;
|
||||
type Index = <PolkadotLike as Chain>::Index;
|
||||
type Signature = <PolkadotLike as Chain>::Signature;
|
||||
|
||||
fn max_extrinsic_size() -> u32 {
|
||||
PolkadotLike::max_extrinsic_size()
|
||||
}
|
||||
|
||||
fn max_extrinsic_weight() -> Weight {
|
||||
PolkadotLike::max_extrinsic_weight()
|
||||
}
|
||||
}
|
||||
|
||||
impl ChainWithGrandpa for Wococo {
|
||||
const WITH_CHAIN_GRANDPA_PALLET_NAME: &'static str = WITH_WOCOCO_GRANDPA_PALLET_NAME;
|
||||
const MAX_AUTHORITIES_COUNT: u32 = MAX_AUTHORITIES_COUNT;
|
||||
const REASONABLE_HEADERS_IN_JUSTIFICATON_ANCESTRY: u32 =
|
||||
REASONABLE_HEADERS_IN_JUSTIFICATON_ANCESTRY;
|
||||
const MAX_HEADER_SIZE: u32 = MAX_HEADER_SIZE;
|
||||
const AVERAGE_HEADER_SIZE_IN_JUSTIFICATION: u32 = AVERAGE_HEADER_SIZE_IN_JUSTIFICATION;
|
||||
}
|
||||
|
||||
/// Name of the With-Wococo GRANDPA pallet instance that is deployed at bridged chains.
|
||||
pub const WITH_WOCOCO_GRANDPA_PALLET_NAME: &str = "BridgeWococoGrandpa";
|
||||
|
||||
decl_bridge_finality_runtime_apis!(wococo);
|
||||
@@ -0,0 +1,45 @@
|
||||
[package]
|
||||
name = "bp-header-chain"
|
||||
description = "A common interface for describing what a bridge pallet should be able to do."
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2021"
|
||||
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
|
||||
|
||||
[dependencies]
|
||||
codec = { package = "parity-scale-codec", version = "3.1.5", default-features = false }
|
||||
finality-grandpa = { version = "0.16.2", default-features = false }
|
||||
scale-info = { version = "2.6.0", default-features = false, features = ["derive"] }
|
||||
serde = { version = "1.0", optional = true }
|
||||
|
||||
# Bridge dependencies
|
||||
|
||||
bp-runtime = { path = "../runtime", default-features = false }
|
||||
|
||||
# Substrate Dependencies
|
||||
|
||||
frame-support = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-core = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-consensus-grandpa = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-std = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
|
||||
[dev-dependencies]
|
||||
bp-test-utils = { path = "../test-utils" }
|
||||
hex = "0.4"
|
||||
hex-literal = "0.4"
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"bp-runtime/std",
|
||||
"codec/std",
|
||||
"finality-grandpa/std",
|
||||
"serde/std",
|
||||
"frame-support/std",
|
||||
"scale-info/std",
|
||||
"sp-core/std",
|
||||
"sp-consensus-grandpa/std",
|
||||
"sp-runtime/std",
|
||||
"sp-std/std",
|
||||
]
|
||||
@@ -0,0 +1,390 @@
|
||||
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Parity Bridges Common is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Pallet for checking GRANDPA Finality Proofs.
|
||||
//!
|
||||
//! Adapted copy of substrate/client/finality-grandpa/src/justification.rs. If origin
|
||||
//! will ever be moved to the sp_consensus_grandpa, we should reuse that implementation.
|
||||
|
||||
use crate::ChainWithGrandpa;
|
||||
|
||||
use bp_runtime::{BlockNumberOf, Chain, HashOf};
|
||||
use codec::{Decode, Encode, MaxEncodedLen};
|
||||
use finality_grandpa::voter_set::VoterSet;
|
||||
use frame_support::RuntimeDebug;
|
||||
use scale_info::TypeInfo;
|
||||
use sp_consensus_grandpa::{AuthorityId, AuthoritySignature, SetId};
|
||||
use sp_runtime::{traits::Header as HeaderT, SaturatedConversion};
|
||||
use sp_std::{
|
||||
collections::{btree_map::BTreeMap, btree_set::BTreeSet},
|
||||
prelude::*,
|
||||
};
|
||||
|
||||
/// A GRANDPA Justification is a proof that a given header was finalized
|
||||
/// at a certain height and with a certain set of authorities.
|
||||
///
|
||||
/// This particular proof is used to prove that headers on a bridged chain
|
||||
/// (so not our chain) have been finalized correctly.
|
||||
#[derive(Encode, Decode, RuntimeDebug, Clone, PartialEq, Eq, TypeInfo)]
|
||||
pub struct GrandpaJustification<Header: HeaderT> {
|
||||
/// The round (voting period) this justification is valid for.
|
||||
pub round: u64,
|
||||
/// The set of votes for the chain which is to be finalized.
|
||||
pub commit:
|
||||
finality_grandpa::Commit<Header::Hash, Header::Number, AuthoritySignature, AuthorityId>,
|
||||
/// A proof that the chain of blocks in the commit are related to each other.
|
||||
pub votes_ancestries: Vec<Header>,
|
||||
}
|
||||
|
||||
impl<H: HeaderT> GrandpaJustification<H> {
|
||||
/// Returns reasonable size of justification using constants from the provided chain.
|
||||
///
|
||||
/// An imprecise analogue of `MaxEncodedLen` implementation. We don't use it for
|
||||
/// any precise calculations - that's just an estimation.
|
||||
pub fn max_reasonable_size<C>(required_precommits: u32) -> u32
|
||||
where
|
||||
C: Chain<Header = H> + ChainWithGrandpa,
|
||||
{
|
||||
// we don't need precise results here - just estimations, so some details
|
||||
// are removed from computations (e.g. bytes required to encode vector length)
|
||||
|
||||
// structures in `finality_grandpa` crate are not implementing `MaxEncodedLength`, so
|
||||
// here's our estimation for the `finality_grandpa::Commit` struct size
|
||||
//
|
||||
// precommit is: hash + number
|
||||
// signed precommit is: precommit + signature (64b) + authority id
|
||||
// commit is: hash + number + vec of signed precommits
|
||||
let signed_precommit_size: u32 = BlockNumberOf::<C>::max_encoded_len()
|
||||
.saturating_add(HashOf::<C>::max_encoded_len().saturated_into())
|
||||
.saturating_add(64)
|
||||
.saturating_add(AuthorityId::max_encoded_len().saturated_into())
|
||||
.saturated_into();
|
||||
let max_expected_signed_commit_size = signed_precommit_size
|
||||
.saturating_mul(required_precommits)
|
||||
.saturating_add(BlockNumberOf::<C>::max_encoded_len().saturated_into())
|
||||
.saturating_add(HashOf::<C>::max_encoded_len().saturated_into());
|
||||
|
||||
// justification is a signed GRANDPA commit, `votes_ancestries` vector and round number
|
||||
let max_expected_votes_ancestries_size = C::REASONABLE_HEADERS_IN_JUSTIFICATON_ANCESTRY
|
||||
.saturating_mul(C::AVERAGE_HEADER_SIZE_IN_JUSTIFICATION);
|
||||
|
||||
8u32.saturating_add(max_expected_signed_commit_size)
|
||||
.saturating_add(max_expected_votes_ancestries_size)
|
||||
}
|
||||
}
|
||||
|
||||
impl<H: HeaderT> crate::FinalityProof<H::Number> for GrandpaJustification<H> {
|
||||
fn target_header_number(&self) -> H::Number {
|
||||
self.commit.target_number
|
||||
}
|
||||
}
|
||||
|
||||
/// Justification verification error.
|
||||
#[derive(Eq, RuntimeDebug, PartialEq)]
|
||||
pub enum Error {
|
||||
/// Failed to decode justification.
|
||||
JustificationDecode,
|
||||
/// Justification is finalizing unexpected header.
|
||||
InvalidJustificationTarget,
|
||||
/// Justification contains redundant votes.
|
||||
RedundantVotesInJustification,
|
||||
/// Justification contains unknown authority precommit.
|
||||
UnknownAuthorityVote,
|
||||
/// Justification contains duplicate authority precommit.
|
||||
DuplicateAuthorityVote,
|
||||
/// The authority has provided an invalid signature.
|
||||
InvalidAuthoritySignature,
|
||||
/// The justification contains precommit for header that is not a descendant of the commit
|
||||
/// header.
|
||||
PrecommitIsNotCommitDescendant,
|
||||
/// The cumulative weight of all votes in the justification is not enough to justify commit
|
||||
/// header finalization.
|
||||
TooLowCumulativeWeight,
|
||||
/// The justification contains extra (unused) headers in its `votes_ancestries` field.
|
||||
ExtraHeadersInVotesAncestries,
|
||||
}
|
||||
|
||||
/// Given GRANDPA authorities set size, return number of valid authorities votes that the
|
||||
/// justification must have to be valid.
|
||||
///
|
||||
/// This function assumes that all authorities have the same vote weight.
|
||||
pub fn required_justification_precommits(authorities_set_length: u32) -> u32 {
|
||||
authorities_set_length - authorities_set_length.saturating_sub(1) / 3
|
||||
}
|
||||
|
||||
/// Decode justification target.
|
||||
pub fn decode_justification_target<Header: HeaderT>(
|
||||
raw_justification: &[u8],
|
||||
) -> Result<(Header::Hash, Header::Number), Error> {
|
||||
GrandpaJustification::<Header>::decode(&mut &*raw_justification)
|
||||
.map(|justification| (justification.commit.target_hash, justification.commit.target_number))
|
||||
.map_err(|_| Error::JustificationDecode)
|
||||
}
|
||||
|
||||
/// Verify and optimize given justification by removing unknown and duplicate votes.
|
||||
pub fn verify_and_optimize_justification<Header: HeaderT>(
|
||||
finalized_target: (Header::Hash, Header::Number),
|
||||
authorities_set_id: SetId,
|
||||
authorities_set: &VoterSet<AuthorityId>,
|
||||
justification: GrandpaJustification<Header>,
|
||||
) -> Result<GrandpaJustification<Header>, Error>
|
||||
where
|
||||
Header::Number: finality_grandpa::BlockNumberOps,
|
||||
{
|
||||
let mut optimizer = OptimizationCallbacks(Vec::new());
|
||||
verify_justification_with_callbacks(
|
||||
finalized_target,
|
||||
authorities_set_id,
|
||||
authorities_set,
|
||||
&justification,
|
||||
&mut optimizer,
|
||||
)?;
|
||||
Ok(optimizer.optimize(justification))
|
||||
}
|
||||
|
||||
/// Verify that justification, that is generated by given authority set, finalizes given header.
|
||||
pub fn verify_justification<Header: HeaderT>(
|
||||
finalized_target: (Header::Hash, Header::Number),
|
||||
authorities_set_id: SetId,
|
||||
authorities_set: &VoterSet<AuthorityId>,
|
||||
justification: &GrandpaJustification<Header>,
|
||||
) -> Result<(), Error>
|
||||
where
|
||||
Header::Number: finality_grandpa::BlockNumberOps,
|
||||
{
|
||||
verify_justification_with_callbacks(
|
||||
finalized_target,
|
||||
authorities_set_id,
|
||||
authorities_set,
|
||||
justification,
|
||||
&mut StrictVerificationCallbacks,
|
||||
)
|
||||
}
|
||||
|
||||
/// Verification callbacks.
|
||||
trait VerificationCallbacks {
|
||||
/// Called when we see a precommit from unknown authority.
|
||||
fn on_unkown_authority(&mut self, precommit_idx: usize) -> Result<(), Error>;
|
||||
/// Called when we see a precommit with duplicate vote from known authority.
|
||||
fn on_duplicate_authority_vote(&mut self, precommit_idx: usize) -> Result<(), Error>;
|
||||
/// Called when we see a precommit after we've collected enough votes from authorities.
|
||||
fn on_redundant_authority_vote(&mut self, precommit_idx: usize) -> Result<(), Error>;
|
||||
}
|
||||
|
||||
/// Verification callbacks that reject all unknown, duplicate or redundant votes.
|
||||
struct StrictVerificationCallbacks;
|
||||
|
||||
impl VerificationCallbacks for StrictVerificationCallbacks {
|
||||
fn on_unkown_authority(&mut self, _precommit_idx: usize) -> Result<(), Error> {
|
||||
Err(Error::UnknownAuthorityVote)
|
||||
}
|
||||
|
||||
fn on_duplicate_authority_vote(&mut self, _precommit_idx: usize) -> Result<(), Error> {
|
||||
Err(Error::DuplicateAuthorityVote)
|
||||
}
|
||||
|
||||
fn on_redundant_authority_vote(&mut self, _precommit_idx: usize) -> Result<(), Error> {
|
||||
Err(Error::RedundantVotesInJustification)
|
||||
}
|
||||
}
|
||||
|
||||
/// Verification callbacks for justification optimization.
|
||||
struct OptimizationCallbacks(Vec<usize>);
|
||||
|
||||
impl OptimizationCallbacks {
|
||||
fn optimize<Header: HeaderT>(
|
||||
self,
|
||||
mut justification: GrandpaJustification<Header>,
|
||||
) -> GrandpaJustification<Header> {
|
||||
for invalid_precommit_idx in self.0.into_iter().rev() {
|
||||
justification.commit.precommits.remove(invalid_precommit_idx);
|
||||
}
|
||||
justification
|
||||
}
|
||||
}
|
||||
|
||||
impl VerificationCallbacks for OptimizationCallbacks {
|
||||
fn on_unkown_authority(&mut self, precommit_idx: usize) -> Result<(), Error> {
|
||||
self.0.push(precommit_idx);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn on_duplicate_authority_vote(&mut self, precommit_idx: usize) -> Result<(), Error> {
|
||||
self.0.push(precommit_idx);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn on_redundant_authority_vote(&mut self, precommit_idx: usize) -> Result<(), Error> {
|
||||
self.0.push(precommit_idx);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Verify that justification, that is generated by given authority set, finalizes given header.
|
||||
fn verify_justification_with_callbacks<Header: HeaderT, C: VerificationCallbacks>(
|
||||
finalized_target: (Header::Hash, Header::Number),
|
||||
authorities_set_id: SetId,
|
||||
authorities_set: &VoterSet<AuthorityId>,
|
||||
justification: &GrandpaJustification<Header>,
|
||||
callbacks: &mut C,
|
||||
) -> Result<(), Error>
|
||||
where
|
||||
Header::Number: finality_grandpa::BlockNumberOps,
|
||||
{
|
||||
// ensure that it is justification for the expected header
|
||||
if (justification.commit.target_hash, justification.commit.target_number) != finalized_target {
|
||||
return Err(Error::InvalidJustificationTarget)
|
||||
}
|
||||
|
||||
let threshold = authorities_set.threshold().0.into();
|
||||
let mut chain = AncestryChain::new(&justification.votes_ancestries);
|
||||
let mut signature_buffer = Vec::new();
|
||||
let mut votes = BTreeSet::new();
|
||||
let mut cumulative_weight = 0u64;
|
||||
|
||||
for (precommit_idx, signed) in justification.commit.precommits.iter().enumerate() {
|
||||
// if we have collected enough precommits, we probabably want to fail/remove extra
|
||||
// precommits
|
||||
if cumulative_weight >= threshold {
|
||||
callbacks.on_redundant_authority_vote(precommit_idx)?;
|
||||
continue
|
||||
}
|
||||
|
||||
// authority must be in the set
|
||||
let authority_info = match authorities_set.get(&signed.id) {
|
||||
Some(authority_info) => authority_info,
|
||||
None => {
|
||||
callbacks.on_unkown_authority(precommit_idx)?;
|
||||
continue
|
||||
},
|
||||
};
|
||||
|
||||
// check if authority has already voted in the same round.
|
||||
//
|
||||
// there's a lot of code in `validate_commit` and `import_precommit` functions inside
|
||||
// `finality-grandpa` crate (mostly related to reporting equivocations). But the only thing
|
||||
// that we care about is that only first vote from the authority is accepted
|
||||
if !votes.insert(signed.id.clone()) {
|
||||
callbacks.on_duplicate_authority_vote(precommit_idx)?;
|
||||
continue
|
||||
}
|
||||
|
||||
// everything below this line can't just `continue`, because state is already altered
|
||||
|
||||
// precommits aren't allowed for block lower than the target
|
||||
if signed.precommit.target_number < justification.commit.target_number {
|
||||
return Err(Error::PrecommitIsNotCommitDescendant)
|
||||
}
|
||||
// all precommits must be descendants of target block
|
||||
chain = chain
|
||||
.ensure_descendant(&justification.commit.target_hash, &signed.precommit.target_hash)?;
|
||||
// since we know now that the precommit target is the descendant of the justification
|
||||
// target, we may increase 'weight' of the justification target
|
||||
//
|
||||
// there's a lot of code in the `VoteGraph::insert` method inside `finality-grandpa` crate,
|
||||
// but in the end it is only used to find GHOST, which we don't care about. The only thing
|
||||
// that we care about is that the justification target has enough weight
|
||||
cumulative_weight = cumulative_weight.checked_add(authority_info.weight().0.into()).expect(
|
||||
"sum of weights of ALL authorities is expected not to overflow - this is guaranteed by\
|
||||
existence of VoterSet;\
|
||||
the order of loop conditions guarantees that we can account vote from same authority\
|
||||
multiple times;\
|
||||
thus we'll never overflow the u64::MAX;\
|
||||
qed",
|
||||
);
|
||||
|
||||
// verify authority signature
|
||||
if !sp_consensus_grandpa::check_message_signature_with_buffer(
|
||||
&finality_grandpa::Message::Precommit(signed.precommit.clone()),
|
||||
&signed.id,
|
||||
&signed.signature,
|
||||
justification.round,
|
||||
authorities_set_id,
|
||||
&mut signature_buffer,
|
||||
) {
|
||||
return Err(Error::InvalidAuthoritySignature)
|
||||
}
|
||||
}
|
||||
|
||||
// check that there are no extra headers in the justification
|
||||
if !chain.unvisited.is_empty() {
|
||||
return Err(Error::ExtraHeadersInVotesAncestries)
|
||||
}
|
||||
|
||||
// check that the cumulative weight of validators voted for the justification target (or one
|
||||
// of its descendents) is larger than required threshold.
|
||||
if cumulative_weight >= threshold {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::TooLowCumulativeWeight)
|
||||
}
|
||||
}
|
||||
|
||||
/// Votes ancestries with useful methods.
|
||||
#[derive(RuntimeDebug)]
|
||||
pub struct AncestryChain<Header: HeaderT> {
|
||||
/// Header hash => parent header hash mapping.
|
||||
pub parents: BTreeMap<Header::Hash, Header::Hash>,
|
||||
/// Hashes of headers that were not visited by `is_ancestor` method.
|
||||
pub unvisited: BTreeSet<Header::Hash>,
|
||||
}
|
||||
|
||||
impl<Header: HeaderT> AncestryChain<Header> {
|
||||
/// Create new ancestry chain.
|
||||
pub fn new(ancestry: &[Header]) -> AncestryChain<Header> {
|
||||
let mut parents = BTreeMap::new();
|
||||
let mut unvisited = BTreeSet::new();
|
||||
for ancestor in ancestry {
|
||||
let hash = ancestor.hash();
|
||||
let parent_hash = *ancestor.parent_hash();
|
||||
parents.insert(hash, parent_hash);
|
||||
unvisited.insert(hash);
|
||||
}
|
||||
AncestryChain { parents, unvisited }
|
||||
}
|
||||
|
||||
/// Returns `Ok(_)` if `precommit_target` is a descendant of the `commit_target` block and
|
||||
/// `Err(_)` otherwise.
|
||||
pub fn ensure_descendant(
|
||||
mut self,
|
||||
commit_target: &Header::Hash,
|
||||
precommit_target: &Header::Hash,
|
||||
) -> Result<Self, Error> {
|
||||
let mut current_hash = *precommit_target;
|
||||
loop {
|
||||
if current_hash == *commit_target {
|
||||
break
|
||||
}
|
||||
|
||||
let is_visited_before = !self.unvisited.remove(¤t_hash);
|
||||
current_hash = match self.parents.get(¤t_hash) {
|
||||
Some(parent_hash) => {
|
||||
if is_visited_before {
|
||||
// `Some(parent_hash)` means that the `current_hash` is in the `parents`
|
||||
// container `is_visited_before` means that it has been visited before in
|
||||
// some of previous calls => since we assume that previous call has finished
|
||||
// with `true`, this also will be finished with `true`
|
||||
return Ok(self)
|
||||
}
|
||||
|
||||
*parent_hash
|
||||
},
|
||||
None => return Err(Error::PrecommitIsNotCommitDescendant),
|
||||
};
|
||||
}
|
||||
Ok(self)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Parity Bridges Common is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Defines traits which represent a common interface for Substrate pallets which want to
|
||||
//! incorporate bridge functionality.
|
||||
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
use bp_runtime::{
|
||||
BasicOperatingMode, Chain, HashOf, HasherOf, HeaderOf, RawStorageProof, StorageProofChecker,
|
||||
StorageProofError,
|
||||
};
|
||||
use codec::{Codec, Decode, Encode, EncodeLike, MaxEncodedLen};
|
||||
use core::{clone::Clone, cmp::Eq, default::Default, fmt::Debug};
|
||||
use frame_support::PalletError;
|
||||
use scale_info::TypeInfo;
|
||||
#[cfg(feature = "std")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sp_consensus_grandpa::{AuthorityList, ConsensusLog, SetId, GRANDPA_ENGINE_ID};
|
||||
use sp_runtime::{traits::Header as HeaderT, Digest, RuntimeDebug};
|
||||
use sp_std::boxed::Box;
|
||||
|
||||
pub mod justification;
|
||||
pub mod storage_keys;
|
||||
|
||||
/// Header chain error.
|
||||
#[derive(Clone, Decode, Encode, Eq, PartialEq, PalletError, Debug, TypeInfo)]
|
||||
pub enum HeaderChainError {
|
||||
/// Header with given hash is missing from the chain.
|
||||
UnknownHeader,
|
||||
/// Storage proof related error.
|
||||
StorageProof(StorageProofError),
|
||||
}
|
||||
|
||||
/// Header data that we're storing on-chain.
|
||||
///
|
||||
/// Even though we may store full header, our applications (XCM) only use couple of header
|
||||
/// fields. Extracting those values makes on-chain storage and PoV smaller, which is good.
|
||||
#[derive(Clone, Decode, Encode, Eq, MaxEncodedLen, PartialEq, RuntimeDebug, TypeInfo)]
|
||||
pub struct StoredHeaderData<Number, Hash> {
|
||||
/// Header number.
|
||||
pub number: Number,
|
||||
/// Header state root.
|
||||
pub state_root: Hash,
|
||||
}
|
||||
|
||||
/// Stored header data builder.
|
||||
pub trait StoredHeaderDataBuilder<Number, Hash> {
|
||||
/// Build header data from self.
|
||||
fn build(&self) -> StoredHeaderData<Number, Hash>;
|
||||
}
|
||||
|
||||
impl<H: HeaderT> StoredHeaderDataBuilder<H::Number, H::Hash> for H {
|
||||
fn build(&self) -> StoredHeaderData<H::Number, H::Hash> {
|
||||
StoredHeaderData { number: *self.number(), state_root: *self.state_root() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Substrate header chain, abstracted from the way it is stored.
|
||||
pub trait HeaderChain<C: Chain> {
|
||||
/// Returns state (storage) root of given finalized header.
|
||||
fn finalized_header_state_root(header_hash: HashOf<C>) -> Option<HashOf<C>>;
|
||||
/// Parse storage proof using finalized header.
|
||||
fn parse_finalized_storage_proof<R>(
|
||||
header_hash: HashOf<C>,
|
||||
storage_proof: RawStorageProof,
|
||||
parse: impl FnOnce(StorageProofChecker<HasherOf<C>>) -> R,
|
||||
) -> Result<R, HeaderChainError> {
|
||||
let state_root = Self::finalized_header_state_root(header_hash)
|
||||
.ok_or(HeaderChainError::UnknownHeader)?;
|
||||
let storage_proof_checker = bp_runtime::StorageProofChecker::new(state_root, storage_proof)
|
||||
.map_err(HeaderChainError::StorageProof)?;
|
||||
|
||||
Ok(parse(storage_proof_checker))
|
||||
}
|
||||
}
|
||||
|
||||
/// A type that can be used as a parameter in a dispatchable function.
|
||||
///
|
||||
/// When using `decl_module` all arguments for call functions must implement this trait.
|
||||
pub trait Parameter: Codec + EncodeLike + Clone + Eq + Debug + TypeInfo {}
|
||||
impl<T> Parameter for T where T: Codec + EncodeLike + Clone + Eq + Debug + TypeInfo {}
|
||||
|
||||
/// A GRANDPA Authority List and ID.
|
||||
#[derive(Default, Encode, Eq, Decode, RuntimeDebug, PartialEq, Clone, TypeInfo)]
|
||||
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
|
||||
pub struct AuthoritySet {
|
||||
/// List of GRANDPA authorities for the current round.
|
||||
pub authorities: AuthorityList,
|
||||
/// Monotonic identifier of the current GRANDPA authority set.
|
||||
pub set_id: SetId,
|
||||
}
|
||||
|
||||
impl AuthoritySet {
|
||||
/// Create a new GRANDPA Authority Set.
|
||||
pub fn new(authorities: AuthorityList, set_id: SetId) -> Self {
|
||||
Self { authorities, set_id }
|
||||
}
|
||||
}
|
||||
|
||||
/// Data required for initializing the GRANDPA bridge pallet.
|
||||
///
|
||||
/// The bridge needs to know where to start its sync from, and this provides that initial context.
|
||||
#[derive(Default, Encode, Decode, RuntimeDebug, PartialEq, Eq, Clone, TypeInfo)]
|
||||
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
|
||||
pub struct InitializationData<H: HeaderT> {
|
||||
/// The header from which we should start syncing.
|
||||
pub header: Box<H>,
|
||||
/// The initial authorities of the pallet.
|
||||
pub authority_list: AuthorityList,
|
||||
/// The ID of the initial authority set.
|
||||
pub set_id: SetId,
|
||||
/// Pallet operating mode.
|
||||
pub operating_mode: BasicOperatingMode,
|
||||
}
|
||||
|
||||
/// Abstract finality proof that is justifying block finality.
|
||||
pub trait FinalityProof<Number>: Clone + Send + Sync + Debug {
|
||||
/// Return number of header that this proof is generated for.
|
||||
fn target_header_number(&self) -> Number;
|
||||
}
|
||||
|
||||
/// A trait that provides helper methods for querying the consensus log.
|
||||
pub trait ConsensusLogReader {
|
||||
/// Returns true if digest contains item that schedules authorities set change.
|
||||
fn schedules_authorities_change(digest: &Digest) -> bool;
|
||||
}
|
||||
|
||||
/// A struct that provides helper methods for querying the GRANDPA consensus log.
|
||||
pub struct GrandpaConsensusLogReader<Number>(sp_std::marker::PhantomData<Number>);
|
||||
|
||||
impl<Number: Codec> GrandpaConsensusLogReader<Number> {
|
||||
pub fn find_authorities_change(
|
||||
digest: &Digest,
|
||||
) -> Option<sp_consensus_grandpa::ScheduledChange<Number>> {
|
||||
// find the first consensus digest with the right ID which converts to
|
||||
// the right kind of consensus log.
|
||||
digest
|
||||
.convert_first(|log| log.consensus_try_to(&GRANDPA_ENGINE_ID))
|
||||
.and_then(|log| match log {
|
||||
ConsensusLog::ScheduledChange(change) => Some(change),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<Number: Codec> ConsensusLogReader for GrandpaConsensusLogReader<Number> {
|
||||
fn schedules_authorities_change(digest: &Digest) -> bool {
|
||||
GrandpaConsensusLogReader::<Number>::find_authorities_change(digest).is_some()
|
||||
}
|
||||
}
|
||||
|
||||
/// A minimized version of `pallet-bridge-grandpa::Call` that can be used without a runtime.
|
||||
#[derive(Encode, Decode, Debug, PartialEq, Eq, Clone, TypeInfo)]
|
||||
#[allow(non_camel_case_types)]
|
||||
pub enum BridgeGrandpaCall<Header: HeaderT> {
|
||||
/// `pallet-bridge-grandpa::Call::submit_finality_proof`
|
||||
#[codec(index = 0)]
|
||||
submit_finality_proof {
|
||||
finality_target: Box<Header>,
|
||||
justification: justification::GrandpaJustification<Header>,
|
||||
},
|
||||
/// `pallet-bridge-grandpa::Call::initialize`
|
||||
#[codec(index = 1)]
|
||||
initialize { init_data: InitializationData<Header> },
|
||||
}
|
||||
|
||||
/// The `BridgeGrandpaCall` used by a chain.
|
||||
pub type BridgeGrandpaCallOf<C> = BridgeGrandpaCall<HeaderOf<C>>;
|
||||
|
||||
/// Substrate-based chain that is using direct GRANDPA finality.
|
||||
///
|
||||
/// Keep in mind that parachains are relying on relay chain GRANDPA, so they should not implement
|
||||
/// this trait.
|
||||
pub trait ChainWithGrandpa: Chain {
|
||||
/// Name of the bridge GRANDPA pallet (used in `construct_runtime` macro call) that is deployed
|
||||
/// at some other chain to bridge with this `ChainWithGrandpa`.
|
||||
///
|
||||
/// We assume that all chains that are bridging with this `ChainWithGrandpa` are using
|
||||
/// the same name.
|
||||
const WITH_CHAIN_GRANDPA_PALLET_NAME: &'static str;
|
||||
|
||||
/// Max number of GRANDPA authorities at the chain.
|
||||
///
|
||||
/// This is a strict constant. If bridged chain will have more authorities than that,
|
||||
/// the GRANDPA bridge pallet may halt.
|
||||
const MAX_AUTHORITIES_COUNT: u32;
|
||||
|
||||
/// Max reasonable number of headers in `votes_ancestries` vector of the GRANDPA justification.
|
||||
///
|
||||
/// This isn't a strict limit. The relay may submit justifications with more headers in its
|
||||
/// ancestry and the pallet will accept such justification. The limit is only used to compute
|
||||
/// maximal refund amount and submitting justifications which exceed the limit, may be costly
|
||||
/// to submitter.
|
||||
const REASONABLE_HEADERS_IN_JUSTIFICATON_ANCESTRY: u32;
|
||||
|
||||
/// Maximal size of the chain header. The header may be the header that enacts new GRANDPA
|
||||
/// authorities set (so it has large digest inside).
|
||||
///
|
||||
/// This isn't a strict limit. The relay may submit larger headers and the pallet will accept
|
||||
/// the call. The limit is only used to compute maximal refund amount and doing calls which
|
||||
/// exceed the limit, may be costly to submitter.
|
||||
const MAX_HEADER_SIZE: u32;
|
||||
|
||||
/// Average size of the chain header from justification ancestry. We don't expect to see there
|
||||
/// headers that change GRANDPA authorities set (GRANDPA will probably be able to finalize at
|
||||
/// least one additional header per session on non test chains), so this is average size of
|
||||
/// headers that aren't changing the set.
|
||||
///
|
||||
/// This isn't a strict limit. The relay may submit justifications with larger headers in its
|
||||
/// ancestry and the pallet will accept the call. The limit is only used to compute maximal
|
||||
/// refund amount and doing calls which exceed the limit, may be costly to submitter.
|
||||
const AVERAGE_HEADER_SIZE_IN_JUSTIFICATION: u32;
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Parity Bridges Common is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Storage keys of bridge GRANDPA pallet.
|
||||
|
||||
/// Name of the `IsHalted` storage value.
|
||||
pub const PALLET_OPERATING_MODE_VALUE_NAME: &str = "PalletOperatingMode";
|
||||
/// Name of the `BestFinalized` storage value.
|
||||
pub const BEST_FINALIZED_VALUE_NAME: &str = "BestFinalized";
|
||||
/// Name of the `CurrentAuthoritySet` storage value.
|
||||
pub const CURRENT_AUTHORITY_SET_VALUE_NAME: &str = "CurrentAuthoritySet";
|
||||
|
||||
use sp_core::storage::StorageKey;
|
||||
|
||||
/// Storage key of the `PalletOperatingMode` variable in the runtime storage.
|
||||
pub fn pallet_operating_mode_key(pallet_prefix: &str) -> StorageKey {
|
||||
StorageKey(
|
||||
bp_runtime::storage_value_final_key(
|
||||
pallet_prefix.as_bytes(),
|
||||
PALLET_OPERATING_MODE_VALUE_NAME.as_bytes(),
|
||||
)
|
||||
.to_vec(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Storage key of the `CurrentAuthoritySet` variable in the runtime storage.
|
||||
pub fn current_authority_set_key(pallet_prefix: &str) -> StorageKey {
|
||||
StorageKey(
|
||||
bp_runtime::storage_value_final_key(
|
||||
pallet_prefix.as_bytes(),
|
||||
CURRENT_AUTHORITY_SET_VALUE_NAME.as_bytes(),
|
||||
)
|
||||
.to_vec(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Storage key of the best finalized header number and hash value in the runtime storage.
|
||||
pub fn best_finalized_key(pallet_prefix: &str) -> StorageKey {
|
||||
StorageKey(
|
||||
bp_runtime::storage_value_final_key(
|
||||
pallet_prefix.as_bytes(),
|
||||
BEST_FINALIZED_VALUE_NAME.as_bytes(),
|
||||
)
|
||||
.to_vec(),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use hex_literal::hex;
|
||||
|
||||
#[test]
|
||||
fn pallet_operating_mode_key_computed_properly() {
|
||||
// If this test fails, then something has been changed in module storage that is breaking
|
||||
// compatibility with previous pallet.
|
||||
let storage_key = pallet_operating_mode_key("BridgeGrandpa").0;
|
||||
assert_eq!(
|
||||
storage_key,
|
||||
hex!("0b06f475eddb98cf933a12262e0388de0f4cf0917788d791142ff6c1f216e7b3").to_vec(),
|
||||
"Unexpected storage key: {}",
|
||||
hex::encode(&storage_key),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn current_authority_set_key_computed_properly() {
|
||||
// If this test fails, then something has been changed in module storage that is breaking
|
||||
// compatibility with previous pallet.
|
||||
let storage_key = current_authority_set_key("BridgeGrandpa").0;
|
||||
assert_eq!(
|
||||
storage_key,
|
||||
hex!("0b06f475eddb98cf933a12262e0388de24a7b8b5717ea33346fa595a66ccbcb0").to_vec(),
|
||||
"Unexpected storage key: {}",
|
||||
hex::encode(&storage_key),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn best_finalized_key_computed_properly() {
|
||||
// If this test fails, then something has been changed in module storage that is breaking
|
||||
// compatibility with previous pallet.
|
||||
let storage_key = best_finalized_key("BridgeGrandpa").0;
|
||||
assert_eq!(
|
||||
storage_key,
|
||||
hex!("0b06f475eddb98cf933a12262e0388dea4ebafdd473c549fdb24c5c991c5591c").to_vec(),
|
||||
"Unexpected storage key: {}",
|
||||
hex::encode(&storage_key),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,418 @@
|
||||
// Copyright 2020-2021 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Parity Bridges Common is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Tests inside this module are made to ensure that our custom justification verification
|
||||
//! implementation works similar to the [`finality_grandpa::validate_commit`] and explicitly
|
||||
//! show where we behave different.
|
||||
//!
|
||||
//! Some of tests in this module may partially duplicate tests from `justification.rs`,
|
||||
//! but their purpose is different.
|
||||
|
||||
use bp_header_chain::justification::{verify_justification, Error, GrandpaJustification};
|
||||
use bp_test_utils::{
|
||||
header_id, make_justification_for_header, signed_precommit, test_header, Account,
|
||||
JustificationGeneratorParams, ALICE, BOB, CHARLIE, DAVE, EVE, FERDIE, TEST_GRANDPA_SET_ID,
|
||||
};
|
||||
use finality_grandpa::voter_set::VoterSet;
|
||||
use sp_consensus_grandpa::{AuthorityId, AuthorityWeight};
|
||||
use sp_runtime::traits::Header as HeaderT;
|
||||
|
||||
type TestHeader = sp_runtime::testing::Header;
|
||||
type TestHash = <TestHeader as HeaderT>::Hash;
|
||||
type TestNumber = <TestHeader as HeaderT>::Number;
|
||||
|
||||
/// Implementation of `finality_grandpa::Chain` that is used in tests.
|
||||
struct AncestryChain(bp_header_chain::justification::AncestryChain<TestHeader>);
|
||||
|
||||
impl AncestryChain {
|
||||
fn new(ancestry: &[TestHeader]) -> Self {
|
||||
Self(bp_header_chain::justification::AncestryChain::new(ancestry))
|
||||
}
|
||||
}
|
||||
|
||||
impl finality_grandpa::Chain<TestHash, TestNumber> for AncestryChain {
|
||||
fn ancestry(
|
||||
&self,
|
||||
base: TestHash,
|
||||
block: TestHash,
|
||||
) -> Result<Vec<TestHash>, finality_grandpa::Error> {
|
||||
let mut route = Vec::new();
|
||||
let mut current_hash = block;
|
||||
loop {
|
||||
if current_hash == base {
|
||||
break
|
||||
}
|
||||
match self.0.parents.get(¤t_hash).cloned() {
|
||||
Some(parent_hash) => {
|
||||
current_hash = parent_hash;
|
||||
route.push(current_hash);
|
||||
},
|
||||
_ => return Err(finality_grandpa::Error::NotDescendent),
|
||||
}
|
||||
}
|
||||
route.pop(); // remove the base
|
||||
|
||||
Ok(route)
|
||||
}
|
||||
}
|
||||
|
||||
/// Get a full set of accounts.
|
||||
fn full_accounts_set() -> Vec<(Account, AuthorityWeight)> {
|
||||
vec![(ALICE, 1), (BOB, 1), (CHARLIE, 1), (DAVE, 1), (EVE, 1)]
|
||||
}
|
||||
|
||||
/// Get a full set of GRANDPA authorities.
|
||||
fn full_voter_set() -> VoterSet<AuthorityId> {
|
||||
VoterSet::new(full_accounts_set().iter().map(|(id, w)| (AuthorityId::from(*id), *w))).unwrap()
|
||||
}
|
||||
|
||||
/// Get a minimal set of accounts.
|
||||
fn minimal_accounts_set() -> Vec<(Account, AuthorityWeight)> {
|
||||
// there are 5 accounts in the full set => we need 2/3 + 1 accounts, which results in 4 accounts
|
||||
vec![(ALICE, 1), (BOB, 1), (CHARLIE, 1), (DAVE, 1)]
|
||||
}
|
||||
|
||||
/// Get a minimal subset of GRANDPA authorities that have enough cumulative vote weight to justify a
|
||||
/// header finality.
|
||||
pub fn minimal_voter_set() -> VoterSet<AuthorityId> {
|
||||
VoterSet::new(minimal_accounts_set().iter().map(|(id, w)| (AuthorityId::from(*id), *w)))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Make a valid GRANDPA justification with sensible defaults.
|
||||
pub fn make_default_justification(header: &TestHeader) -> GrandpaJustification<TestHeader> {
|
||||
make_justification_for_header(JustificationGeneratorParams {
|
||||
header: header.clone(),
|
||||
authorities: minimal_accounts_set(),
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
|
||||
// the `finality_grandpa::validate_commit` function has two ways to report an unsuccessful
|
||||
// commit validation:
|
||||
//
|
||||
// 1) to return `Err()` (which only may happen if `finality_grandpa::Chain` implementation
|
||||
// returns an error);
|
||||
// 2) to return `Ok(validation_result)` if `validation_result.is_valid()` is false.
|
||||
//
|
||||
// Our implementation would just return error in both cases.
|
||||
|
||||
#[test]
|
||||
fn same_result_when_precommit_target_has_lower_number_than_commit_target() {
|
||||
let mut justification = make_default_justification(&test_header(1));
|
||||
// the number of header in precommit (0) is lower than number of header in commit (1)
|
||||
justification.commit.precommits[0].precommit.target_number = 0;
|
||||
|
||||
// our implementation returns an error
|
||||
assert_eq!(
|
||||
verify_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(1),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&full_voter_set(),
|
||||
&justification,
|
||||
),
|
||||
Err(Error::PrecommitIsNotCommitDescendant),
|
||||
);
|
||||
|
||||
// original implementation returns `Ok(validation_result)`
|
||||
// with `validation_result.is_valid() == false`.
|
||||
let result = finality_grandpa::validate_commit(
|
||||
&justification.commit,
|
||||
&full_voter_set(),
|
||||
&AncestryChain::new(&justification.votes_ancestries),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert!(!result.is_valid());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_result_when_precommit_target_is_not_descendant_of_commit_target() {
|
||||
let not_descendant = test_header::<TestHeader>(10);
|
||||
let mut justification = make_default_justification(&test_header(1));
|
||||
// the route from header of commit (1) to header of precommit (10) is missing from
|
||||
// the votes ancestries
|
||||
justification.commit.precommits[0].precommit.target_number = *not_descendant.number();
|
||||
justification.commit.precommits[0].precommit.target_hash = not_descendant.hash();
|
||||
justification.votes_ancestries.push(not_descendant);
|
||||
|
||||
// our implementation returns an error
|
||||
assert_eq!(
|
||||
verify_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(1),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&full_voter_set(),
|
||||
&justification,
|
||||
),
|
||||
Err(Error::PrecommitIsNotCommitDescendant),
|
||||
);
|
||||
|
||||
// original implementation returns `Ok(validation_result)`
|
||||
// with `validation_result.is_valid() == false`.
|
||||
let result = finality_grandpa::validate_commit(
|
||||
&justification.commit,
|
||||
&full_voter_set(),
|
||||
&AncestryChain::new(&justification.votes_ancestries),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert!(!result.is_valid());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_result_when_there_are_not_enough_cumulative_weight_to_finalize_commit_target() {
|
||||
// just remove one authority from the minimal set and we shall not reach the threshold
|
||||
let mut authorities_set = minimal_accounts_set();
|
||||
authorities_set.pop();
|
||||
let justification = make_justification_for_header(JustificationGeneratorParams {
|
||||
header: test_header(1),
|
||||
authorities: authorities_set,
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
// our implementation returns an error
|
||||
assert_eq!(
|
||||
verify_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(1),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&full_voter_set(),
|
||||
&justification,
|
||||
),
|
||||
Err(Error::TooLowCumulativeWeight),
|
||||
);
|
||||
// original implementation returns `Ok(validation_result)`
|
||||
// with `validation_result.is_valid() == false`.
|
||||
let result = finality_grandpa::validate_commit(
|
||||
&justification.commit,
|
||||
&full_voter_set(),
|
||||
&AncestryChain::new(&justification.votes_ancestries),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert!(!result.is_valid());
|
||||
}
|
||||
|
||||
// tests below are our differences with the original implementation
|
||||
|
||||
#[test]
|
||||
fn different_result_when_justification_contains_duplicate_vote() {
|
||||
let mut justification = make_justification_for_header(JustificationGeneratorParams {
|
||||
header: test_header(1),
|
||||
authorities: minimal_accounts_set(),
|
||||
ancestors: 0,
|
||||
..Default::default()
|
||||
});
|
||||
// the justification may contain exactly the same vote (i.e. same precommit and same signature)
|
||||
// multiple times && it isn't treated as an error by original implementation
|
||||
let last_precommit = justification.commit.precommits.pop().unwrap();
|
||||
justification.commit.precommits.push(justification.commit.precommits[0].clone());
|
||||
justification.commit.precommits.push(last_precommit);
|
||||
|
||||
// our implementation fails
|
||||
assert_eq!(
|
||||
verify_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(1),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&full_voter_set(),
|
||||
&justification,
|
||||
),
|
||||
Err(Error::DuplicateAuthorityVote),
|
||||
);
|
||||
// original implementation returns `Ok(validation_result)`
|
||||
// with `validation_result.is_valid() == true`.
|
||||
let result = finality_grandpa::validate_commit(
|
||||
&justification.commit,
|
||||
&full_voter_set(),
|
||||
&AncestryChain::new(&justification.votes_ancestries),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert!(result.is_valid());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn different_results_when_authority_equivocates_once_in_a_round() {
|
||||
let mut justification = make_justification_for_header(JustificationGeneratorParams {
|
||||
header: test_header(1),
|
||||
authorities: minimal_accounts_set(),
|
||||
ancestors: 0,
|
||||
..Default::default()
|
||||
});
|
||||
// the justification original implementation allows authority to submit two different
|
||||
// votes in a single round, of which only first is 'accepted'
|
||||
let last_precommit = justification.commit.precommits.pop().unwrap();
|
||||
justification.commit.precommits.push(signed_precommit::<TestHeader>(
|
||||
&ALICE,
|
||||
header_id::<TestHeader>(1),
|
||||
justification.round,
|
||||
TEST_GRANDPA_SET_ID,
|
||||
));
|
||||
justification.commit.precommits.push(last_precommit);
|
||||
|
||||
// our implementation fails
|
||||
assert_eq!(
|
||||
verify_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(1),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&full_voter_set(),
|
||||
&justification,
|
||||
),
|
||||
Err(Error::DuplicateAuthorityVote),
|
||||
);
|
||||
// original implementation returns `Ok(validation_result)`
|
||||
// with `validation_result.is_valid() == true`.
|
||||
let result = finality_grandpa::validate_commit(
|
||||
&justification.commit,
|
||||
&full_voter_set(),
|
||||
&AncestryChain::new(&justification.votes_ancestries),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert!(result.is_valid());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn different_results_when_authority_equivocates_twice_in_a_round() {
|
||||
let mut justification = make_justification_for_header(JustificationGeneratorParams {
|
||||
header: test_header(1),
|
||||
authorities: minimal_accounts_set(),
|
||||
ancestors: 0,
|
||||
..Default::default()
|
||||
});
|
||||
// there's some code in the original implementation that should return an error when
|
||||
// same authority submits more than two different votes in a single round:
|
||||
// https://github.com/paritytech/finality-grandpa/blob/6aeea2d1159d0f418f0b86e70739f2130629ca09/src/lib.rs#L473
|
||||
// but there's also a code that prevents this from happening:
|
||||
// https://github.com/paritytech/finality-grandpa/blob/6aeea2d1159d0f418f0b86e70739f2130629ca09/src/round.rs#L287
|
||||
// => so now we are also just ignoring all votes from the same authority, except the first one
|
||||
let last_precommit = justification.commit.precommits.pop().unwrap();
|
||||
let prev_last_precommit = justification.commit.precommits.pop().unwrap();
|
||||
justification.commit.precommits.push(signed_precommit::<TestHeader>(
|
||||
&ALICE,
|
||||
header_id::<TestHeader>(1),
|
||||
justification.round,
|
||||
TEST_GRANDPA_SET_ID,
|
||||
));
|
||||
justification.commit.precommits.push(signed_precommit::<TestHeader>(
|
||||
&ALICE,
|
||||
header_id::<TestHeader>(1),
|
||||
justification.round,
|
||||
TEST_GRANDPA_SET_ID,
|
||||
));
|
||||
justification.commit.precommits.push(last_precommit);
|
||||
justification.commit.precommits.push(prev_last_precommit);
|
||||
|
||||
// our implementation fails
|
||||
assert_eq!(
|
||||
verify_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(1),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&full_voter_set(),
|
||||
&justification,
|
||||
),
|
||||
Err(Error::DuplicateAuthorityVote),
|
||||
);
|
||||
// original implementation returns `Ok(validation_result)`
|
||||
// with `validation_result.is_valid() == true`.
|
||||
let result = finality_grandpa::validate_commit(
|
||||
&justification.commit,
|
||||
&full_voter_set(),
|
||||
&AncestryChain::new(&justification.votes_ancestries),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert!(result.is_valid());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn different_results_when_there_are_more_than_enough_votes() {
|
||||
let mut justification = make_justification_for_header(JustificationGeneratorParams {
|
||||
header: test_header(1),
|
||||
authorities: minimal_accounts_set(),
|
||||
ancestors: 0,
|
||||
..Default::default()
|
||||
});
|
||||
// the reference implementation just keep verifying signatures even if we have
|
||||
// collected enough votes. We are not
|
||||
justification.commit.precommits.push(signed_precommit::<TestHeader>(
|
||||
&EVE,
|
||||
header_id::<TestHeader>(1),
|
||||
justification.round,
|
||||
TEST_GRANDPA_SET_ID,
|
||||
));
|
||||
|
||||
// our implementation fails
|
||||
assert_eq!(
|
||||
verify_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(1),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&full_voter_set(),
|
||||
&justification,
|
||||
),
|
||||
Err(Error::RedundantVotesInJustification),
|
||||
);
|
||||
// original implementation returns `Ok(validation_result)`
|
||||
// with `validation_result.is_valid() == true`.
|
||||
let result = finality_grandpa::validate_commit(
|
||||
&justification.commit,
|
||||
&full_voter_set(),
|
||||
&AncestryChain::new(&justification.votes_ancestries),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert!(result.is_valid());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn different_results_when_there_is_a_vote_of_unknown_authority() {
|
||||
let mut justification = make_justification_for_header(JustificationGeneratorParams {
|
||||
header: test_header(1),
|
||||
authorities: minimal_accounts_set(),
|
||||
ancestors: 0,
|
||||
..Default::default()
|
||||
});
|
||||
// the reference implementation just keep verifying signatures even if we have
|
||||
// collected enough votes. We are not
|
||||
let last_precommit = justification.commit.precommits.pop().unwrap();
|
||||
justification.commit.precommits.push(signed_precommit::<TestHeader>(
|
||||
&FERDIE,
|
||||
header_id::<TestHeader>(1),
|
||||
justification.round,
|
||||
TEST_GRANDPA_SET_ID,
|
||||
));
|
||||
justification.commit.precommits.push(last_precommit);
|
||||
|
||||
// our implementation fails
|
||||
assert_eq!(
|
||||
verify_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(1),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&full_voter_set(),
|
||||
&justification,
|
||||
),
|
||||
Err(Error::UnknownAuthorityVote),
|
||||
);
|
||||
// original implementation returns `Ok(validation_result)`
|
||||
// with `validation_result.is_valid() == true`.
|
||||
let result = finality_grandpa::validate_commit(
|
||||
&justification.commit,
|
||||
&full_voter_set(),
|
||||
&AncestryChain::new(&justification.votes_ancestries),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert!(result.is_valid());
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
// Copyright 2020-2021 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Parity Bridges Common is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Tests for Grandpa Justification code.
|
||||
|
||||
use bp_header_chain::justification::{
|
||||
required_justification_precommits, verify_and_optimize_justification, verify_justification,
|
||||
Error,
|
||||
};
|
||||
use bp_test_utils::*;
|
||||
|
||||
type TestHeader = sp_runtime::testing::Header;
|
||||
|
||||
#[test]
|
||||
fn valid_justification_accepted() {
|
||||
let authorities = vec![(ALICE, 1), (BOB, 1), (CHARLIE, 1)];
|
||||
let params = JustificationGeneratorParams {
|
||||
header: test_header(1),
|
||||
round: TEST_GRANDPA_ROUND,
|
||||
set_id: TEST_GRANDPA_SET_ID,
|
||||
authorities: authorities.clone(),
|
||||
ancestors: 7,
|
||||
forks: 3,
|
||||
};
|
||||
|
||||
let justification = make_justification_for_header::<TestHeader>(params.clone());
|
||||
assert_eq!(
|
||||
verify_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(1),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&voter_set(),
|
||||
&justification,
|
||||
),
|
||||
Ok(()),
|
||||
);
|
||||
|
||||
assert_eq!(justification.commit.precommits.len(), authorities.len());
|
||||
assert_eq!(justification.votes_ancestries.len(), params.ancestors as usize);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_justification_accepted_with_single_fork() {
|
||||
let params = JustificationGeneratorParams {
|
||||
header: test_header(1),
|
||||
round: TEST_GRANDPA_ROUND,
|
||||
set_id: TEST_GRANDPA_SET_ID,
|
||||
authorities: vec![(ALICE, 1), (BOB, 1), (CHARLIE, 1)],
|
||||
ancestors: 5,
|
||||
forks: 1,
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
verify_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(1),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&voter_set(),
|
||||
&make_justification_for_header::<TestHeader>(params)
|
||||
),
|
||||
Ok(()),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_justification_accepted_with_arbitrary_number_of_authorities() {
|
||||
use finality_grandpa::voter_set::VoterSet;
|
||||
use sp_consensus_grandpa::AuthorityId;
|
||||
|
||||
let n = 15;
|
||||
let required_signatures = required_justification_precommits(n as _);
|
||||
let authorities = accounts(n).iter().map(|k| (*k, 1)).collect::<Vec<_>>();
|
||||
|
||||
let params = JustificationGeneratorParams {
|
||||
header: test_header(1),
|
||||
round: TEST_GRANDPA_ROUND,
|
||||
set_id: TEST_GRANDPA_SET_ID,
|
||||
authorities: authorities.clone().into_iter().take(required_signatures as _).collect(),
|
||||
ancestors: n.into(),
|
||||
forks: required_signatures,
|
||||
};
|
||||
|
||||
let authorities = authorities
|
||||
.iter()
|
||||
.map(|(id, w)| (AuthorityId::from(*id), *w))
|
||||
.collect::<Vec<(AuthorityId, _)>>();
|
||||
let voter_set = VoterSet::new(authorities).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
verify_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(1),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&voter_set,
|
||||
&make_justification_for_header::<TestHeader>(params)
|
||||
),
|
||||
Ok(()),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn justification_with_invalid_target_rejected() {
|
||||
assert_eq!(
|
||||
verify_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(2),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&voter_set(),
|
||||
&make_default_justification::<TestHeader>(&test_header(1)),
|
||||
),
|
||||
Err(Error::InvalidJustificationTarget),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn justification_with_invalid_commit_rejected() {
|
||||
let mut justification = make_default_justification::<TestHeader>(&test_header(1));
|
||||
justification.commit.precommits.clear();
|
||||
|
||||
assert_eq!(
|
||||
verify_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(1),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&voter_set(),
|
||||
&justification,
|
||||
),
|
||||
Err(Error::ExtraHeadersInVotesAncestries),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn justification_with_invalid_authority_signature_rejected() {
|
||||
let mut justification = make_default_justification::<TestHeader>(&test_header(1));
|
||||
justification.commit.precommits[0].signature =
|
||||
sp_core::crypto::UncheckedFrom::unchecked_from([1u8; 64]);
|
||||
|
||||
assert_eq!(
|
||||
verify_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(1),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&voter_set(),
|
||||
&justification,
|
||||
),
|
||||
Err(Error::InvalidAuthoritySignature),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn justification_with_invalid_precommit_ancestry() {
|
||||
let mut justification = make_default_justification::<TestHeader>(&test_header(1));
|
||||
justification.votes_ancestries.push(test_header(10));
|
||||
|
||||
assert_eq!(
|
||||
verify_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(1),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&voter_set(),
|
||||
&justification,
|
||||
),
|
||||
Err(Error::ExtraHeadersInVotesAncestries),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn justification_is_invalid_if_we_dont_meet_threshold() {
|
||||
// Need at least three authorities to sign off or else the voter set threshold can't be reached
|
||||
let authorities = vec![(ALICE, 1), (BOB, 1)];
|
||||
|
||||
let params = JustificationGeneratorParams {
|
||||
header: test_header(1),
|
||||
round: TEST_GRANDPA_ROUND,
|
||||
set_id: TEST_GRANDPA_SET_ID,
|
||||
authorities: authorities.clone(),
|
||||
ancestors: 2 * authorities.len() as u32,
|
||||
forks: 2,
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
verify_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(1),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&voter_set(),
|
||||
&make_justification_for_header::<TestHeader>(params)
|
||||
),
|
||||
Err(Error::TooLowCumulativeWeight),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optimizer_does_noting_with_minimal_justification() {
|
||||
let justification = make_default_justification::<TestHeader>(&test_header(1));
|
||||
|
||||
let num_precommits_before = justification.commit.precommits.len();
|
||||
let justification = verify_and_optimize_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(1),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&voter_set(),
|
||||
justification,
|
||||
)
|
||||
.unwrap();
|
||||
let num_precommits_after = justification.commit.precommits.len();
|
||||
|
||||
assert_eq!(num_precommits_before, num_precommits_after);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_authority_votes_are_removed_by_optimizer() {
|
||||
let mut justification = make_default_justification::<TestHeader>(&test_header(1));
|
||||
justification.commit.precommits.push(signed_precommit::<TestHeader>(
|
||||
&bp_test_utils::Account(42),
|
||||
header_id::<TestHeader>(1),
|
||||
justification.round,
|
||||
TEST_GRANDPA_SET_ID,
|
||||
));
|
||||
|
||||
let num_precommits_before = justification.commit.precommits.len();
|
||||
let justification = verify_and_optimize_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(1),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&voter_set(),
|
||||
justification,
|
||||
)
|
||||
.unwrap();
|
||||
let num_precommits_after = justification.commit.precommits.len();
|
||||
|
||||
assert_eq!(num_precommits_before - 1, num_precommits_after);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_authority_votes_are_removed_by_optimizer() {
|
||||
let mut justification = make_default_justification::<TestHeader>(&test_header(1));
|
||||
justification
|
||||
.commit
|
||||
.precommits
|
||||
.push(justification.commit.precommits.first().cloned().unwrap());
|
||||
|
||||
let num_precommits_before = justification.commit.precommits.len();
|
||||
let justification = verify_and_optimize_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(1),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&voter_set(),
|
||||
justification,
|
||||
)
|
||||
.unwrap();
|
||||
let num_precommits_after = justification.commit.precommits.len();
|
||||
|
||||
assert_eq!(num_precommits_before - 1, num_precommits_after);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redundant_authority_votes_are_removed_by_optimizer() {
|
||||
let mut justification = make_default_justification::<TestHeader>(&test_header(1));
|
||||
justification.commit.precommits.push(signed_precommit::<TestHeader>(
|
||||
&EVE,
|
||||
header_id::<TestHeader>(1),
|
||||
justification.round,
|
||||
TEST_GRANDPA_SET_ID,
|
||||
));
|
||||
|
||||
let num_precommits_before = justification.commit.precommits.len();
|
||||
let justification = verify_and_optimize_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(1),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&voter_set(),
|
||||
justification,
|
||||
)
|
||||
.unwrap();
|
||||
let num_precommits_after = justification.commit.precommits.len();
|
||||
|
||||
assert_eq!(num_precommits_before - 1, num_precommits_after);
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
[package]
|
||||
name = "bp-messages"
|
||||
description = "Primitives of messages module."
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2021"
|
||||
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
|
||||
|
||||
[dependencies]
|
||||
codec = { package = "parity-scale-codec", version = "3.1.5", default-features = false, features = ["derive", "bit-vec"] }
|
||||
scale-info = { version = "2.6.0", default-features = false, features = ["bit-vec", "derive"] }
|
||||
serde = { version = "1.0", optional = true, features = ["derive"] }
|
||||
|
||||
# Bridge dependencies
|
||||
|
||||
bp-runtime = { path = "../runtime", default-features = false }
|
||||
|
||||
# Substrate Dependencies
|
||||
|
||||
frame-support = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-core = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-std = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
|
||||
[dev-dependencies]
|
||||
hex = "0.4"
|
||||
hex-literal = "0.4"
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"bp-runtime/std",
|
||||
"codec/std",
|
||||
"frame-support/std",
|
||||
"scale-info/std",
|
||||
"serde",
|
||||
"sp-core/std",
|
||||
"sp-std/std"
|
||||
]
|
||||
@@ -0,0 +1,484 @@
|
||||
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Parity Bridges Common is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Primitives of messages module.
|
||||
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
// RuntimeApi generated functions
|
||||
#![allow(clippy::too_many_arguments)]
|
||||
|
||||
use bp_runtime::{BasicOperatingMode, OperatingMode, RangeInclusiveExt};
|
||||
use codec::{Decode, Encode, MaxEncodedLen};
|
||||
use frame_support::RuntimeDebug;
|
||||
use scale_info::TypeInfo;
|
||||
use source_chain::RelayersRewards;
|
||||
use sp_core::TypeId;
|
||||
use sp_std::{collections::vec_deque::VecDeque, ops::RangeInclusive, prelude::*};
|
||||
|
||||
pub mod source_chain;
|
||||
pub mod storage_keys;
|
||||
pub mod target_chain;
|
||||
|
||||
use bp_runtime::messages::MessageDispatchResult;
|
||||
// Weight is reexported to avoid additional frame-support dependencies in related crates.
|
||||
pub use frame_support::weights::Weight;
|
||||
|
||||
/// Messages pallet operating mode.
|
||||
#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)]
|
||||
#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub enum MessagesOperatingMode {
|
||||
/// Basic operating mode (Normal/Halted)
|
||||
Basic(BasicOperatingMode),
|
||||
/// The pallet is not accepting outbound messages. Inbound messages and receiving proofs
|
||||
/// are still accepted.
|
||||
///
|
||||
/// This mode may be used e.g. when bridged chain expects upgrade. Then to avoid dispatch
|
||||
/// failures, the pallet owner may stop accepting new messages, while continuing to deliver
|
||||
/// queued messages to the bridged chain. Once upgrade is completed, the mode may be switched
|
||||
/// back to `Normal`.
|
||||
RejectingOutboundMessages,
|
||||
}
|
||||
|
||||
impl Default for MessagesOperatingMode {
|
||||
fn default() -> Self {
|
||||
MessagesOperatingMode::Basic(BasicOperatingMode::Normal)
|
||||
}
|
||||
}
|
||||
|
||||
impl OperatingMode for MessagesOperatingMode {
|
||||
fn is_halted(&self) -> bool {
|
||||
match self {
|
||||
Self::Basic(operating_mode) => operating_mode.is_halted(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Lane id which implements `TypeId`.
|
||||
#[derive(
|
||||
Clone, Copy, Decode, Default, Encode, Eq, Ord, PartialOrd, PartialEq, TypeInfo, MaxEncodedLen,
|
||||
)]
|
||||
pub struct LaneId(pub [u8; 4]);
|
||||
|
||||
impl core::fmt::Debug for LaneId {
|
||||
fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
|
||||
self.0.fmt(fmt)
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<[u8]> for LaneId {
|
||||
fn as_ref(&self) -> &[u8] {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl TypeId for LaneId {
|
||||
const TYPE_ID: [u8; 4] = *b"blan";
|
||||
}
|
||||
|
||||
/// Message nonce. Valid messages will never have 0 nonce.
|
||||
pub type MessageNonce = u64;
|
||||
|
||||
/// Message id as a tuple.
|
||||
pub type BridgeMessageId = (LaneId, MessageNonce);
|
||||
|
||||
/// Opaque message payload. We only decode this payload when it is dispatched.
|
||||
pub type MessagePayload = Vec<u8>;
|
||||
|
||||
/// Message key (unique message identifier) as it is stored in the storage.
|
||||
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)]
|
||||
pub struct MessageKey {
|
||||
/// ID of the message lane.
|
||||
pub lane_id: LaneId,
|
||||
/// Message nonce.
|
||||
pub nonce: MessageNonce,
|
||||
}
|
||||
|
||||
/// Message as it is stored in the storage.
|
||||
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
|
||||
pub struct Message {
|
||||
/// Message key.
|
||||
pub key: MessageKey,
|
||||
/// Message payload.
|
||||
pub payload: MessagePayload,
|
||||
}
|
||||
|
||||
/// Inbound lane data.
|
||||
#[derive(Encode, Decode, Clone, RuntimeDebug, PartialEq, Eq, TypeInfo)]
|
||||
pub struct InboundLaneData<RelayerId> {
|
||||
/// Identifiers of relayers and messages that they have delivered to this lane (ordered by
|
||||
/// message nonce).
|
||||
///
|
||||
/// This serves as a helper storage item, to allow the source chain to easily pay rewards
|
||||
/// to the relayers who successfully delivered messages to the target chain (inbound lane).
|
||||
///
|
||||
/// It is guaranteed to have at most N entries, where N is configured at the module level.
|
||||
/// If there are N entries in this vec, then:
|
||||
/// 1) all incoming messages are rejected if they're missing corresponding
|
||||
/// `proof-of(outbound-lane.state)`; 2) all incoming messages are rejected if
|
||||
/// `proof-of(outbound-lane.state).last_delivered_nonce` is equal to
|
||||
/// `self.last_confirmed_nonce`. Given what is said above, all nonces in this queue are in
|
||||
/// range: `(self.last_confirmed_nonce; self.last_delivered_nonce()]`.
|
||||
///
|
||||
/// When a relayer sends a single message, both of MessageNonces are the same.
|
||||
/// When relayer sends messages in a batch, the first arg is the lowest nonce, second arg the
|
||||
/// highest nonce. Multiple dispatches from the same relayer are allowed.
|
||||
pub relayers: VecDeque<UnrewardedRelayer<RelayerId>>,
|
||||
|
||||
/// Nonce of the last message that
|
||||
/// a) has been delivered to the target (this) chain and
|
||||
/// b) the delivery has been confirmed on the source chain
|
||||
///
|
||||
/// that the target chain knows of.
|
||||
///
|
||||
/// This value is updated indirectly when an `OutboundLane` state of the source
|
||||
/// chain is received alongside with new messages delivery.
|
||||
pub last_confirmed_nonce: MessageNonce,
|
||||
}
|
||||
|
||||
impl<RelayerId> Default for InboundLaneData<RelayerId> {
|
||||
fn default() -> Self {
|
||||
InboundLaneData { relayers: VecDeque::new(), last_confirmed_nonce: 0 }
|
||||
}
|
||||
}
|
||||
|
||||
impl<RelayerId> InboundLaneData<RelayerId> {
|
||||
/// Returns approximate size of the struct, given a number of entries in the `relayers` set and
|
||||
/// size of each entry.
|
||||
///
|
||||
/// Returns `None` if size overflows `usize` limits.
|
||||
pub fn encoded_size_hint(relayers_entries: usize) -> Option<usize>
|
||||
where
|
||||
RelayerId: MaxEncodedLen,
|
||||
{
|
||||
relayers_entries
|
||||
.checked_mul(UnrewardedRelayer::<RelayerId>::max_encoded_len())?
|
||||
.checked_add(MessageNonce::max_encoded_len())
|
||||
}
|
||||
|
||||
/// Returns the approximate size of the struct as u32, given a number of entries in the
|
||||
/// `relayers` set and the size of each entry.
|
||||
///
|
||||
/// Returns `u32::MAX` if size overflows `u32` limits.
|
||||
pub fn encoded_size_hint_u32(relayers_entries: usize) -> u32
|
||||
where
|
||||
RelayerId: MaxEncodedLen,
|
||||
{
|
||||
Self::encoded_size_hint(relayers_entries)
|
||||
.and_then(|x| u32::try_from(x).ok())
|
||||
.unwrap_or(u32::MAX)
|
||||
}
|
||||
|
||||
/// Nonce of the last message that has been delivered to this (target) chain.
|
||||
pub fn last_delivered_nonce(&self) -> MessageNonce {
|
||||
self.relayers
|
||||
.back()
|
||||
.map(|entry| entry.messages.end)
|
||||
.unwrap_or(self.last_confirmed_nonce)
|
||||
}
|
||||
}
|
||||
|
||||
/// Outbound message details, returned by runtime APIs.
|
||||
#[derive(Clone, Encode, Decode, RuntimeDebug, PartialEq, Eq, TypeInfo)]
|
||||
pub struct OutboundMessageDetails {
|
||||
/// Nonce assigned to the message.
|
||||
pub nonce: MessageNonce,
|
||||
/// Message dispatch weight.
|
||||
///
|
||||
/// Depending on messages pallet configuration, it may be declared by the message submitter,
|
||||
/// computed automatically or just be zero if dispatch fee is paid at the target chain.
|
||||
pub dispatch_weight: Weight,
|
||||
/// Size of the encoded message.
|
||||
pub size: u32,
|
||||
}
|
||||
|
||||
/// Inbound message details, returned by runtime APIs.
|
||||
#[derive(Clone, Encode, Decode, RuntimeDebug, PartialEq, Eq, TypeInfo)]
|
||||
pub struct InboundMessageDetails {
|
||||
/// Computed message dispatch weight.
|
||||
///
|
||||
/// Runtime API guarantees that it will match the value, returned by
|
||||
/// `target_chain::MessageDispatch::dispatch_weight`. This means that if the runtime
|
||||
/// has failed to decode the message, it will be zero - that's because `undecodable`
|
||||
/// message cannot be dispatched.
|
||||
pub dispatch_weight: Weight,
|
||||
}
|
||||
|
||||
/// Unrewarded relayer entry stored in the inbound lane data.
|
||||
///
|
||||
/// This struct represents a continuous range of messages that have been delivered by the same
|
||||
/// relayer and whose confirmations are still pending.
|
||||
#[derive(Encode, Decode, Clone, RuntimeDebug, PartialEq, Eq, TypeInfo, MaxEncodedLen)]
|
||||
pub struct UnrewardedRelayer<RelayerId> {
|
||||
/// Identifier of the relayer.
|
||||
pub relayer: RelayerId,
|
||||
/// Messages range, delivered by this relayer.
|
||||
pub messages: DeliveredMessages,
|
||||
}
|
||||
|
||||
/// Received messages with their dispatch result.
|
||||
#[derive(Clone, Default, Encode, Decode, RuntimeDebug, PartialEq, Eq, TypeInfo)]
|
||||
pub struct ReceivedMessages<DispatchLevelResult> {
|
||||
/// Id of the lane which is receiving messages.
|
||||
pub lane: LaneId,
|
||||
/// Result of messages which we tried to dispatch
|
||||
pub receive_results: Vec<(MessageNonce, ReceivalResult<DispatchLevelResult>)>,
|
||||
}
|
||||
|
||||
impl<DispatchLevelResult> ReceivedMessages<DispatchLevelResult> {
|
||||
pub fn new(
|
||||
lane: LaneId,
|
||||
receive_results: Vec<(MessageNonce, ReceivalResult<DispatchLevelResult>)>,
|
||||
) -> Self {
|
||||
ReceivedMessages { lane, receive_results }
|
||||
}
|
||||
|
||||
pub fn push(&mut self, message: MessageNonce, result: ReceivalResult<DispatchLevelResult>) {
|
||||
self.receive_results.push((message, result));
|
||||
}
|
||||
}
|
||||
|
||||
/// Result of single message receival.
|
||||
#[derive(RuntimeDebug, Encode, Decode, PartialEq, Eq, Clone, TypeInfo)]
|
||||
pub enum ReceivalResult<DispatchLevelResult> {
|
||||
/// Message has been received and dispatched. Note that we don't care whether dispatch has
|
||||
/// been successful or not - in both case message falls into this category.
|
||||
///
|
||||
/// The message dispatch result is also returned.
|
||||
Dispatched(MessageDispatchResult<DispatchLevelResult>),
|
||||
/// Message has invalid nonce and lane has rejected to accept this message.
|
||||
InvalidNonce,
|
||||
/// There are too many unrewarded relayer entries at the lane.
|
||||
TooManyUnrewardedRelayers,
|
||||
/// There are too many unconfirmed messages at the lane.
|
||||
TooManyUnconfirmedMessages,
|
||||
}
|
||||
|
||||
/// Delivered messages with their dispatch result.
|
||||
#[derive(Clone, Default, Encode, Decode, RuntimeDebug, PartialEq, Eq, TypeInfo, MaxEncodedLen)]
|
||||
pub struct DeliveredMessages {
|
||||
/// Nonce of the first message that has been delivered (inclusive).
|
||||
pub begin: MessageNonce,
|
||||
/// Nonce of the last message that has been delivered (inclusive).
|
||||
pub end: MessageNonce,
|
||||
}
|
||||
|
||||
impl DeliveredMessages {
|
||||
/// Create new `DeliveredMessages` struct that confirms delivery of single nonce with given
|
||||
/// dispatch result.
|
||||
pub fn new(nonce: MessageNonce) -> Self {
|
||||
DeliveredMessages { begin: nonce, end: nonce }
|
||||
}
|
||||
|
||||
/// Return total count of delivered messages.
|
||||
pub fn total_messages(&self) -> MessageNonce {
|
||||
(self.begin..=self.end).checked_len().unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Note new dispatched message.
|
||||
pub fn note_dispatched_message(&mut self) {
|
||||
self.end += 1;
|
||||
}
|
||||
|
||||
/// Returns true if delivered messages contain message with given nonce.
|
||||
pub fn contains_message(&self, nonce: MessageNonce) -> bool {
|
||||
(self.begin..=self.end).contains(&nonce)
|
||||
}
|
||||
}
|
||||
|
||||
/// Gist of `InboundLaneData::relayers` field used by runtime APIs.
|
||||
#[derive(Clone, Default, Encode, Decode, RuntimeDebug, PartialEq, Eq, TypeInfo)]
|
||||
pub struct UnrewardedRelayersState {
|
||||
/// Number of entries in the `InboundLaneData::relayers` set.
|
||||
pub unrewarded_relayer_entries: MessageNonce,
|
||||
/// Number of messages in the oldest entry of `InboundLaneData::relayers`. This is the
|
||||
/// minimal number of reward proofs required to push out this entry from the set.
|
||||
pub messages_in_oldest_entry: MessageNonce,
|
||||
/// Total number of messages in the relayers vector.
|
||||
pub total_messages: MessageNonce,
|
||||
/// Nonce of the latest message that has been delivered to the target chain.
|
||||
///
|
||||
/// This corresponds to the result of the `InboundLaneData::last_delivered_nonce` call
|
||||
/// at the bridged chain.
|
||||
pub last_delivered_nonce: MessageNonce,
|
||||
}
|
||||
|
||||
impl<RelayerId> From<&InboundLaneData<RelayerId>> for UnrewardedRelayersState {
|
||||
fn from(lane: &InboundLaneData<RelayerId>) -> UnrewardedRelayersState {
|
||||
UnrewardedRelayersState {
|
||||
unrewarded_relayer_entries: lane.relayers.len() as _,
|
||||
messages_in_oldest_entry: lane
|
||||
.relayers
|
||||
.front()
|
||||
.and_then(|entry| (entry.messages.begin..=entry.messages.end).checked_len())
|
||||
.unwrap_or(0),
|
||||
total_messages: total_unrewarded_messages(&lane.relayers).unwrap_or(MessageNonce::MAX),
|
||||
last_delivered_nonce: lane.last_delivered_nonce(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Outbound lane data.
|
||||
#[derive(Encode, Decode, Clone, RuntimeDebug, PartialEq, Eq, TypeInfo, MaxEncodedLen)]
|
||||
pub struct OutboundLaneData {
|
||||
/// Nonce of the oldest message that we haven't yet pruned. May point to not-yet-generated
|
||||
/// message if all sent messages are already pruned.
|
||||
pub oldest_unpruned_nonce: MessageNonce,
|
||||
/// Nonce of the latest message, received by bridged chain.
|
||||
pub latest_received_nonce: MessageNonce,
|
||||
/// Nonce of the latest message, generated by us.
|
||||
pub latest_generated_nonce: MessageNonce,
|
||||
}
|
||||
|
||||
impl Default for OutboundLaneData {
|
||||
fn default() -> Self {
|
||||
OutboundLaneData {
|
||||
// it is 1 because we're pruning everything in [oldest_unpruned_nonce;
|
||||
// latest_received_nonce]
|
||||
oldest_unpruned_nonce: 1,
|
||||
latest_received_nonce: 0,
|
||||
latest_generated_nonce: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns total number of messages in the `InboundLaneData::relayers` vector.
|
||||
///
|
||||
/// Returns `None` if there are more messages that `MessageNonce` may fit (i.e. `MessageNonce + 1`).
|
||||
pub fn total_unrewarded_messages<RelayerId>(
|
||||
relayers: &VecDeque<UnrewardedRelayer<RelayerId>>,
|
||||
) -> Option<MessageNonce> {
|
||||
match (relayers.front(), relayers.back()) {
|
||||
(Some(front), Some(back)) => {
|
||||
if let Some(difference) = back.messages.end.checked_sub(front.messages.begin) {
|
||||
difference.checked_add(1)
|
||||
} else {
|
||||
Some(0)
|
||||
}
|
||||
},
|
||||
_ => Some(0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Calculate the number of messages that the relayers have delivered.
|
||||
pub fn calc_relayers_rewards<AccountId>(
|
||||
messages_relayers: VecDeque<UnrewardedRelayer<AccountId>>,
|
||||
received_range: &RangeInclusive<MessageNonce>,
|
||||
) -> RelayersRewards<AccountId>
|
||||
where
|
||||
AccountId: sp_std::cmp::Ord,
|
||||
{
|
||||
// remember to reward relayers that have delivered messages
|
||||
// this loop is bounded by `T::MaxUnrewardedRelayerEntriesAtInboundLane` on the bridged chain
|
||||
let mut relayers_rewards = RelayersRewards::new();
|
||||
for entry in messages_relayers {
|
||||
let nonce_begin = sp_std::cmp::max(entry.messages.begin, *received_range.start());
|
||||
let nonce_end = sp_std::cmp::min(entry.messages.end, *received_range.end());
|
||||
if nonce_end >= nonce_begin {
|
||||
*relayers_rewards.entry(entry.relayer).or_default() += nonce_end - nonce_begin + 1;
|
||||
}
|
||||
}
|
||||
relayers_rewards
|
||||
}
|
||||
|
||||
/// A minimized version of `pallet-bridge-messages::Call` that can be used without a runtime.
|
||||
#[derive(Encode, Decode, Debug, PartialEq, Eq, Clone, TypeInfo)]
|
||||
#[allow(non_camel_case_types)]
|
||||
pub enum BridgeMessagesCall<AccountId, MessagesProof, MessagesDeliveryProof> {
|
||||
/// `pallet-bridge-messages::Call::receive_messages_proof`
|
||||
#[codec(index = 2)]
|
||||
receive_messages_proof {
|
||||
relayer_id_at_bridged_chain: AccountId,
|
||||
proof: MessagesProof,
|
||||
messages_count: u32,
|
||||
dispatch_weight: Weight,
|
||||
},
|
||||
/// `pallet-bridge-messages::Call::receive_messages_delivery_proof`
|
||||
#[codec(index = 3)]
|
||||
receive_messages_delivery_proof {
|
||||
proof: MessagesDeliveryProof,
|
||||
relayers_state: UnrewardedRelayersState,
|
||||
},
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn total_unrewarded_messages_does_not_overflow() {
|
||||
assert_eq!(
|
||||
total_unrewarded_messages(
|
||||
&vec![
|
||||
UnrewardedRelayer { relayer: 1, messages: DeliveredMessages::new(0) },
|
||||
UnrewardedRelayer {
|
||||
relayer: 2,
|
||||
messages: DeliveredMessages::new(MessageNonce::MAX)
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.collect()
|
||||
),
|
||||
None,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inbound_lane_data_returns_correct_hint() {
|
||||
let test_cases = vec![
|
||||
// single relayer, multiple messages
|
||||
(1, 128u8),
|
||||
// multiple relayers, single message per relayer
|
||||
(128u8, 128u8),
|
||||
// several messages per relayer
|
||||
(13u8, 128u8),
|
||||
];
|
||||
for (relayer_entries, messages_count) in test_cases {
|
||||
let expected_size = InboundLaneData::<u8>::encoded_size_hint(relayer_entries as _);
|
||||
let actual_size = InboundLaneData {
|
||||
relayers: (1u8..=relayer_entries)
|
||||
.map(|i| UnrewardedRelayer {
|
||||
relayer: i,
|
||||
messages: DeliveredMessages::new(i as _),
|
||||
})
|
||||
.collect(),
|
||||
last_confirmed_nonce: messages_count as _,
|
||||
}
|
||||
.encode()
|
||||
.len();
|
||||
let difference = (expected_size.unwrap() as f64 - actual_size as f64).abs();
|
||||
assert!(
|
||||
difference / (std::cmp::min(actual_size, expected_size.unwrap()) as f64) < 0.1,
|
||||
"Too large difference between actual ({actual_size}) and expected ({expected_size:?}) inbound lane data size. Test case: {relayer_entries}+{messages_count}",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contains_result_works() {
|
||||
let delivered_messages = DeliveredMessages { begin: 100, end: 150 };
|
||||
|
||||
assert!(!delivered_messages.contains_message(99));
|
||||
assert!(delivered_messages.contains_message(100));
|
||||
assert!(delivered_messages.contains_message(150));
|
||||
assert!(!delivered_messages.contains_message(151));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lane_id_debug_format_matches_inner_array_format() {
|
||||
assert_eq!(format!("{:?}", LaneId([0, 0, 0, 0])), format!("{:?}", [0, 0, 0, 0]),);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Parity Bridges Common is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Primitives of messages module, that are used on the source chain.
|
||||
|
||||
use crate::{InboundLaneData, LaneId, MessageNonce, OutboundLaneData};
|
||||
|
||||
use crate::UnrewardedRelayer;
|
||||
use bp_runtime::Size;
|
||||
use frame_support::{Parameter, RuntimeDebug};
|
||||
use sp_std::{
|
||||
collections::{btree_map::BTreeMap, vec_deque::VecDeque},
|
||||
fmt::Debug,
|
||||
ops::RangeInclusive,
|
||||
};
|
||||
|
||||
/// Number of messages, delivered by relayers.
|
||||
pub type RelayersRewards<AccountId> = BTreeMap<AccountId, MessageNonce>;
|
||||
|
||||
/// Target chain API. Used by source chain to verify target chain proofs.
|
||||
///
|
||||
/// All implementations of this trait should only work with finalized data that
|
||||
/// can't change. Wrong implementation may lead to invalid lane states (i.e. lane
|
||||
/// that's stuck) and/or processing messages without paying fees.
|
||||
///
|
||||
/// The `Payload` type here means the payload of the message that is sent from the
|
||||
/// source chain to the target chain. The `AccountId` type here means the account
|
||||
/// type used by the source chain.
|
||||
pub trait TargetHeaderChain<Payload, AccountId> {
|
||||
/// Error type.
|
||||
type Error: Debug;
|
||||
|
||||
/// Proof that messages have been received by target chain.
|
||||
type MessagesDeliveryProof: Parameter + Size;
|
||||
|
||||
/// Verify message payload before we accept it.
|
||||
///
|
||||
/// **CAUTION**: this is very important function. Incorrect implementation may lead
|
||||
/// to stuck lanes and/or relayers loses.
|
||||
///
|
||||
/// The proper implementation must ensure that the delivery-transaction with this
|
||||
/// payload would (at least) be accepted into target chain transaction pool AND
|
||||
/// eventually will be successfully mined. The most obvious incorrect implementation
|
||||
/// example would be implementation for BTC chain that accepts payloads larger than
|
||||
/// 1MB. BTC nodes aren't accepting transactions that are larger than 1MB, so relayer
|
||||
/// will be unable to craft valid transaction => this (and all subsequent) messages will
|
||||
/// never be delivered.
|
||||
fn verify_message(payload: &Payload) -> Result<(), Self::Error>;
|
||||
|
||||
/// Verify messages delivery proof and return lane && nonce of the latest received message.
|
||||
fn verify_messages_delivery_proof(
|
||||
proof: Self::MessagesDeliveryProof,
|
||||
) -> Result<(LaneId, InboundLaneData<AccountId>), Self::Error>;
|
||||
}
|
||||
|
||||
/// Lane message verifier.
|
||||
///
|
||||
/// Runtime developer may implement any additional validation logic over message-lane mechanism.
|
||||
/// E.g. if lanes should have some security (e.g. you can only accept Lane1 messages from
|
||||
/// Submitter1, Lane2 messages for those who has submitted first message to this lane, disable
|
||||
/// Lane3 until some block, ...), then it may be built using this verifier.
|
||||
///
|
||||
/// Any fee requirements should also be enforced here.
|
||||
pub trait LaneMessageVerifier<SenderOrigin, Payload> {
|
||||
/// Error type.
|
||||
type Error: Debug + Into<&'static str>;
|
||||
|
||||
/// Verify message payload and return Ok(()) if message is valid and allowed to be sent over the
|
||||
/// lane.
|
||||
fn verify_message(
|
||||
submitter: &SenderOrigin,
|
||||
lane: &LaneId,
|
||||
outbound_data: &OutboundLaneData,
|
||||
payload: &Payload,
|
||||
) -> Result<(), Self::Error>;
|
||||
}
|
||||
|
||||
/// Manages payments that are happening at the source chain during delivery confirmation
|
||||
/// transaction.
|
||||
pub trait DeliveryConfirmationPayments<AccountId> {
|
||||
/// Error type.
|
||||
type Error: Debug + Into<&'static str>;
|
||||
|
||||
/// Pay rewards for delivering messages to the given relayers.
|
||||
///
|
||||
/// The implementation may also choose to pay reward to the `confirmation_relayer`, which is
|
||||
/// a relayer that has submitted delivery confirmation transaction.
|
||||
///
|
||||
/// Returns number of actually rewarded relayers.
|
||||
fn pay_reward(
|
||||
lane_id: LaneId,
|
||||
messages_relayers: VecDeque<UnrewardedRelayer<AccountId>>,
|
||||
confirmation_relayer: &AccountId,
|
||||
received_range: &RangeInclusive<MessageNonce>,
|
||||
) -> MessageNonce;
|
||||
}
|
||||
|
||||
impl<AccountId> DeliveryConfirmationPayments<AccountId> for () {
|
||||
type Error = &'static str;
|
||||
|
||||
fn pay_reward(
|
||||
_lane_id: LaneId,
|
||||
_messages_relayers: VecDeque<UnrewardedRelayer<AccountId>>,
|
||||
_confirmation_relayer: &AccountId,
|
||||
_received_range: &RangeInclusive<MessageNonce>,
|
||||
) -> MessageNonce {
|
||||
// this implementation is not rewarding relayers at all
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
/// Send message artifacts.
|
||||
#[derive(Eq, RuntimeDebug, PartialEq)]
|
||||
pub struct SendMessageArtifacts {
|
||||
/// Nonce of the message.
|
||||
pub nonce: MessageNonce,
|
||||
}
|
||||
|
||||
/// Messages bridge API to be used from other pallets.
|
||||
pub trait MessagesBridge<SenderOrigin, Payload> {
|
||||
/// Error type.
|
||||
type Error: Debug;
|
||||
|
||||
/// Send message over the bridge.
|
||||
///
|
||||
/// Returns unique message nonce or error if send has failed.
|
||||
fn send_message(
|
||||
sender: SenderOrigin,
|
||||
lane: LaneId,
|
||||
message: Payload,
|
||||
) -> Result<SendMessageArtifacts, Self::Error>;
|
||||
}
|
||||
|
||||
/// Bridge that does nothing when message is being sent.
|
||||
#[derive(Eq, RuntimeDebug, PartialEq)]
|
||||
pub struct NoopMessagesBridge;
|
||||
|
||||
impl<SenderOrigin, Payload> MessagesBridge<SenderOrigin, Payload> for NoopMessagesBridge {
|
||||
type Error = &'static str;
|
||||
|
||||
fn send_message(
|
||||
_sender: SenderOrigin,
|
||||
_lane: LaneId,
|
||||
_message: Payload,
|
||||
) -> Result<SendMessageArtifacts, Self::Error> {
|
||||
Ok(SendMessageArtifacts { nonce: 0 })
|
||||
}
|
||||
}
|
||||
|
||||
/// Structure that may be used in place of `TargetHeaderChain`, `LaneMessageVerifier` and
|
||||
/// `MessageDeliveryAndDispatchPayment` on chains, where outbound messages are forbidden.
|
||||
pub struct ForbidOutboundMessages;
|
||||
|
||||
/// Error message that is used in `ForbidOutboundMessages` implementation.
|
||||
const ALL_OUTBOUND_MESSAGES_REJECTED: &str =
|
||||
"This chain is configured to reject all outbound messages";
|
||||
|
||||
impl<Payload, AccountId> TargetHeaderChain<Payload, AccountId> for ForbidOutboundMessages {
|
||||
type Error = &'static str;
|
||||
|
||||
type MessagesDeliveryProof = ();
|
||||
|
||||
fn verify_message(_payload: &Payload) -> Result<(), Self::Error> {
|
||||
Err(ALL_OUTBOUND_MESSAGES_REJECTED)
|
||||
}
|
||||
|
||||
fn verify_messages_delivery_proof(
|
||||
_proof: Self::MessagesDeliveryProof,
|
||||
) -> Result<(LaneId, InboundLaneData<AccountId>), Self::Error> {
|
||||
Err(ALL_OUTBOUND_MESSAGES_REJECTED)
|
||||
}
|
||||
}
|
||||
|
||||
impl<SenderOrigin, Payload> LaneMessageVerifier<SenderOrigin, Payload> for ForbidOutboundMessages {
|
||||
type Error = &'static str;
|
||||
|
||||
fn verify_message(
|
||||
_submitter: &SenderOrigin,
|
||||
_lane: &LaneId,
|
||||
_outbound_data: &OutboundLaneData,
|
||||
_payload: &Payload,
|
||||
) -> Result<(), Self::Error> {
|
||||
Err(ALL_OUTBOUND_MESSAGES_REJECTED)
|
||||
}
|
||||
}
|
||||
|
||||
impl<AccountId> DeliveryConfirmationPayments<AccountId> for ForbidOutboundMessages {
|
||||
type Error = &'static str;
|
||||
|
||||
fn pay_reward(
|
||||
_lane_id: LaneId,
|
||||
_messages_relayers: VecDeque<UnrewardedRelayer<AccountId>>,
|
||||
_confirmation_relayer: &AccountId,
|
||||
_received_range: &RangeInclusive<MessageNonce>,
|
||||
) -> MessageNonce {
|
||||
0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Parity Bridges Common is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Storage keys of bridge messages pallet.
|
||||
|
||||
/// Name of the `OPERATING_MODE_VALUE_NAME` storage value.
|
||||
pub const OPERATING_MODE_VALUE_NAME: &str = "PalletOperatingMode";
|
||||
/// Name of the `OutboundMessages` storage map.
|
||||
pub const OUTBOUND_MESSAGES_MAP_NAME: &str = "OutboundMessages";
|
||||
/// Name of the `OutboundLanes` storage map.
|
||||
pub const OUTBOUND_LANES_MAP_NAME: &str = "OutboundLanes";
|
||||
/// Name of the `InboundLanes` storage map.
|
||||
pub const INBOUND_LANES_MAP_NAME: &str = "InboundLanes";
|
||||
|
||||
use crate::{LaneId, MessageKey, MessageNonce};
|
||||
|
||||
use codec::Encode;
|
||||
use frame_support::Blake2_128Concat;
|
||||
use sp_core::storage::StorageKey;
|
||||
|
||||
/// Storage key of the `PalletOperatingMode` value in the runtime storage.
|
||||
pub fn operating_mode_key(pallet_prefix: &str) -> StorageKey {
|
||||
StorageKey(
|
||||
bp_runtime::storage_value_final_key(
|
||||
pallet_prefix.as_bytes(),
|
||||
OPERATING_MODE_VALUE_NAME.as_bytes(),
|
||||
)
|
||||
.to_vec(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Storage key of the outbound message in the runtime storage.
|
||||
pub fn message_key(pallet_prefix: &str, lane: &LaneId, nonce: MessageNonce) -> StorageKey {
|
||||
bp_runtime::storage_map_final_key::<Blake2_128Concat>(
|
||||
pallet_prefix,
|
||||
OUTBOUND_MESSAGES_MAP_NAME,
|
||||
&MessageKey { lane_id: *lane, nonce }.encode(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Storage key of the outbound message lane state in the runtime storage.
|
||||
pub fn outbound_lane_data_key(pallet_prefix: &str, lane: &LaneId) -> StorageKey {
|
||||
bp_runtime::storage_map_final_key::<Blake2_128Concat>(
|
||||
pallet_prefix,
|
||||
OUTBOUND_LANES_MAP_NAME,
|
||||
&lane.encode(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Storage key of the inbound message lane state in the runtime storage.
|
||||
pub fn inbound_lane_data_key(pallet_prefix: &str, lane: &LaneId) -> StorageKey {
|
||||
bp_runtime::storage_map_final_key::<Blake2_128Concat>(
|
||||
pallet_prefix,
|
||||
INBOUND_LANES_MAP_NAME,
|
||||
&lane.encode(),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use hex_literal::hex;
|
||||
|
||||
#[test]
|
||||
fn operating_mode_key_computed_properly() {
|
||||
// If this test fails, then something has been changed in module storage that is possibly
|
||||
// breaking all existing message relays.
|
||||
let storage_key = operating_mode_key("BridgeMessages").0;
|
||||
assert_eq!(
|
||||
storage_key,
|
||||
hex!("dd16c784ebd3390a9bc0357c7511ed010f4cf0917788d791142ff6c1f216e7b3").to_vec(),
|
||||
"Unexpected storage key: {}",
|
||||
hex::encode(&storage_key),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn storage_message_key_computed_properly() {
|
||||
// If this test fails, then something has been changed in module storage that is breaking
|
||||
// all previously crafted messages proofs.
|
||||
let storage_key = message_key("BridgeMessages", &LaneId(*b"test"), 42).0;
|
||||
assert_eq!(
|
||||
storage_key,
|
||||
hex!("dd16c784ebd3390a9bc0357c7511ed018a395e6242c6813b196ca31ed0547ea79446af0e09063bd4a7874aef8a997cec746573742a00000000000000").to_vec(),
|
||||
"Unexpected storage key: {}",
|
||||
hex::encode(&storage_key),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outbound_lane_data_key_computed_properly() {
|
||||
// If this test fails, then something has been changed in module storage that is breaking
|
||||
// all previously crafted outbound lane state proofs.
|
||||
let storage_key = outbound_lane_data_key("BridgeMessages", &LaneId(*b"test")).0;
|
||||
assert_eq!(
|
||||
storage_key,
|
||||
hex!("dd16c784ebd3390a9bc0357c7511ed0196c246acb9b55077390e3ca723a0ca1f44a8995dd50b6657a037a7839304535b74657374").to_vec(),
|
||||
"Unexpected storage key: {}",
|
||||
hex::encode(&storage_key),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inbound_lane_data_key_computed_properly() {
|
||||
// If this test fails, then something has been changed in module storage that is breaking
|
||||
// all previously crafted inbound lane state proofs.
|
||||
let storage_key = inbound_lane_data_key("BridgeMessages", &LaneId(*b"test")).0;
|
||||
assert_eq!(
|
||||
storage_key,
|
||||
hex!("dd16c784ebd3390a9bc0357c7511ed01e5f83cf83f2127eb47afdc35d6e43fab44a8995dd50b6657a037a7839304535b74657374").to_vec(),
|
||||
"Unexpected storage key: {}",
|
||||
hex::encode(&storage_key),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Parity Bridges Common is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Primitives of messages module, that are used on the target chain.
|
||||
|
||||
use crate::{LaneId, Message, MessageKey, MessageNonce, MessagePayload, OutboundLaneData};
|
||||
|
||||
use bp_runtime::{messages::MessageDispatchResult, Size};
|
||||
use codec::{Decode, Encode, Error as CodecError};
|
||||
use frame_support::{weights::Weight, Parameter, RuntimeDebug};
|
||||
use scale_info::TypeInfo;
|
||||
use sp_std::{collections::btree_map::BTreeMap, fmt::Debug, marker::PhantomData, prelude::*};
|
||||
|
||||
/// Proved messages from the source chain.
|
||||
pub type ProvedMessages<Message> = BTreeMap<LaneId, ProvedLaneMessages<Message>>;
|
||||
|
||||
/// Proved messages from single lane of the source chain.
|
||||
#[derive(RuntimeDebug, Encode, Decode, Clone, PartialEq, Eq, TypeInfo)]
|
||||
pub struct ProvedLaneMessages<Message> {
|
||||
/// Optional outbound lane state.
|
||||
pub lane_state: Option<OutboundLaneData>,
|
||||
/// Messages sent through this lane.
|
||||
pub messages: Vec<Message>,
|
||||
}
|
||||
|
||||
/// Message data with decoded dispatch payload.
|
||||
#[derive(RuntimeDebug)]
|
||||
pub struct DispatchMessageData<DispatchPayload> {
|
||||
/// Result of dispatch payload decoding.
|
||||
pub payload: Result<DispatchPayload, CodecError>,
|
||||
}
|
||||
|
||||
/// Message with decoded dispatch payload.
|
||||
#[derive(RuntimeDebug)]
|
||||
pub struct DispatchMessage<DispatchPayload> {
|
||||
/// Message key.
|
||||
pub key: MessageKey,
|
||||
/// Message data with decoded dispatch payload.
|
||||
pub data: DispatchMessageData<DispatchPayload>,
|
||||
}
|
||||
|
||||
/// Source chain API. Used by target chain, to verify source chain proofs.
|
||||
///
|
||||
/// All implementations of this trait should only work with finalized data that
|
||||
/// can't change. Wrong implementation may lead to invalid lane states (i.e. lane
|
||||
/// that's stuck) and/or processing messages without paying fees.
|
||||
pub trait SourceHeaderChain {
|
||||
/// Error type.
|
||||
type Error: Debug;
|
||||
|
||||
/// Proof that messages are sent from source chain. This may also include proof
|
||||
/// of corresponding outbound lane states.
|
||||
type MessagesProof: Parameter + Size;
|
||||
|
||||
/// Verify messages proof and return proved messages.
|
||||
///
|
||||
/// Returns error if either proof is incorrect, or the number of messages in the proof
|
||||
/// is not matching the `messages_count`.
|
||||
///
|
||||
/// Messages vector is required to be sorted by nonce within each lane. Out-of-order
|
||||
/// messages will be rejected.
|
||||
///
|
||||
/// The `messages_count` argument verification (sane limits) is supposed to be made
|
||||
/// outside this function. This function only verifies that the proof declares exactly
|
||||
/// `messages_count` messages.
|
||||
fn verify_messages_proof(
|
||||
proof: Self::MessagesProof,
|
||||
messages_count: u32,
|
||||
) -> Result<ProvedMessages<Message>, Self::Error>;
|
||||
}
|
||||
|
||||
/// Called when inbound message is received.
|
||||
pub trait MessageDispatch {
|
||||
/// Decoded message payload type. Valid message may contain invalid payload. In this case
|
||||
/// message is delivered, but dispatch fails. Therefore, two separate types of payload
|
||||
/// (opaque `MessagePayload` used in delivery and this `DispatchPayload` used in dispatch).
|
||||
type DispatchPayload: Decode;
|
||||
|
||||
/// Fine-grained result of single message dispatch (for better diagnostic purposes)
|
||||
type DispatchLevelResult: Clone + sp_std::fmt::Debug + Eq;
|
||||
|
||||
/// Estimate dispatch weight.
|
||||
///
|
||||
/// This function must return correct upper bound of dispatch weight. The return value
|
||||
/// of this function is expected to match return value of the corresponding
|
||||
/// `From<Chain>InboundLaneApi::message_details().dispatch_weight` call.
|
||||
fn dispatch_weight(message: &mut DispatchMessage<Self::DispatchPayload>) -> Weight;
|
||||
|
||||
/// Called when inbound message is received.
|
||||
///
|
||||
/// It is up to the implementers of this trait to determine whether the message
|
||||
/// is invalid (i.e. improperly encoded, has too large weight, ...) or not.
|
||||
fn dispatch(
|
||||
message: DispatchMessage<Self::DispatchPayload>,
|
||||
) -> MessageDispatchResult<Self::DispatchLevelResult>;
|
||||
}
|
||||
|
||||
/// Manages payments that are happening at the target chain during message delivery transaction.
|
||||
pub trait DeliveryPayments<AccountId> {
|
||||
/// Error type.
|
||||
type Error: Debug + Into<&'static str>;
|
||||
|
||||
/// Pay rewards for delivering messages to the given relayer.
|
||||
///
|
||||
/// This method is called during message delivery transaction which has been submitted
|
||||
/// by the `relayer`. The transaction brings `total_messages` messages but only
|
||||
/// `valid_messages` have been accepted. The post-dispatch transaction weight is the
|
||||
/// `actual_weight`.
|
||||
fn pay_reward(
|
||||
relayer: AccountId,
|
||||
total_messages: MessageNonce,
|
||||
valid_messages: MessageNonce,
|
||||
actual_weight: Weight,
|
||||
);
|
||||
}
|
||||
|
||||
impl<Message> Default for ProvedLaneMessages<Message> {
|
||||
fn default() -> Self {
|
||||
ProvedLaneMessages { lane_state: None, messages: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
impl<DispatchPayload: Decode> From<Message> for DispatchMessage<DispatchPayload> {
|
||||
fn from(message: Message) -> Self {
|
||||
DispatchMessage { key: message.key, data: message.payload.into() }
|
||||
}
|
||||
}
|
||||
|
||||
impl<DispatchPayload: Decode> From<MessagePayload> for DispatchMessageData<DispatchPayload> {
|
||||
fn from(payload: MessagePayload) -> Self {
|
||||
DispatchMessageData { payload: DispatchPayload::decode(&mut &payload[..]) }
|
||||
}
|
||||
}
|
||||
|
||||
impl<AccountId> DeliveryPayments<AccountId> for () {
|
||||
type Error = &'static str;
|
||||
|
||||
fn pay_reward(
|
||||
_relayer: AccountId,
|
||||
_total_messages: MessageNonce,
|
||||
_valid_messages: MessageNonce,
|
||||
_actual_weight: Weight,
|
||||
) {
|
||||
// this implementation is not rewarding relayer at all
|
||||
}
|
||||
}
|
||||
|
||||
/// Structure that may be used in place of `SourceHeaderChain` and `MessageDispatch` on chains,
|
||||
/// where inbound messages are forbidden.
|
||||
pub struct ForbidInboundMessages<MessagesProof, DispatchPayload>(
|
||||
PhantomData<(MessagesProof, DispatchPayload)>,
|
||||
);
|
||||
|
||||
/// Error message that is used in `ForbidOutboundMessages` implementation.
|
||||
const ALL_INBOUND_MESSAGES_REJECTED: &str =
|
||||
"This chain is configured to reject all inbound messages";
|
||||
|
||||
impl<MessagesProof: Parameter + Size, DispatchPayload> SourceHeaderChain
|
||||
for ForbidInboundMessages<MessagesProof, DispatchPayload>
|
||||
{
|
||||
type Error = &'static str;
|
||||
type MessagesProof = MessagesProof;
|
||||
|
||||
fn verify_messages_proof(
|
||||
_proof: Self::MessagesProof,
|
||||
_messages_count: u32,
|
||||
) -> Result<ProvedMessages<Message>, Self::Error> {
|
||||
Err(ALL_INBOUND_MESSAGES_REJECTED)
|
||||
}
|
||||
}
|
||||
|
||||
impl<MessagesProof, DispatchPayload: Decode> MessageDispatch
|
||||
for ForbidInboundMessages<MessagesProof, DispatchPayload>
|
||||
{
|
||||
type DispatchPayload = DispatchPayload;
|
||||
type DispatchLevelResult = ();
|
||||
|
||||
fn dispatch_weight(_message: &mut DispatchMessage<Self::DispatchPayload>) -> Weight {
|
||||
Weight::MAX
|
||||
}
|
||||
|
||||
fn dispatch(
|
||||
_: DispatchMessage<Self::DispatchPayload>,
|
||||
) -> MessageDispatchResult<Self::DispatchLevelResult> {
|
||||
MessageDispatchResult { unspent_weight: Weight::zero(), dispatch_level_result: () }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
[package]
|
||||
name = "bp-parachains"
|
||||
description = "Primitives of parachains module."
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2018"
|
||||
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
|
||||
|
||||
[dependencies]
|
||||
codec = { package = "parity-scale-codec", version = "3.1.5", default-features = false, features = ["derive"] }
|
||||
impl-trait-for-tuples = "0.2"
|
||||
scale-info = { version = "2.6.0", default-features = false, features = ["derive"] }
|
||||
|
||||
# Bridge dependencies
|
||||
|
||||
bp-header-chain = { path = "../header-chain", default-features = false }
|
||||
bp-polkadot-core = { path = "../polkadot-core", default-features = false }
|
||||
bp-runtime = { path = "../runtime", default-features = false }
|
||||
|
||||
# Substrate dependencies
|
||||
|
||||
frame-support = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-core = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-std = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"bp-header-chain/std",
|
||||
"bp-polkadot-core/std",
|
||||
"bp-runtime/std",
|
||||
"codec/std",
|
||||
"frame-support/std",
|
||||
"scale-info/std",
|
||||
"sp-core/std",
|
||||
"sp-runtime/std",
|
||||
"sp-std/std",
|
||||
]
|
||||
@@ -0,0 +1,180 @@
|
||||
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Parity Bridges Common is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Primitives of parachains module.
|
||||
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
pub use bp_header_chain::StoredHeaderData;
|
||||
|
||||
use bp_polkadot_core::{
|
||||
parachains::{ParaHash, ParaHead, ParaHeadsProof, ParaId},
|
||||
BlockNumber as RelayBlockNumber, Hash as RelayBlockHash,
|
||||
};
|
||||
use bp_runtime::{
|
||||
BlockNumberOf, Chain, HashOf, HeaderOf, Parachain, StorageDoubleMapKeyProvider,
|
||||
StorageMapKeyProvider,
|
||||
};
|
||||
use codec::{Decode, Encode, MaxEncodedLen};
|
||||
use frame_support::{Blake2_128Concat, RuntimeDebug, Twox64Concat};
|
||||
use scale_info::TypeInfo;
|
||||
use sp_core::storage::StorageKey;
|
||||
use sp_runtime::traits::Header as HeaderT;
|
||||
use sp_std::{marker::PhantomData, prelude::*};
|
||||
|
||||
/// Best known parachain head hash.
|
||||
#[derive(Clone, Decode, Encode, MaxEncodedLen, PartialEq, RuntimeDebug, TypeInfo)]
|
||||
pub struct BestParaHeadHash {
|
||||
/// Number of relay block where this head has been read.
|
||||
///
|
||||
/// Parachain head is opaque to relay chain. So we can't simply decode it as a header of
|
||||
/// parachains and call `block_number()` on it. Instead, we're using the fact that parachain
|
||||
/// head is always built on top of previous head (because it is blockchain) and relay chain
|
||||
/// always imports parachain heads in order. What it means for us is that at any given
|
||||
/// **finalized** relay block `B`, head of parachain will be ancestor (or the same) of all
|
||||
/// parachain heads available at descendants of `B`.
|
||||
pub at_relay_block_number: RelayBlockNumber,
|
||||
/// Hash of parachain head.
|
||||
pub head_hash: ParaHash,
|
||||
}
|
||||
|
||||
/// Best known parachain head as it is stored in the runtime storage.
|
||||
#[derive(Decode, Encode, MaxEncodedLen, PartialEq, RuntimeDebug, TypeInfo)]
|
||||
pub struct ParaInfo {
|
||||
/// Best known parachain head hash.
|
||||
pub best_head_hash: BestParaHeadHash,
|
||||
/// Current ring buffer position for this parachain.
|
||||
pub next_imported_hash_position: u32,
|
||||
}
|
||||
|
||||
/// Returns runtime storage key of given parachain head at the source chain.
|
||||
///
|
||||
/// The head is stored by the `paras` pallet in the `Heads` map.
|
||||
pub fn parachain_head_storage_key_at_source(
|
||||
paras_pallet_name: &str,
|
||||
para_id: ParaId,
|
||||
) -> StorageKey {
|
||||
bp_runtime::storage_map_final_key::<Twox64Concat>(paras_pallet_name, "Heads", ¶_id.encode())
|
||||
}
|
||||
|
||||
/// Can be use to access the runtime storage key of the parachains info at the target chain.
|
||||
///
|
||||
/// The info is stored by the `pallet-bridge-parachains` pallet in the `ParasInfo` map.
|
||||
pub struct ParasInfoKeyProvider;
|
||||
impl StorageMapKeyProvider for ParasInfoKeyProvider {
|
||||
const MAP_NAME: &'static str = "ParasInfo";
|
||||
|
||||
type Hasher = Blake2_128Concat;
|
||||
type Key = ParaId;
|
||||
type Value = ParaInfo;
|
||||
}
|
||||
|
||||
/// Can be use to access the runtime storage key of the parachain head at the target chain.
|
||||
///
|
||||
/// The head is stored by the `pallet-bridge-parachains` pallet in the `ImportedParaHeads` map.
|
||||
pub struct ImportedParaHeadsKeyProvider;
|
||||
impl StorageDoubleMapKeyProvider for ImportedParaHeadsKeyProvider {
|
||||
const MAP_NAME: &'static str = "ImportedParaHeads";
|
||||
|
||||
type Hasher1 = Blake2_128Concat;
|
||||
type Key1 = ParaId;
|
||||
type Hasher2 = Blake2_128Concat;
|
||||
type Key2 = ParaHash;
|
||||
type Value = ParaStoredHeaderData;
|
||||
}
|
||||
|
||||
/// Stored data of the parachain head. It is encoded version of the
|
||||
/// `bp_runtime::StoredHeaderData` structure.
|
||||
///
|
||||
/// We do not know exact structure of the parachain head, so we always store encoded version
|
||||
/// of the `bp_runtime::StoredHeaderData`. It is only decoded when we talk about specific parachain.
|
||||
#[derive(Clone, Decode, Encode, PartialEq, RuntimeDebug, TypeInfo)]
|
||||
pub struct ParaStoredHeaderData(pub Vec<u8>);
|
||||
|
||||
impl ParaStoredHeaderData {
|
||||
/// Decode stored parachain head data.
|
||||
pub fn decode_parachain_head_data<C: Chain>(
|
||||
&self,
|
||||
) -> Result<StoredHeaderData<BlockNumberOf<C>, HashOf<C>>, codec::Error> {
|
||||
StoredHeaderData::<BlockNumberOf<C>, HashOf<C>>::decode(&mut &self.0[..])
|
||||
}
|
||||
}
|
||||
|
||||
/// Stored parachain head data builder.
|
||||
pub trait ParaStoredHeaderDataBuilder {
|
||||
/// Return number of parachains that are supported by this builder.
|
||||
fn supported_parachains() -> u32;
|
||||
|
||||
/// Try to build head data from encoded head of parachain with given id.
|
||||
fn try_build(para_id: ParaId, para_head: &ParaHead) -> Option<ParaStoredHeaderData>;
|
||||
}
|
||||
|
||||
/// Helper for using single parachain as `ParaStoredHeaderDataBuilder`.
|
||||
pub struct SingleParaStoredHeaderDataBuilder<C: Parachain>(PhantomData<C>);
|
||||
|
||||
impl<C: Parachain> ParaStoredHeaderDataBuilder for SingleParaStoredHeaderDataBuilder<C> {
|
||||
fn supported_parachains() -> u32 {
|
||||
1
|
||||
}
|
||||
|
||||
fn try_build(para_id: ParaId, para_head: &ParaHead) -> Option<ParaStoredHeaderData> {
|
||||
if para_id == ParaId(C::PARACHAIN_ID) {
|
||||
let header = HeaderOf::<C>::decode(&mut ¶_head.0[..]).ok()?;
|
||||
return Some(ParaStoredHeaderData(
|
||||
StoredHeaderData { number: *header.number(), state_root: *header.state_root() }
|
||||
.encode(),
|
||||
))
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
// Tries to build header data from each tuple member, short-circuiting on first successful one.
|
||||
#[impl_trait_for_tuples::impl_for_tuples(1, 30)]
|
||||
#[tuple_types_custom_trait_bound(Parachain)]
|
||||
impl ParaStoredHeaderDataBuilder for C {
|
||||
fn supported_parachains() -> u32 {
|
||||
let mut result = 0;
|
||||
for_tuples!( #(
|
||||
result += SingleParaStoredHeaderDataBuilder::<C>::supported_parachains();
|
||||
)* );
|
||||
result
|
||||
}
|
||||
|
||||
fn try_build(para_id: ParaId, para_head: &ParaHead) -> Option<ParaStoredHeaderData> {
|
||||
for_tuples!( #(
|
||||
let maybe_para_head = SingleParaStoredHeaderDataBuilder::<C>::try_build(para_id, para_head);
|
||||
if let Some(maybe_para_head) = maybe_para_head {
|
||||
return Some(maybe_para_head);
|
||||
}
|
||||
)* );
|
||||
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// A minimized version of `pallet-bridge-parachains::Call` that can be used without a runtime.
|
||||
#[derive(Encode, Decode, Debug, PartialEq, Eq, Clone, TypeInfo)]
|
||||
#[allow(non_camel_case_types)]
|
||||
pub enum BridgeParachainCall {
|
||||
/// `pallet-bridge-parachains::Call::submit_parachain_heads`
|
||||
#[codec(index = 0)]
|
||||
submit_parachain_heads {
|
||||
at_relay_block: (RelayBlockNumber, RelayBlockHash),
|
||||
parachains: Vec<(ParaId, ParaHash)>,
|
||||
parachain_heads_proof: ParaHeadsProof,
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
[package]
|
||||
name = "bp-polkadot-core"
|
||||
description = "Primitives of Polkadot-like runtime."
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2021"
|
||||
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
|
||||
|
||||
[dependencies]
|
||||
codec = { package = "parity-scale-codec", version = "3.1.5", default-features = false, features = ["derive"] }
|
||||
parity-util-mem = { version = "0.12.0", optional = true }
|
||||
scale-info = { version = "2.6.0", default-features = false, features = ["derive"] }
|
||||
serde = { version = "1.0", optional = true, features = ["derive"] }
|
||||
|
||||
# Bridge Dependencies
|
||||
|
||||
bp-messages = { path = "../messages", default-features = false }
|
||||
bp-runtime = { path = "../runtime", default-features = false }
|
||||
|
||||
# Substrate Based Dependencies
|
||||
|
||||
frame-support = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
frame-system = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-core = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-std = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
|
||||
[dev-dependencies]
|
||||
hex = "0.4"
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"bp-messages/std",
|
||||
"bp-runtime/std",
|
||||
"frame-support/std",
|
||||
"frame-system/std",
|
||||
"codec/std",
|
||||
"parity-util-mem",
|
||||
"scale-info/std",
|
||||
"serde",
|
||||
"sp-core/std",
|
||||
"sp-runtime/std",
|
||||
"sp-std/std",
|
||||
]
|
||||
@@ -0,0 +1,292 @@
|
||||
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Parity Bridges Common is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
use bp_messages::MessageNonce;
|
||||
use bp_runtime::{Chain, EncodedOrDecodedCall, StorageMapKeyProvider};
|
||||
use frame_support::{
|
||||
dispatch::DispatchClass,
|
||||
parameter_types,
|
||||
weights::{
|
||||
constants::{BlockExecutionWeight, WEIGHT_REF_TIME_PER_SECOND},
|
||||
Weight,
|
||||
},
|
||||
Blake2_128Concat, RuntimeDebug,
|
||||
};
|
||||
use frame_system::limits;
|
||||
use sp_core::{storage::StorageKey, Hasher as HasherT};
|
||||
use sp_runtime::{
|
||||
generic,
|
||||
traits::{BlakeTwo256, IdentifyAccount, Verify},
|
||||
MultiAddress, MultiSignature, OpaqueExtrinsic,
|
||||
};
|
||||
use sp_std::prelude::Vec;
|
||||
|
||||
// Re-export's to avoid extra substrate dependencies in chain-specific crates.
|
||||
pub use frame_support::{weights::constants::ExtrinsicBaseWeight, Parameter};
|
||||
pub use sp_runtime::{traits::Convert, Perbill};
|
||||
|
||||
pub mod parachains;
|
||||
|
||||
/// Maximal number of GRANDPA authorities at Polkadot-like chains.
|
||||
///
|
||||
/// Ideally, we would set it to the value of `MaxAuthorities` constant from bridged runtime
|
||||
/// configurations. But right now it is set to the `100_000`, which makes PoV size for
|
||||
/// our bridge hub parachains huge. So let's stick to the real-world value here.
|
||||
///
|
||||
/// Right now both Kusama and Polkadot aim to have around 1000 validators. Let's be safe here and
|
||||
/// take a bit more here.
|
||||
pub const MAX_AUTHORITIES_COUNT: u32 = 1_256;
|
||||
|
||||
/// Reasonable number of headers in the `votes_ancestries` on Polkadot-like chains.
|
||||
///
|
||||
/// See [`bp-header-chain::ChainWithGrandpa`] for more details.
|
||||
///
|
||||
/// This value comes from recent (February, 2023) Kusama and Polkadot headers. There are no
|
||||
/// justifications with any additional headers in votes ancestry, so reasonable headers may
|
||||
/// be set to zero. But we assume that there may be small GRANDPA lags, so we're leaving some
|
||||
/// reserve here.
|
||||
pub const REASONABLE_HEADERS_IN_JUSTIFICATON_ANCESTRY: u32 = 2;
|
||||
|
||||
/// Approximate average header size in `votes_ancestries` field of justification on Polkadot-like
|
||||
/// chains.
|
||||
///
|
||||
/// See [`bp-header-chain::ChainWithGrandpa`] for more details.
|
||||
///
|
||||
/// This value comes from recent (February, 2023) Kusama headers. Average is `336` there, but some
|
||||
/// non-mandatory headers has size `40kb` (they contain the BABE epoch descriptor with all
|
||||
/// authorities - just like our mandatory header). Since we assume `2` headers in justification
|
||||
/// votes ancestry, let's set average header to `40kb / 2`.
|
||||
pub const AVERAGE_HEADER_SIZE_IN_JUSTIFICATION: u32 = 20 * 1024;
|
||||
|
||||
/// Approximate maximal header size on Polkadot-like chains.
|
||||
///
|
||||
/// See [`bp-header-chain::ChainWithGrandpa`] for more details.
|
||||
///
|
||||
/// This value comes from recent (February, 2023) Kusama headers. Maximal header is a mandatory
|
||||
/// header. In its SCALE-encoded form it is `80348` bytes. Let's have some reserve here.
|
||||
pub const MAX_HEADER_SIZE: u32 = 90_000;
|
||||
|
||||
/// Number of extra bytes (excluding size of storage value itself) of storage proof, built at
|
||||
/// Polkadot-like chain. This mostly depends on number of entries in the storage trie.
|
||||
/// Some reserve is reserved to account future chain growth.
|
||||
///
|
||||
/// To compute this value, we've synced Kusama chain blocks [0; 6545733] to see if there were
|
||||
/// any significant changes of the storage proof size (NO):
|
||||
///
|
||||
/// - at block 3072 the storage proof size overhead was 579 bytes;
|
||||
/// - at block 2479616 it was 578 bytes;
|
||||
/// - at block 4118528 it was 711 bytes;
|
||||
/// - at block 6540800 it was 779 bytes.
|
||||
///
|
||||
/// The number of storage entries at the block 6546170 was 351207 and number of trie nodes in
|
||||
/// the storage proof was 5 (log(16, 351207) ~ 4.6).
|
||||
///
|
||||
/// So the assumption is that the storage proof size overhead won't be larger than 1024 in the
|
||||
/// nearest future. If it'll ever break this barrier, then we'll need to update this constant
|
||||
/// at next runtime upgrade.
|
||||
pub const EXTRA_STORAGE_PROOF_SIZE: u32 = 1024;
|
||||
|
||||
/// All Polkadot-like chains allow normal extrinsics to fill block up to 75 percent.
|
||||
///
|
||||
/// This is a copy-paste from the Polkadot repo's `polkadot-runtime-common` crate.
|
||||
const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
|
||||
|
||||
/// All Polkadot-like chains allow 2 seconds of compute with a 6-second average block time.
|
||||
///
|
||||
/// This is a copy-paste from the Polkadot repo's `polkadot-runtime-common` crate.
|
||||
pub const MAXIMUM_BLOCK_WEIGHT: Weight =
|
||||
Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND.saturating_mul(2), u64::MAX);
|
||||
|
||||
/// All Polkadot-like chains assume that an on-initialize consumes 1 percent of the weight on
|
||||
/// average, hence a single extrinsic will not be allowed to consume more than
|
||||
/// `AvailableBlockRatio - 1 percent`.
|
||||
///
|
||||
/// This is a copy-paste from the Polkadot repo's `polkadot-runtime-common` crate.
|
||||
pub const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(1);
|
||||
|
||||
parameter_types! {
|
||||
/// All Polkadot-like chains have maximal block size set to 5MB.
|
||||
///
|
||||
/// This is a copy-paste from the Polkadot repo's `polkadot-runtime-common` crate.
|
||||
pub BlockLength: limits::BlockLength = limits::BlockLength::max_with_normal_ratio(
|
||||
5 * 1024 * 1024,
|
||||
NORMAL_DISPATCH_RATIO,
|
||||
);
|
||||
/// All Polkadot-like chains have the same block weights.
|
||||
///
|
||||
/// This is a copy-paste from the Polkadot repo's `polkadot-runtime-common` crate.
|
||||
pub BlockWeights: limits::BlockWeights = limits::BlockWeights::builder()
|
||||
.base_block(BlockExecutionWeight::get())
|
||||
.for_class(DispatchClass::all(), |weights| {
|
||||
weights.base_extrinsic = ExtrinsicBaseWeight::get();
|
||||
})
|
||||
.for_class(DispatchClass::Normal, |weights| {
|
||||
weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
|
||||
})
|
||||
.for_class(DispatchClass::Operational, |weights| {
|
||||
weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
|
||||
// Operational transactions have an extra reserved space, so that they
|
||||
// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.
|
||||
weights.reserved = Some(
|
||||
MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT,
|
||||
);
|
||||
})
|
||||
.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
|
||||
.build_or_panic();
|
||||
}
|
||||
|
||||
// TODO [#78] may need to be updated after https://github.com/paritytech/parity-bridges-common/issues/78
|
||||
/// Maximal number of messages in single delivery transaction.
|
||||
pub const MAX_MESSAGES_IN_DELIVERY_TRANSACTION: MessageNonce = 128;
|
||||
|
||||
/// Maximal number of bytes, included in the signed Polkadot-like transaction apart from the encoded
|
||||
/// call itself.
|
||||
///
|
||||
/// Can be computed by subtracting encoded call size from raw transaction size.
|
||||
pub const TX_EXTRA_BYTES: u32 = 256;
|
||||
|
||||
/// Re-export `time_units` to make usage easier.
|
||||
pub use time_units::*;
|
||||
|
||||
/// Human readable time units defined in terms of number of blocks.
|
||||
pub mod time_units {
|
||||
use super::BlockNumber;
|
||||
|
||||
pub const MILLISECS_PER_BLOCK: u64 = 6000;
|
||||
pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;
|
||||
|
||||
pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);
|
||||
pub const HOURS: BlockNumber = MINUTES * 60;
|
||||
pub const DAYS: BlockNumber = HOURS * 24;
|
||||
}
|
||||
|
||||
/// Block number type used in Polkadot-like chains.
|
||||
pub type BlockNumber = u32;
|
||||
|
||||
/// Hash type used in Polkadot-like chains.
|
||||
pub type Hash = <BlakeTwo256 as HasherT>::Out;
|
||||
|
||||
/// Account Index (a.k.a. nonce).
|
||||
pub type Index = u32;
|
||||
|
||||
/// Hashing type.
|
||||
pub type Hashing = BlakeTwo256;
|
||||
|
||||
/// The type of object that can produce hashes on Polkadot-like chains.
|
||||
pub type Hasher = BlakeTwo256;
|
||||
|
||||
/// The header type used by Polkadot-like chains.
|
||||
pub type Header = generic::Header<BlockNumber, Hasher>;
|
||||
|
||||
/// Signature type used by Polkadot-like chains.
|
||||
pub type Signature = MultiSignature;
|
||||
|
||||
/// Public key of account on Polkadot-like chains.
|
||||
pub type AccountPublic = <Signature as Verify>::Signer;
|
||||
|
||||
/// Id of account on Polkadot-like chains.
|
||||
pub type AccountId = <AccountPublic as IdentifyAccount>::AccountId;
|
||||
|
||||
/// Address of account on Polkadot-like chains.
|
||||
pub type AccountAddress = MultiAddress<AccountId, ()>;
|
||||
|
||||
/// Index of a transaction on the Polkadot-like chains.
|
||||
pub type Nonce = u32;
|
||||
|
||||
/// Block type of Polkadot-like chains.
|
||||
pub type Block = generic::Block<Header, OpaqueExtrinsic>;
|
||||
|
||||
/// Polkadot-like block signed with a Justification.
|
||||
pub type SignedBlock = generic::SignedBlock<Block>;
|
||||
|
||||
/// The balance of an account on Polkadot-like chain.
|
||||
pub type Balance = u128;
|
||||
|
||||
/// Unchecked Extrinsic type.
|
||||
pub type UncheckedExtrinsic<Call, SignedExt> =
|
||||
generic::UncheckedExtrinsic<AccountAddress, EncodedOrDecodedCall<Call>, Signature, SignedExt>;
|
||||
|
||||
/// Account address, used by the Polkadot-like chain.
|
||||
pub type Address = MultiAddress<AccountId, ()>;
|
||||
|
||||
/// Polkadot-like chain.
|
||||
#[derive(RuntimeDebug)]
|
||||
pub struct PolkadotLike;
|
||||
|
||||
impl Chain for PolkadotLike {
|
||||
type BlockNumber = BlockNumber;
|
||||
type Hash = Hash;
|
||||
type Hasher = Hasher;
|
||||
type Header = Header;
|
||||
|
||||
type AccountId = AccountId;
|
||||
type Balance = Balance;
|
||||
type Index = Index;
|
||||
type Signature = Signature;
|
||||
|
||||
fn max_extrinsic_size() -> u32 {
|
||||
*BlockLength::get().max.get(DispatchClass::Normal)
|
||||
}
|
||||
|
||||
fn max_extrinsic_weight() -> Weight {
|
||||
BlockWeights::get()
|
||||
.get(DispatchClass::Normal)
|
||||
.max_extrinsic
|
||||
.unwrap_or(Weight::MAX)
|
||||
}
|
||||
}
|
||||
|
||||
/// Provides a storage key for account data.
|
||||
///
|
||||
/// We need to use this approach when we don't have access to the runtime.
|
||||
/// The equivalent command to invoke in case full `Runtime` is known is this:
|
||||
/// `let key = frame_system::Account::<Runtime>::storage_map_final_key(&account_id);`
|
||||
pub struct AccountInfoStorageMapKeyProvider;
|
||||
|
||||
impl StorageMapKeyProvider for AccountInfoStorageMapKeyProvider {
|
||||
const MAP_NAME: &'static str = "Account";
|
||||
type Hasher = Blake2_128Concat;
|
||||
type Key = AccountId;
|
||||
// This should actually be `AccountInfo`, but we don't use this property in order to decode the
|
||||
// data. So we use `Vec<u8>` as if we would work with encoded data.
|
||||
type Value = Vec<u8>;
|
||||
}
|
||||
|
||||
impl AccountInfoStorageMapKeyProvider {
|
||||
const PALLET_NAME: &'static str = "System";
|
||||
|
||||
pub fn final_key(id: &AccountId) -> StorageKey {
|
||||
<Self as StorageMapKeyProvider>::final_key(Self::PALLET_NAME, id)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn should_generate_storage_key() {
|
||||
let acc = [
|
||||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
|
||||
25, 26, 27, 28, 29, 30, 31, 32,
|
||||
]
|
||||
.into();
|
||||
let key = AccountInfoStorageMapKeyProvider::final_key(&acc);
|
||||
assert_eq!(hex::encode(key), "26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da92dccd599abfe1920a1cff8a7358231430102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Parity Bridges Common is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Primitives of polkadot-like chains, that are related to parachains functionality.
|
||||
//!
|
||||
//! Even though this (bridges) repository references polkadot repository, we can't
|
||||
//! reference polkadot crates from pallets. That's because bridges repository is
|
||||
//! included in the polkadot repository and included pallets are used by polkadot
|
||||
//! chains. Having pallets that are referencing polkadot, would mean that there may
|
||||
//! be two versions of polkadot crates included in the runtime. Which is bad.
|
||||
|
||||
use bp_runtime::{RawStorageProof, Size};
|
||||
use codec::{CompactAs, Decode, Encode, MaxEncodedLen};
|
||||
use frame_support::RuntimeDebug;
|
||||
use scale_info::TypeInfo;
|
||||
use sp_core::Hasher;
|
||||
use sp_std::vec::Vec;
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
use parity_util_mem::MallocSizeOf;
|
||||
|
||||
/// Parachain id.
|
||||
///
|
||||
/// This is an equivalent of the `polkadot_parachain::Id`, which is a compact-encoded `u32`.
|
||||
#[derive(
|
||||
Clone,
|
||||
CompactAs,
|
||||
Copy,
|
||||
Decode,
|
||||
Default,
|
||||
Encode,
|
||||
Eq,
|
||||
Hash,
|
||||
MaxEncodedLen,
|
||||
Ord,
|
||||
PartialEq,
|
||||
PartialOrd,
|
||||
RuntimeDebug,
|
||||
TypeInfo,
|
||||
)]
|
||||
pub struct ParaId(pub u32);
|
||||
|
||||
impl From<u32> for ParaId {
|
||||
fn from(id: u32) -> Self {
|
||||
ParaId(id)
|
||||
}
|
||||
}
|
||||
|
||||
/// Parachain head.
|
||||
///
|
||||
/// This is an equivalent of the `polkadot_parachain::HeadData`.
|
||||
///
|
||||
/// The parachain head means (at least in Cumulus) a SCALE-encoded parachain header.
|
||||
#[derive(
|
||||
PartialEq, Eq, Clone, PartialOrd, Ord, Encode, Decode, RuntimeDebug, TypeInfo, Default,
|
||||
)]
|
||||
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Hash, MallocSizeOf))]
|
||||
pub struct ParaHead(pub Vec<u8>);
|
||||
|
||||
impl ParaHead {
|
||||
/// Returns the hash of this head data.
|
||||
pub fn hash(&self) -> crate::Hash {
|
||||
sp_runtime::traits::BlakeTwo256::hash(&self.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Parachain head hash.
|
||||
pub type ParaHash = crate::Hash;
|
||||
|
||||
/// Parachain head hasher.
|
||||
pub type ParaHasher = crate::Hasher;
|
||||
|
||||
/// Raw storage proof of parachain heads, stored in polkadot-like chain runtime.
|
||||
#[derive(Clone, Decode, Encode, Eq, PartialEq, RuntimeDebug, TypeInfo)]
|
||||
pub struct ParaHeadsProof(pub RawStorageProof);
|
||||
|
||||
impl Size for ParaHeadsProof {
|
||||
fn size(&self) -> u32 {
|
||||
u32::try_from(self.0.iter().fold(0usize, |sum, node| sum.saturating_add(node.len())))
|
||||
.unwrap_or(u32::MAX)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
[package]
|
||||
name = "bp-relayers"
|
||||
description = "Primitives of relayers module."
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2021"
|
||||
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
|
||||
|
||||
[dependencies]
|
||||
codec = { package = "parity-scale-codec", version = "3.1.5", default-features = false, features = ["derive", "bit-vec"] }
|
||||
scale-info = { version = "2.6.0", default-features = false, features = ["bit-vec", "derive"] }
|
||||
|
||||
# Bridge Dependencies
|
||||
|
||||
bp-messages = { path = "../messages", default-features = false }
|
||||
bp-runtime = { path = "../runtime", default-features = false }
|
||||
|
||||
# Substrate Dependencies
|
||||
|
||||
frame-support = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-std = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
|
||||
[dev-dependencies]
|
||||
hex = "0.4"
|
||||
hex-literal = "0.4"
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"bp-messages/std",
|
||||
"bp-runtime/std",
|
||||
"frame-support/std",
|
||||
"sp-runtime/std",
|
||||
"sp-std/std",
|
||||
]
|
||||
@@ -0,0 +1,206 @@
|
||||
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Parity Bridges Common is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Primitives of messages module.
|
||||
|
||||
#![warn(missing_docs)]
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
pub use registration::{Registration, StakeAndSlash};
|
||||
|
||||
use bp_messages::LaneId;
|
||||
use bp_runtime::{ChainId, StorageDoubleMapKeyProvider};
|
||||
use frame_support::{traits::tokens::Preservation, Blake2_128Concat, Identity};
|
||||
use scale_info::TypeInfo;
|
||||
use sp_runtime::{
|
||||
codec::{Codec, Decode, Encode, EncodeLike, MaxEncodedLen},
|
||||
traits::AccountIdConversion,
|
||||
TypeId,
|
||||
};
|
||||
use sp_std::{fmt::Debug, marker::PhantomData};
|
||||
|
||||
mod registration;
|
||||
|
||||
/// The owner of the sovereign account that should pay the rewards.
|
||||
///
|
||||
/// Each of the 2 final points connected by a bridge owns a sovereign account at each end of the
|
||||
/// bridge. So here, at this end of the bridge there can be 2 sovereign accounts that pay rewards.
|
||||
#[derive(Copy, Clone, Debug, Decode, Encode, Eq, PartialEq, TypeInfo, MaxEncodedLen)]
|
||||
pub enum RewardsAccountOwner {
|
||||
/// The sovereign account of the final chain on this end of the bridge.
|
||||
ThisChain,
|
||||
/// The sovereign account of the final chain on the other end of the bridge.
|
||||
BridgedChain,
|
||||
}
|
||||
|
||||
/// Structure used to identify the account that pays a reward to the relayer.
|
||||
///
|
||||
/// A bridge connects 2 bridge ends. Each one is located on a separate relay chain. The bridge ends
|
||||
/// can be the final destinations of the bridge, or they can be intermediary points
|
||||
/// (e.g. a bridge hub) used to forward messages between pairs of parachains on the bridged relay
|
||||
/// chains. A pair of such parachains is connected using a bridge lane. Each of the 2 final
|
||||
/// destinations of a bridge lane must have a sovereign account at each end of the bridge and each
|
||||
/// of the sovereign accounts will pay rewards for different operations. So we need multiple
|
||||
/// parameters to identify the account that pays a reward to the relayer.
|
||||
#[derive(Copy, Clone, Debug, Decode, Encode, Eq, PartialEq, TypeInfo, MaxEncodedLen)]
|
||||
pub struct RewardsAccountParams {
|
||||
lane_id: LaneId,
|
||||
bridged_chain_id: ChainId,
|
||||
owner: RewardsAccountOwner,
|
||||
}
|
||||
|
||||
impl RewardsAccountParams {
|
||||
/// Create a new instance of `RewardsAccountParams`.
|
||||
pub const fn new(
|
||||
lane_id: LaneId,
|
||||
bridged_chain_id: ChainId,
|
||||
owner: RewardsAccountOwner,
|
||||
) -> Self {
|
||||
Self { lane_id, bridged_chain_id, owner }
|
||||
}
|
||||
}
|
||||
|
||||
impl TypeId for RewardsAccountParams {
|
||||
const TYPE_ID: [u8; 4] = *b"brap";
|
||||
}
|
||||
|
||||
/// Reward payment procedure.
|
||||
pub trait PaymentProcedure<Relayer, Reward> {
|
||||
/// Error that may be returned by the procedure.
|
||||
type Error: Debug;
|
||||
|
||||
/// Pay reward to the relayer from the account with provided params.
|
||||
fn pay_reward(
|
||||
relayer: &Relayer,
|
||||
rewards_account_params: RewardsAccountParams,
|
||||
reward: Reward,
|
||||
) -> Result<(), Self::Error>;
|
||||
}
|
||||
|
||||
impl<Relayer, Reward> PaymentProcedure<Relayer, Reward> for () {
|
||||
type Error = &'static str;
|
||||
|
||||
fn pay_reward(_: &Relayer, _: RewardsAccountParams, _: Reward) -> Result<(), Self::Error> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Reward payment procedure that does `balances::transfer` call from the account, derived from
|
||||
/// given params.
|
||||
pub struct PayRewardFromAccount<T, Relayer>(PhantomData<(T, Relayer)>);
|
||||
|
||||
impl<T, Relayer> PayRewardFromAccount<T, Relayer>
|
||||
where
|
||||
Relayer: Decode + Encode,
|
||||
{
|
||||
/// Return account that pays rewards based on the provided parameters.
|
||||
pub fn rewards_account(params: RewardsAccountParams) -> Relayer {
|
||||
params.into_sub_account_truncating(b"rewards-account")
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, Relayer> PaymentProcedure<Relayer, T::Balance> for PayRewardFromAccount<T, Relayer>
|
||||
where
|
||||
T: frame_support::traits::fungible::Mutate<Relayer>,
|
||||
Relayer: Decode + Encode,
|
||||
{
|
||||
type Error = sp_runtime::DispatchError;
|
||||
|
||||
fn pay_reward(
|
||||
relayer: &Relayer,
|
||||
rewards_account_params: RewardsAccountParams,
|
||||
reward: T::Balance,
|
||||
) -> Result<(), Self::Error> {
|
||||
T::transfer(
|
||||
&Self::rewards_account(rewards_account_params),
|
||||
relayer,
|
||||
reward,
|
||||
Preservation::Expendable,
|
||||
)
|
||||
.map(drop)
|
||||
}
|
||||
}
|
||||
|
||||
/// Can be use to access the runtime storage key within the `RelayerRewards` map of the relayers
|
||||
/// pallet.
|
||||
pub struct RelayerRewardsKeyProvider<AccountId, Reward>(PhantomData<(AccountId, Reward)>);
|
||||
|
||||
impl<AccountId, Reward> StorageDoubleMapKeyProvider for RelayerRewardsKeyProvider<AccountId, Reward>
|
||||
where
|
||||
AccountId: Codec + EncodeLike,
|
||||
Reward: Codec + EncodeLike,
|
||||
{
|
||||
const MAP_NAME: &'static str = "RelayerRewards";
|
||||
|
||||
type Hasher1 = Blake2_128Concat;
|
||||
type Key1 = AccountId;
|
||||
type Hasher2 = Identity;
|
||||
type Key2 = RewardsAccountParams;
|
||||
type Value = Reward;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use bp_messages::LaneId;
|
||||
use sp_runtime::testing::H256;
|
||||
|
||||
#[test]
|
||||
fn different_lanes_are_using_different_accounts() {
|
||||
assert_eq!(
|
||||
PayRewardFromAccount::<(), H256>::rewards_account(RewardsAccountParams::new(
|
||||
LaneId([0, 0, 0, 0]),
|
||||
*b"test",
|
||||
RewardsAccountOwner::ThisChain
|
||||
)),
|
||||
hex_literal::hex!("62726170000000007465737400726577617264732d6163636f756e7400000000")
|
||||
.into(),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
PayRewardFromAccount::<(), H256>::rewards_account(RewardsAccountParams::new(
|
||||
LaneId([0, 0, 0, 1]),
|
||||
*b"test",
|
||||
RewardsAccountOwner::ThisChain
|
||||
)),
|
||||
hex_literal::hex!("62726170000000017465737400726577617264732d6163636f756e7400000000")
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn different_directions_are_using_different_accounts() {
|
||||
assert_eq!(
|
||||
PayRewardFromAccount::<(), H256>::rewards_account(RewardsAccountParams::new(
|
||||
LaneId([0, 0, 0, 0]),
|
||||
*b"test",
|
||||
RewardsAccountOwner::ThisChain
|
||||
)),
|
||||
hex_literal::hex!("62726170000000007465737400726577617264732d6163636f756e7400000000")
|
||||
.into(),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
PayRewardFromAccount::<(), H256>::rewards_account(RewardsAccountParams::new(
|
||||
LaneId([0, 0, 0, 0]),
|
||||
*b"test",
|
||||
RewardsAccountOwner::BridgedChain
|
||||
)),
|
||||
hex_literal::hex!("62726170000000007465737401726577617264732d6163636f756e7400000000")
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
// Copyright 2021 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Parity Bridges Common is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Bridge relayers registration and slashing scheme.
|
||||
//!
|
||||
//! There is an option to add a refund-relayer signed extension that will compensate
|
||||
//! relayer costs of the message delivery and confirmation transactions (as well as
|
||||
//! required finality proofs). This extension boosts priority of message delivery
|
||||
//! transactions, based on the number of bundled messages. So transaction with more
|
||||
//! messages has larger priority than the transaction with less messages.
|
||||
//! See `bridge_runtime_common::priority_calculator` for details;
|
||||
//!
|
||||
//! This encourages relayers to include more messages to their delivery transactions.
|
||||
//! At the same time, we are not verifying storage proofs before boosting
|
||||
//! priority. Instead, we simply trust relayer, when it says that transaction delivers
|
||||
//! `N` messages.
|
||||
//!
|
||||
//! This allows relayers to submit transactions which declare large number of bundled
|
||||
//! transactions to receive priority boost for free, potentially pushing actual delivery
|
||||
//! transactions from the block (or even transaction queue). Such transactions are
|
||||
//! not free, but their cost is relatively small.
|
||||
//!
|
||||
//! To alleviate that, we only boost transactions of relayers that have some stake
|
||||
//! that guarantees that their transactions are valid. Such relayers get priority
|
||||
//! for free, but they risk to lose their stake.
|
||||
|
||||
use crate::RewardsAccountParams;
|
||||
|
||||
use codec::{Decode, Encode, MaxEncodedLen};
|
||||
use scale_info::TypeInfo;
|
||||
use sp_runtime::{
|
||||
traits::{Get, Zero},
|
||||
DispatchError, DispatchResult,
|
||||
};
|
||||
|
||||
/// Relayer registration.
|
||||
#[derive(Copy, Clone, Debug, Decode, Encode, Eq, PartialEq, TypeInfo, MaxEncodedLen)]
|
||||
pub struct Registration<BlockNumber, Balance> {
|
||||
/// The last block number, where this registration is considered active.
|
||||
///
|
||||
/// Relayer has an option to renew his registration (this may be done before it
|
||||
/// is spoiled as well). Starting from block `valid_till + 1`, relayer may `deregister`
|
||||
/// himself and get his stake back.
|
||||
///
|
||||
/// Please keep in mind that priority boost stops working some blocks before the
|
||||
/// registration ends (see [`StakeAndSlash::RequiredRegistrationLease`]).
|
||||
pub valid_till: BlockNumber,
|
||||
/// Active relayer stake, which is mapped to the relayer reserved balance.
|
||||
///
|
||||
/// If `stake` is less than the [`StakeAndSlash::RequiredStake`], the registration
|
||||
/// is considered inactive even if `valid_till + 1` is not yet reached.
|
||||
pub stake: Balance,
|
||||
}
|
||||
|
||||
/// Relayer stake-and-slash mechanism.
|
||||
pub trait StakeAndSlash<AccountId, BlockNumber, Balance> {
|
||||
/// The stake that the relayer must have to have its transactions boosted.
|
||||
type RequiredStake: Get<Balance>;
|
||||
/// Required **remaining** registration lease to be able to get transaction priority boost.
|
||||
///
|
||||
/// If the difference between registration's `valid_till` and the current block number
|
||||
/// is less than the `RequiredRegistrationLease`, it becomes inactive and relayer transaction
|
||||
/// won't get priority boost. This period exists, because priority is calculated when
|
||||
/// transaction is placed to the queue (and it is reevaluated periodically) and then some time
|
||||
/// may pass before transaction will be included into the block.
|
||||
type RequiredRegistrationLease: Get<BlockNumber>;
|
||||
|
||||
/// Reserve the given amount at relayer account.
|
||||
fn reserve(relayer: &AccountId, amount: Balance) -> DispatchResult;
|
||||
/// `Unreserve` the given amount from relayer account.
|
||||
///
|
||||
/// Returns amount that we have failed to `unreserve`.
|
||||
fn unreserve(relayer: &AccountId, amount: Balance) -> Balance;
|
||||
/// Slash up to `amount` from reserved balance of account `relayer` and send funds to given
|
||||
/// `beneficiary`.
|
||||
///
|
||||
/// Returns `Ok(_)` with non-zero balance if we have failed to repatriate some portion of stake.
|
||||
fn repatriate_reserved(
|
||||
relayer: &AccountId,
|
||||
beneficiary: RewardsAccountParams,
|
||||
amount: Balance,
|
||||
) -> Result<Balance, DispatchError>;
|
||||
}
|
||||
|
||||
impl<AccountId, BlockNumber, Balance> StakeAndSlash<AccountId, BlockNumber, Balance> for ()
|
||||
where
|
||||
Balance: Default + Zero,
|
||||
BlockNumber: Default,
|
||||
{
|
||||
type RequiredStake = ();
|
||||
type RequiredRegistrationLease = ();
|
||||
|
||||
fn reserve(_relayer: &AccountId, _amount: Balance) -> DispatchResult {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn unreserve(_relayer: &AccountId, _amount: Balance) -> Balance {
|
||||
Zero::zero()
|
||||
}
|
||||
|
||||
fn repatriate_reserved(
|
||||
_relayer: &AccountId,
|
||||
_beneficiary: RewardsAccountParams,
|
||||
_amount: Balance,
|
||||
) -> Result<Balance, DispatchError> {
|
||||
Ok(Zero::zero())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
[package]
|
||||
name = "bp-runtime"
|
||||
description = "Primitives that may be used at (bridges) runtime level."
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2021"
|
||||
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
|
||||
|
||||
[dependencies]
|
||||
codec = { package = "parity-scale-codec", version = "3.1.5", default-features = false }
|
||||
hash-db = { version = "0.16.0", default-features = false }
|
||||
impl-trait-for-tuples = "0.2.2"
|
||||
num-traits = { version = "0.2", default-features = false }
|
||||
scale-info = { version = "2.6.0", default-features = false, features = ["derive"] }
|
||||
serde = { version = "1.0", optional = true, features = ["derive"] }
|
||||
|
||||
# Substrate Dependencies
|
||||
|
||||
frame-support = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
frame-system = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-core = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-io = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-state-machine = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-std = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-trie = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
trie-db = { version = "0.27.1", default-features = false }
|
||||
|
||||
[dev-dependencies]
|
||||
hex-literal = "0.4"
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"codec/std",
|
||||
"frame-support/std",
|
||||
"frame-system/std",
|
||||
"hash-db/std",
|
||||
"num-traits/std",
|
||||
"scale-info/std",
|
||||
"serde",
|
||||
"sp-core/std",
|
||||
"sp-io/std",
|
||||
"sp-runtime/std",
|
||||
"sp-std/std",
|
||||
"sp-state-machine/std",
|
||||
"sp-trie/std",
|
||||
"trie-db/std",
|
||||
]
|
||||
@@ -0,0 +1,375 @@
|
||||
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Parity Bridges Common is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
use crate::HeaderIdProvider;
|
||||
use codec::{Decode, Encode, MaxEncodedLen};
|
||||
use frame_support::{weights::Weight, Parameter};
|
||||
use num_traits::{AsPrimitive, Bounded, CheckedSub, Saturating, SaturatingAdd, Zero};
|
||||
use sp_runtime::{
|
||||
traits::{
|
||||
AtLeast32Bit, AtLeast32BitUnsigned, Hash as HashT, Header as HeaderT, MaybeDisplay,
|
||||
MaybeSerialize, MaybeSerializeDeserialize, Member, SimpleBitOps, Verify,
|
||||
},
|
||||
FixedPointOperand,
|
||||
};
|
||||
use sp_std::{convert::TryFrom, fmt::Debug, hash::Hash, str::FromStr, vec, vec::Vec};
|
||||
|
||||
/// Chain call, that is either SCALE-encoded, or decoded.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum EncodedOrDecodedCall<ChainCall> {
|
||||
/// The call that is SCALE-encoded.
|
||||
///
|
||||
/// This variant is used when we the chain runtime is not bundled with the relay, but
|
||||
/// we still need the represent call in some RPC calls or transactions.
|
||||
Encoded(Vec<u8>),
|
||||
/// The decoded call.
|
||||
Decoded(ChainCall),
|
||||
}
|
||||
|
||||
impl<ChainCall: Clone + Decode> EncodedOrDecodedCall<ChainCall> {
|
||||
/// Returns decoded call.
|
||||
pub fn to_decoded(&self) -> Result<ChainCall, codec::Error> {
|
||||
match self {
|
||||
Self::Encoded(ref encoded_call) =>
|
||||
ChainCall::decode(&mut &encoded_call[..]).map_err(Into::into),
|
||||
Self::Decoded(ref decoded_call) => Ok(decoded_call.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts self to decoded call.
|
||||
pub fn into_decoded(self) -> Result<ChainCall, codec::Error> {
|
||||
match self {
|
||||
Self::Encoded(encoded_call) =>
|
||||
ChainCall::decode(&mut &encoded_call[..]).map_err(Into::into),
|
||||
Self::Decoded(decoded_call) => Ok(decoded_call),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<ChainCall> From<ChainCall> for EncodedOrDecodedCall<ChainCall> {
|
||||
fn from(call: ChainCall) -> EncodedOrDecodedCall<ChainCall> {
|
||||
EncodedOrDecodedCall::Decoded(call)
|
||||
}
|
||||
}
|
||||
|
||||
impl<ChainCall: Decode> Decode for EncodedOrDecodedCall<ChainCall> {
|
||||
fn decode<I: codec::Input>(input: &mut I) -> Result<Self, codec::Error> {
|
||||
// having encoded version is better than decoded, because decoding isn't required
|
||||
// everywhere and for mocked calls it may lead to **unneeded** errors
|
||||
match input.remaining_len()? {
|
||||
Some(remaining_len) => {
|
||||
let mut encoded_call = vec![0u8; remaining_len];
|
||||
input.read(&mut encoded_call)?;
|
||||
Ok(EncodedOrDecodedCall::Encoded(encoded_call))
|
||||
},
|
||||
None => Ok(EncodedOrDecodedCall::Decoded(ChainCall::decode(input)?)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<ChainCall: Encode> Encode for EncodedOrDecodedCall<ChainCall> {
|
||||
fn encode(&self) -> Vec<u8> {
|
||||
match *self {
|
||||
Self::Encoded(ref encoded_call) => encoded_call.clone(),
|
||||
Self::Decoded(ref decoded_call) => decoded_call.encode(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Minimal Substrate-based chain representation that may be used from no_std environment.
|
||||
pub trait Chain: Send + Sync + 'static {
|
||||
/// A type that fulfills the abstract idea of what a Substrate block number is.
|
||||
// Constraits come from the associated Number type of `sp_runtime::traits::Header`
|
||||
// See here for more info:
|
||||
// https://crates.parity.io/sp_runtime/traits/trait.Header.html#associatedtype.Number
|
||||
//
|
||||
// Note that the `AsPrimitive<usize>` trait is required by the GRANDPA justification
|
||||
// verifier, and is not usually part of a Substrate Header's Number type.
|
||||
type BlockNumber: Parameter
|
||||
+ Member
|
||||
+ MaybeSerializeDeserialize
|
||||
+ Hash
|
||||
+ Copy
|
||||
+ Default
|
||||
+ MaybeDisplay
|
||||
+ AtLeast32BitUnsigned
|
||||
+ FromStr
|
||||
+ AsPrimitive<usize>
|
||||
+ Default
|
||||
+ Saturating
|
||||
+ MaxEncodedLen;
|
||||
|
||||
/// A type that fulfills the abstract idea of what a Substrate hash is.
|
||||
// Constraits come from the associated Hash type of `sp_runtime::traits::Header`
|
||||
// See here for more info:
|
||||
// https://crates.parity.io/sp_runtime/traits/trait.Header.html#associatedtype.Hash
|
||||
type Hash: Parameter
|
||||
+ Member
|
||||
+ MaybeSerializeDeserialize
|
||||
+ Hash
|
||||
+ Ord
|
||||
+ Copy
|
||||
+ MaybeDisplay
|
||||
+ Default
|
||||
+ SimpleBitOps
|
||||
+ AsRef<[u8]>
|
||||
+ AsMut<[u8]>
|
||||
+ MaxEncodedLen;
|
||||
|
||||
/// A type that fulfills the abstract idea of what a Substrate hasher (a type
|
||||
/// that produces hashes) is.
|
||||
// Constraits come from the associated Hashing type of `sp_runtime::traits::Header`
|
||||
// See here for more info:
|
||||
// https://crates.parity.io/sp_runtime/traits/trait.Header.html#associatedtype.Hashing
|
||||
type Hasher: HashT<Output = Self::Hash>;
|
||||
|
||||
/// A type that fulfills the abstract idea of what a Substrate header is.
|
||||
// See here for more info:
|
||||
// https://crates.parity.io/sp_runtime/traits/trait.Header.html
|
||||
type Header: Parameter
|
||||
+ HeaderT<Number = Self::BlockNumber, Hash = Self::Hash>
|
||||
+ HeaderIdProvider<Self::Header>
|
||||
+ MaybeSerializeDeserialize;
|
||||
|
||||
/// The user account identifier type for the runtime.
|
||||
type AccountId: Parameter
|
||||
+ Member
|
||||
+ MaybeSerializeDeserialize
|
||||
+ Debug
|
||||
+ MaybeDisplay
|
||||
+ Ord
|
||||
+ MaxEncodedLen;
|
||||
/// Balance of an account in native tokens.
|
||||
///
|
||||
/// The chain may support multiple tokens, but this particular type is for token that is used
|
||||
/// to pay for transaction dispatch, to reward different relayers (headers, messages), etc.
|
||||
type Balance: AtLeast32BitUnsigned
|
||||
+ FixedPointOperand
|
||||
+ Parameter
|
||||
+ Member
|
||||
+ MaybeSerializeDeserialize
|
||||
+ Clone
|
||||
+ Copy
|
||||
+ Bounded
|
||||
+ CheckedSub
|
||||
+ PartialOrd
|
||||
+ SaturatingAdd
|
||||
+ Zero
|
||||
+ TryFrom<sp_core::U256>
|
||||
+ MaxEncodedLen;
|
||||
/// Index of a transaction used by the chain.
|
||||
type Index: Parameter
|
||||
+ Member
|
||||
+ MaybeSerialize
|
||||
+ Debug
|
||||
+ Default
|
||||
+ MaybeDisplay
|
||||
+ MaybeSerializeDeserialize
|
||||
+ AtLeast32Bit
|
||||
+ Copy
|
||||
+ MaxEncodedLen;
|
||||
/// Signature type, used on this chain.
|
||||
type Signature: Parameter + Verify;
|
||||
|
||||
/// Get the maximum size (in bytes) of a Normal extrinsic at this chain.
|
||||
fn max_extrinsic_size() -> u32;
|
||||
/// Get the maximum weight (compute time) that a Normal extrinsic at this chain can use.
|
||||
fn max_extrinsic_weight() -> Weight;
|
||||
}
|
||||
|
||||
/// A trait that provides the type of the underlying chain.
|
||||
pub trait UnderlyingChainProvider {
|
||||
/// Underlying chain type.
|
||||
type Chain: Chain;
|
||||
}
|
||||
|
||||
impl<T> Chain for T
|
||||
where
|
||||
T: Send + Sync + 'static + UnderlyingChainProvider,
|
||||
{
|
||||
type BlockNumber = <T::Chain as Chain>::BlockNumber;
|
||||
type Hash = <T::Chain as Chain>::Hash;
|
||||
type Hasher = <T::Chain as Chain>::Hasher;
|
||||
type Header = <T::Chain as Chain>::Header;
|
||||
type AccountId = <T::Chain as Chain>::AccountId;
|
||||
type Balance = <T::Chain as Chain>::Balance;
|
||||
type Index = <T::Chain as Chain>::Index;
|
||||
type Signature = <T::Chain as Chain>::Signature;
|
||||
|
||||
fn max_extrinsic_size() -> u32 {
|
||||
<T::Chain as Chain>::max_extrinsic_size()
|
||||
}
|
||||
|
||||
fn max_extrinsic_weight() -> Weight {
|
||||
<T::Chain as Chain>::max_extrinsic_weight()
|
||||
}
|
||||
}
|
||||
|
||||
/// Minimal parachain representation that may be used from no_std environment.
|
||||
pub trait Parachain: Chain {
|
||||
/// Parachain identifier.
|
||||
const PARACHAIN_ID: u32;
|
||||
}
|
||||
|
||||
impl<T> Parachain for T
|
||||
where
|
||||
T: Chain + UnderlyingChainProvider,
|
||||
<T as UnderlyingChainProvider>::Chain: Parachain,
|
||||
{
|
||||
const PARACHAIN_ID: u32 = <<T as UnderlyingChainProvider>::Chain as Parachain>::PARACHAIN_ID;
|
||||
}
|
||||
|
||||
/// Underlying chain type.
|
||||
pub type UnderlyingChainOf<C> = <C as UnderlyingChainProvider>::Chain;
|
||||
|
||||
/// Block number used by the chain.
|
||||
pub type BlockNumberOf<C> = <C as Chain>::BlockNumber;
|
||||
|
||||
/// Hash type used by the chain.
|
||||
pub type HashOf<C> = <C as Chain>::Hash;
|
||||
|
||||
/// Hasher type used by the chain.
|
||||
pub type HasherOf<C> = <C as Chain>::Hasher;
|
||||
|
||||
/// Header type used by the chain.
|
||||
pub type HeaderOf<C> = <C as Chain>::Header;
|
||||
|
||||
/// Account id type used by the chain.
|
||||
pub type AccountIdOf<C> = <C as Chain>::AccountId;
|
||||
|
||||
/// Balance type used by the chain.
|
||||
pub type BalanceOf<C> = <C as Chain>::Balance;
|
||||
|
||||
/// Transaction index type used by the chain.
|
||||
pub type IndexOf<C> = <C as Chain>::Index;
|
||||
|
||||
/// Signature type used by the chain.
|
||||
pub type SignatureOf<C> = <C as Chain>::Signature;
|
||||
|
||||
/// Account public type used by the chain.
|
||||
pub type AccountPublicOf<C> = <SignatureOf<C> as Verify>::Signer;
|
||||
|
||||
/// Transaction era used by the chain.
|
||||
pub type TransactionEraOf<C> = crate::TransactionEra<BlockNumberOf<C>, HashOf<C>>;
|
||||
|
||||
/// Convenience macro that declares bridge finality runtime apis and related constants for a chain.
|
||||
/// This includes:
|
||||
/// - chain-specific bridge runtime APIs:
|
||||
/// - `<ThisChain>FinalityApi`
|
||||
/// - constants that are stringified names of runtime API methods:
|
||||
/// - `BEST_FINALIZED_<THIS_CHAIN>_HEADER_METHOD`
|
||||
/// The name of the chain has to be specified in snake case (e.g. `rialto_parachain`).
|
||||
#[macro_export]
|
||||
macro_rules! decl_bridge_finality_runtime_apis {
|
||||
($chain: ident) => {
|
||||
bp_runtime::paste::item! {
|
||||
mod [<$chain _finality_api>] {
|
||||
use super::*;
|
||||
|
||||
/// Name of the `<ThisChain>FinalityApi::best_finalized` runtime method.
|
||||
pub const [<BEST_FINALIZED_ $chain:upper _HEADER_METHOD>]: &str =
|
||||
stringify!([<$chain:camel FinalityApi_best_finalized>]);
|
||||
|
||||
sp_api::decl_runtime_apis! {
|
||||
/// API for querying information about the finalized chain headers.
|
||||
///
|
||||
/// This API is implemented by runtimes that are receiving messages from this chain, not by this
|
||||
/// chain's runtime itself.
|
||||
pub trait [<$chain:camel FinalityApi>] {
|
||||
/// Returns number and hash of the best finalized header known to the bridge module.
|
||||
fn best_finalized() -> Option<bp_runtime::HeaderId<Hash, BlockNumber>>;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub use [<$chain _finality_api>]::*;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// Convenience macro that declares bridge messages runtime apis and related constants for a chain.
|
||||
/// This includes:
|
||||
/// - chain-specific bridge runtime APIs:
|
||||
/// - `To<ThisChain>OutboundLaneApi`
|
||||
/// - `From<ThisChain>InboundLaneApi`
|
||||
/// - constants that are stringified names of runtime API methods:
|
||||
/// - `FROM_<THIS_CHAIN>_MESSAGE_DETAILS_METHOD`,
|
||||
/// The name of the chain has to be specified in snake case (e.g. `rialto_parachain`).
|
||||
#[macro_export]
|
||||
macro_rules! decl_bridge_messages_runtime_apis {
|
||||
($chain: ident) => {
|
||||
bp_runtime::paste::item! {
|
||||
mod [<$chain _messages_api>] {
|
||||
use super::*;
|
||||
|
||||
/// Name of the `To<ThisChain>OutboundLaneApi::message_details` runtime method.
|
||||
pub const [<TO_ $chain:upper _MESSAGE_DETAILS_METHOD>]: &str =
|
||||
stringify!([<To $chain:camel OutboundLaneApi_message_details>]);
|
||||
|
||||
/// Name of the `From<ThisChain>InboundLaneApi::message_details` runtime method.
|
||||
pub const [<FROM_ $chain:upper _MESSAGE_DETAILS_METHOD>]: &str =
|
||||
stringify!([<From $chain:camel InboundLaneApi_message_details>]);
|
||||
|
||||
sp_api::decl_runtime_apis! {
|
||||
/// Outbound message lane API for messages that are sent to this chain.
|
||||
///
|
||||
/// This API is implemented by runtimes that are receiving messages from this chain, not by this
|
||||
/// chain's runtime itself.
|
||||
pub trait [<To $chain:camel OutboundLaneApi>] {
|
||||
/// Returns dispatch weight, encoded payload size and delivery+dispatch fee of all
|
||||
/// messages in given inclusive range.
|
||||
///
|
||||
/// If some (or all) messages are missing from the storage, they'll also will
|
||||
/// be missing from the resulting vector. The vector is ordered by the nonce.
|
||||
fn message_details(
|
||||
lane: LaneId,
|
||||
begin: MessageNonce,
|
||||
end: MessageNonce,
|
||||
) -> Vec<OutboundMessageDetails>;
|
||||
}
|
||||
|
||||
/// Inbound message lane API for messages sent by this chain.
|
||||
///
|
||||
/// This API is implemented by runtimes that are receiving messages from this chain, not by this
|
||||
/// chain's runtime itself.
|
||||
///
|
||||
/// Entries of the resulting vector are matching entries of the `messages` vector. Entries of the
|
||||
/// `messages` vector may (and need to) be read using `To<ThisChain>OutboundLaneApi::message_details`.
|
||||
pub trait [<From $chain:camel InboundLaneApi>] {
|
||||
/// Return details of given inbound messages.
|
||||
fn message_details(
|
||||
lane: LaneId,
|
||||
messages: Vec<(MessagePayload, OutboundMessageDetails)>,
|
||||
) -> Vec<InboundMessageDetails>;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub use [<$chain _messages_api>]::*;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// Convenience macro that declares bridge finality runtime apis, bridge messages runtime apis
|
||||
/// and related constants for a chain.
|
||||
/// The name of the chain has to be specified in snake case (e.g. `rialto_parachain`).
|
||||
#[macro_export]
|
||||
macro_rules! decl_bridge_runtime_apis {
|
||||
($chain: ident) => {
|
||||
bp_runtime::decl_bridge_finality_runtime_apis!($chain);
|
||||
bp_runtime::decl_bridge_messages_runtime_apis!($chain);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Parity Bridges Common is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Primitives that may be used for creating signed extensions for indirect runtimes.
|
||||
|
||||
use codec::{Compact, Decode, Encode};
|
||||
use impl_trait_for_tuples::impl_for_tuples;
|
||||
use scale_info::{StaticTypeInfo, TypeInfo};
|
||||
use sp_runtime::{
|
||||
traits::{DispatchInfoOf, SignedExtension},
|
||||
transaction_validity::TransactionValidityError,
|
||||
};
|
||||
use sp_std::{fmt::Debug, marker::PhantomData};
|
||||
|
||||
/// Trait that describes some properties of a `SignedExtension` that are needed in order to send a
|
||||
/// transaction to the chain.
|
||||
pub trait SignedExtensionSchema: Encode + Decode + Debug + Eq + Clone + StaticTypeInfo {
|
||||
/// A type of the data encoded as part of the transaction.
|
||||
type Payload: Encode + Decode + Debug + Eq + Clone + StaticTypeInfo;
|
||||
/// Parameters which are part of the payload used to produce transaction signature,
|
||||
/// but don't end up in the transaction itself (i.e. inherent part of the runtime).
|
||||
type AdditionalSigned: Encode + Debug + Eq + Clone + StaticTypeInfo;
|
||||
}
|
||||
|
||||
// An implementation of `SignedExtensionSchema` using generic params.
|
||||
#[derive(Encode, Decode, Clone, Debug, PartialEq, Eq, TypeInfo)]
|
||||
pub struct GenericSignedExtensionSchema<P, S>(PhantomData<(P, S)>);
|
||||
|
||||
impl<P, S> SignedExtensionSchema for GenericSignedExtensionSchema<P, S>
|
||||
where
|
||||
P: Encode + Decode + Debug + Eq + Clone + StaticTypeInfo,
|
||||
S: Encode + Debug + Eq + Clone + StaticTypeInfo,
|
||||
{
|
||||
type Payload = P;
|
||||
type AdditionalSigned = S;
|
||||
}
|
||||
|
||||
/// The `SignedExtensionSchema` for `frame_system::CheckNonZeroSender`.
|
||||
pub type CheckNonZeroSender = GenericSignedExtensionSchema<(), ()>;
|
||||
|
||||
/// The `SignedExtensionSchema` for `frame_system::CheckSpecVersion`.
|
||||
pub type CheckSpecVersion = GenericSignedExtensionSchema<(), u32>;
|
||||
|
||||
/// The `SignedExtensionSchema` for `frame_system::CheckTxVersion`.
|
||||
pub type CheckTxVersion = GenericSignedExtensionSchema<(), u32>;
|
||||
|
||||
/// The `SignedExtensionSchema` for `frame_system::CheckGenesis`.
|
||||
pub type CheckGenesis<Hash> = GenericSignedExtensionSchema<(), Hash>;
|
||||
|
||||
/// The `SignedExtensionSchema` for `frame_system::CheckEra`.
|
||||
pub type CheckEra<Hash> = GenericSignedExtensionSchema<sp_runtime::generic::Era, Hash>;
|
||||
|
||||
/// The `SignedExtensionSchema` for `frame_system::CheckNonce`.
|
||||
pub type CheckNonce<TxNonce> = GenericSignedExtensionSchema<Compact<TxNonce>, ()>;
|
||||
|
||||
/// The `SignedExtensionSchema` for `frame_system::CheckWeight`.
|
||||
pub type CheckWeight = GenericSignedExtensionSchema<(), ()>;
|
||||
|
||||
/// The `SignedExtensionSchema` for `pallet_transaction_payment::ChargeTransactionPayment`.
|
||||
pub type ChargeTransactionPayment<Balance> = GenericSignedExtensionSchema<Compact<Balance>, ()>;
|
||||
|
||||
/// The `SignedExtensionSchema` for `BridgeRejectObsoleteHeadersAndMessages`.
|
||||
pub type BridgeRejectObsoleteHeadersAndMessages = GenericSignedExtensionSchema<(), ()>;
|
||||
|
||||
/// The `SignedExtensionSchema` for `RefundBridgedParachainMessages`.
|
||||
/// This schema is dedicated for `RefundBridgedParachainMessages` signed extension as
|
||||
/// wildcard/placeholder, which relies on the scale encoding for `()` or `((), ())`, or `((), (),
|
||||
/// ())` is the same. So runtime can contains any kind of tuple:
|
||||
/// `(BridgeRefundBridgeHubRococoMessages)`
|
||||
/// `(BridgeRefundBridgeHubRococoMessages, BridgeRefundBridgeHubWococoMessages)`
|
||||
/// `(BridgeRefundParachainMessages1, ..., BridgeRefundParachainMessagesN)`
|
||||
pub type RefundBridgedParachainMessagesSchema = GenericSignedExtensionSchema<(), ()>;
|
||||
|
||||
#[impl_for_tuples(1, 12)]
|
||||
impl SignedExtensionSchema for Tuple {
|
||||
for_tuples!( type Payload = ( #( Tuple::Payload ),* ); );
|
||||
for_tuples!( type AdditionalSigned = ( #( Tuple::AdditionalSigned ),* ); );
|
||||
}
|
||||
|
||||
/// A simplified version of signed extensions meant for producing signed transactions
|
||||
/// and signed payloads in the client code.
|
||||
#[derive(Encode, Decode, Debug, PartialEq, Eq, Clone, TypeInfo)]
|
||||
pub struct GenericSignedExtension<S: SignedExtensionSchema> {
|
||||
pub payload: S::Payload,
|
||||
#[codec(skip)]
|
||||
// It may be set to `None` if extensions are decoded. We are never reconstructing transactions
|
||||
// (and it makes no sense to do that) => decoded version of `SignedExtensions` is only used to
|
||||
// read fields of the `payload`. And when resigning transaction, we're reconstructing
|
||||
// `SignedExtensions` from the scratch.
|
||||
additional_signed: Option<S::AdditionalSigned>,
|
||||
}
|
||||
|
||||
impl<S: SignedExtensionSchema> GenericSignedExtension<S> {
|
||||
pub fn new(payload: S::Payload, additional_signed: Option<S::AdditionalSigned>) -> Self {
|
||||
Self { payload, additional_signed }
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> SignedExtension for GenericSignedExtension<S>
|
||||
where
|
||||
S: SignedExtensionSchema,
|
||||
S::Payload: Send + Sync,
|
||||
S::AdditionalSigned: Send + Sync,
|
||||
{
|
||||
const IDENTIFIER: &'static str = "Not needed.";
|
||||
type AccountId = ();
|
||||
type Call = ();
|
||||
type AdditionalSigned = S::AdditionalSigned;
|
||||
type Pre = ();
|
||||
|
||||
fn additional_signed(&self) -> Result<Self::AdditionalSigned, TransactionValidityError> {
|
||||
// we shall not ever see this error in relay, because we are never signing decoded
|
||||
// transactions. Instead we're constructing and signing new transactions. So the error code
|
||||
// is kinda random here
|
||||
self.additional_signed.clone().ok_or(
|
||||
frame_support::unsigned::TransactionValidityError::Unknown(
|
||||
frame_support::unsigned::UnknownTransaction::Custom(0xFF),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
fn pre_dispatch(
|
||||
self,
|
||||
_who: &Self::AccountId,
|
||||
_call: &Self::Call,
|
||||
_info: &DispatchInfoOf<Self::Call>,
|
||||
_len: usize,
|
||||
) -> Result<Self::Pre, TransactionValidityError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,573 @@
|
||||
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Parity Bridges Common is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Primitives that may be used at (bridges) runtime level.
|
||||
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
use codec::{Decode, Encode, FullCodec, MaxEncodedLen};
|
||||
use frame_support::{
|
||||
log, pallet_prelude::DispatchResult, weights::Weight, PalletError, RuntimeDebug, StorageHasher,
|
||||
StorageValue,
|
||||
};
|
||||
use frame_system::RawOrigin;
|
||||
use scale_info::TypeInfo;
|
||||
use sp_core::storage::StorageKey;
|
||||
use sp_runtime::traits::{BadOrigin, Header as HeaderT, UniqueSaturatedInto};
|
||||
use sp_std::{convert::TryFrom, fmt::Debug, ops::RangeInclusive, vec, vec::Vec};
|
||||
|
||||
pub use chain::{
|
||||
AccountIdOf, AccountPublicOf, BalanceOf, BlockNumberOf, Chain, EncodedOrDecodedCall, HashOf,
|
||||
HasherOf, HeaderOf, IndexOf, Parachain, SignatureOf, TransactionEraOf, UnderlyingChainOf,
|
||||
UnderlyingChainProvider,
|
||||
};
|
||||
pub use frame_support::storage::storage_prefix as storage_value_final_key;
|
||||
use num_traits::{CheckedAdd, CheckedSub, One};
|
||||
pub use storage_proof::{
|
||||
record_all_keys as record_all_trie_keys, Error as StorageProofError,
|
||||
ProofSize as StorageProofSize, RawStorageProof, StorageProofChecker,
|
||||
};
|
||||
pub use storage_types::BoundedStorageValue;
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
pub use storage_proof::craft_valid_storage_proof;
|
||||
|
||||
pub mod extensions;
|
||||
pub mod messages;
|
||||
|
||||
mod chain;
|
||||
mod storage_proof;
|
||||
mod storage_types;
|
||||
|
||||
// Re-export macro to aviod include paste dependency everywhere
|
||||
pub use sp_runtime::paste;
|
||||
|
||||
/// Use this when something must be shared among all instances.
|
||||
pub const NO_INSTANCE_ID: ChainId = [0, 0, 0, 0];
|
||||
|
||||
/// Rialto chain id.
|
||||
pub const RIALTO_CHAIN_ID: ChainId = *b"rlto";
|
||||
|
||||
/// RialtoParachain chain id.
|
||||
pub const RIALTO_PARACHAIN_CHAIN_ID: ChainId = *b"rlpa";
|
||||
|
||||
/// Millau chain id.
|
||||
pub const MILLAU_CHAIN_ID: ChainId = *b"mlau";
|
||||
|
||||
/// Polkadot chain id.
|
||||
pub const POLKADOT_CHAIN_ID: ChainId = *b"pdot";
|
||||
|
||||
/// Kusama chain id.
|
||||
pub const KUSAMA_CHAIN_ID: ChainId = *b"ksma";
|
||||
|
||||
/// Westend chain id.
|
||||
pub const WESTEND_CHAIN_ID: ChainId = *b"wend";
|
||||
|
||||
/// Westend chain id.
|
||||
pub const WESTMINT_CHAIN_ID: ChainId = *b"wmnt";
|
||||
|
||||
/// Rococo chain id.
|
||||
pub const ROCOCO_CHAIN_ID: ChainId = *b"roco";
|
||||
|
||||
/// Wococo chain id.
|
||||
pub const WOCOCO_CHAIN_ID: ChainId = *b"woco";
|
||||
|
||||
/// BridgeHubRococo chain id.
|
||||
pub const BRIDGE_HUB_ROCOCO_CHAIN_ID: ChainId = *b"bhro";
|
||||
|
||||
/// BridgeHubWococo chain id.
|
||||
pub const BRIDGE_HUB_WOCOCO_CHAIN_ID: ChainId = *b"bhwo";
|
||||
|
||||
/// BridgeHubKusama chain id.
|
||||
pub const BRIDGE_HUB_KUSAMA_CHAIN_ID: ChainId = *b"bhks";
|
||||
|
||||
/// BridgeHubPolkadot chain id.
|
||||
pub const BRIDGE_HUB_POLKADOT_CHAIN_ID: ChainId = *b"bhwo";
|
||||
|
||||
/// Generic header Id.
|
||||
#[derive(
|
||||
RuntimeDebug,
|
||||
Default,
|
||||
Clone,
|
||||
Encode,
|
||||
Decode,
|
||||
Copy,
|
||||
Eq,
|
||||
Hash,
|
||||
MaxEncodedLen,
|
||||
PartialEq,
|
||||
PartialOrd,
|
||||
Ord,
|
||||
TypeInfo,
|
||||
)]
|
||||
pub struct HeaderId<Hash, Number>(pub Number, pub Hash);
|
||||
|
||||
impl<Hash: Copy, Number: Copy> HeaderId<Hash, Number> {
|
||||
/// Return header number.
|
||||
pub fn number(&self) -> Number {
|
||||
self.0
|
||||
}
|
||||
|
||||
/// Return header hash.
|
||||
pub fn hash(&self) -> Hash {
|
||||
self.1
|
||||
}
|
||||
}
|
||||
|
||||
/// Header id used by the chain.
|
||||
pub type HeaderIdOf<C> = HeaderId<HashOf<C>, BlockNumberOf<C>>;
|
||||
|
||||
/// Generic header id provider.
|
||||
pub trait HeaderIdProvider<Header: HeaderT> {
|
||||
// Get the header id.
|
||||
fn id(&self) -> HeaderId<Header::Hash, Header::Number>;
|
||||
|
||||
// Get the header id for the parent block.
|
||||
fn parent_id(&self) -> Option<HeaderId<Header::Hash, Header::Number>>;
|
||||
}
|
||||
|
||||
impl<Header: HeaderT> HeaderIdProvider<Header> for Header {
|
||||
fn id(&self) -> HeaderId<Header::Hash, Header::Number> {
|
||||
HeaderId(*self.number(), self.hash())
|
||||
}
|
||||
|
||||
fn parent_id(&self) -> Option<HeaderId<Header::Hash, Header::Number>> {
|
||||
self.number()
|
||||
.checked_sub(&One::one())
|
||||
.map(|parent_number| HeaderId(parent_number, *self.parent_hash()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Unique identifier of the chain.
|
||||
///
|
||||
/// In addition to its main function (identifying the chain), this type may also be used to
|
||||
/// identify module instance. We have a bunch of pallets that may be used in different bridges. E.g.
|
||||
/// messages pallet may be deployed twice in the same runtime to bridge ThisChain with Chain1 and
|
||||
/// Chain2. Sometimes we need to be able to identify deployed instance dynamically. This type may be
|
||||
/// used for that.
|
||||
pub type ChainId = [u8; 4];
|
||||
|
||||
/// Anything that has size.
|
||||
pub trait Size {
|
||||
/// Return size of this object (in bytes).
|
||||
fn size(&self) -> u32;
|
||||
}
|
||||
|
||||
impl Size for () {
|
||||
fn size(&self) -> u32 {
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
impl Size for Vec<u8> {
|
||||
fn size(&self) -> u32 {
|
||||
self.len() as _
|
||||
}
|
||||
}
|
||||
|
||||
/// Pre-computed size.
|
||||
pub struct PreComputedSize(pub usize);
|
||||
|
||||
impl Size for PreComputedSize {
|
||||
fn size(&self) -> u32 {
|
||||
u32::try_from(self.0).unwrap_or(u32::MAX)
|
||||
}
|
||||
}
|
||||
|
||||
/// Era of specific transaction.
|
||||
#[derive(RuntimeDebug, Clone, Copy, PartialEq)]
|
||||
pub enum TransactionEra<BlockNumber, BlockHash> {
|
||||
/// Transaction is immortal.
|
||||
Immortal,
|
||||
/// Transaction is valid for a given number of blocks, starting from given block.
|
||||
Mortal(HeaderId<BlockHash, BlockNumber>, u32),
|
||||
}
|
||||
|
||||
impl<BlockNumber: Copy + UniqueSaturatedInto<u64>, BlockHash: Copy>
|
||||
TransactionEra<BlockNumber, BlockHash>
|
||||
{
|
||||
/// Prepare transaction era, based on mortality period and current best block number.
|
||||
pub fn new(
|
||||
best_block_id: HeaderId<BlockHash, BlockNumber>,
|
||||
mortality_period: Option<u32>,
|
||||
) -> Self {
|
||||
mortality_period
|
||||
.map(|mortality_period| TransactionEra::Mortal(best_block_id, mortality_period))
|
||||
.unwrap_or(TransactionEra::Immortal)
|
||||
}
|
||||
|
||||
/// Create new immortal transaction era.
|
||||
pub fn immortal() -> Self {
|
||||
TransactionEra::Immortal
|
||||
}
|
||||
|
||||
/// Returns mortality period if transaction is mortal.
|
||||
pub fn mortality_period(&self) -> Option<u32> {
|
||||
match *self {
|
||||
TransactionEra::Immortal => None,
|
||||
TransactionEra::Mortal(_, period) => Some(period),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns era that is used by FRAME-based runtimes.
|
||||
pub fn frame_era(&self) -> sp_runtime::generic::Era {
|
||||
match *self {
|
||||
TransactionEra::Immortal => sp_runtime::generic::Era::immortal(),
|
||||
// `unique_saturated_into` is fine here - mortality `u64::MAX` is not something we
|
||||
// expect to see on any chain
|
||||
TransactionEra::Mortal(header_id, period) =>
|
||||
sp_runtime::generic::Era::mortal(period as _, header_id.0.unique_saturated_into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns header hash that needs to be included in the signature payload.
|
||||
pub fn signed_payload(&self, genesis_hash: BlockHash) -> BlockHash {
|
||||
match *self {
|
||||
TransactionEra::Immortal => genesis_hash,
|
||||
TransactionEra::Mortal(header_id, _) => header_id.1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// This is a copy of the
|
||||
/// `frame_support::storage::generator::StorageMap::storage_map_final_key` for maps based
|
||||
/// on selected hasher.
|
||||
///
|
||||
/// We're using it because to call `storage_map_final_key` directly, we need access to the runtime
|
||||
/// and pallet instance, which (sometimes) is impossible.
|
||||
pub fn storage_map_final_key<H: StorageHasher>(
|
||||
pallet_prefix: &str,
|
||||
map_name: &str,
|
||||
key: &[u8],
|
||||
) -> StorageKey {
|
||||
let key_hashed = H::hash(key);
|
||||
let pallet_prefix_hashed = frame_support::Twox128::hash(pallet_prefix.as_bytes());
|
||||
let storage_prefix_hashed = frame_support::Twox128::hash(map_name.as_bytes());
|
||||
|
||||
let mut final_key = Vec::with_capacity(
|
||||
pallet_prefix_hashed.len() + storage_prefix_hashed.len() + key_hashed.as_ref().len(),
|
||||
);
|
||||
|
||||
final_key.extend_from_slice(&pallet_prefix_hashed[..]);
|
||||
final_key.extend_from_slice(&storage_prefix_hashed[..]);
|
||||
final_key.extend_from_slice(key_hashed.as_ref());
|
||||
|
||||
StorageKey(final_key)
|
||||
}
|
||||
|
||||
/// This is how a storage key of storage parameter (`parameter_types! { storage Param: bool = false;
|
||||
/// }`) is computed.
|
||||
///
|
||||
/// Copied from `frame_support::parameter_types` macro.
|
||||
pub fn storage_parameter_key(parameter_name: &str) -> StorageKey {
|
||||
let mut buffer = Vec::with_capacity(1 + parameter_name.len() + 1);
|
||||
buffer.push(b':');
|
||||
buffer.extend_from_slice(parameter_name.as_bytes());
|
||||
buffer.push(b':');
|
||||
StorageKey(sp_io::hashing::twox_128(&buffer).to_vec())
|
||||
}
|
||||
|
||||
/// This is how a storage key of storage value is computed.
|
||||
///
|
||||
/// Copied from `frame_support::storage::storage_prefix`.
|
||||
pub fn storage_value_key(pallet_prefix: &str, value_name: &str) -> StorageKey {
|
||||
let pallet_hash = sp_io::hashing::twox_128(pallet_prefix.as_bytes());
|
||||
let storage_hash = sp_io::hashing::twox_128(value_name.as_bytes());
|
||||
|
||||
let mut final_key = vec![0u8; 32];
|
||||
final_key[..16].copy_from_slice(&pallet_hash);
|
||||
final_key[16..].copy_from_slice(&storage_hash);
|
||||
|
||||
StorageKey(final_key)
|
||||
}
|
||||
|
||||
/// Can be use to access the runtime storage key of a `StorageMap`.
|
||||
pub trait StorageMapKeyProvider {
|
||||
/// The name of the variable that holds the `StorageMap`.
|
||||
const MAP_NAME: &'static str;
|
||||
|
||||
/// The same as `StorageMap::Hasher1`.
|
||||
type Hasher: StorageHasher;
|
||||
/// The same as `StorageMap::Key1`.
|
||||
type Key: FullCodec;
|
||||
/// The same as `StorageMap::Value`.
|
||||
type Value: FullCodec;
|
||||
|
||||
/// This is a copy of the
|
||||
/// `frame_support::storage::generator::StorageMap::storage_map_final_key`.
|
||||
///
|
||||
/// We're using it because to call `storage_map_final_key` directly, we need access
|
||||
/// to the runtime and pallet instance, which (sometimes) is impossible.
|
||||
fn final_key(pallet_prefix: &str, key: &Self::Key) -> StorageKey {
|
||||
storage_map_final_key::<Self::Hasher>(pallet_prefix, Self::MAP_NAME, &key.encode())
|
||||
}
|
||||
}
|
||||
|
||||
/// Can be use to access the runtime storage key of a `StorageDoubleMap`.
|
||||
pub trait StorageDoubleMapKeyProvider {
|
||||
/// The name of the variable that holds the `StorageDoubleMap`.
|
||||
const MAP_NAME: &'static str;
|
||||
|
||||
/// The same as `StorageDoubleMap::Hasher1`.
|
||||
type Hasher1: StorageHasher;
|
||||
/// The same as `StorageDoubleMap::Key1`.
|
||||
type Key1: FullCodec;
|
||||
/// The same as `StorageDoubleMap::Hasher2`.
|
||||
type Hasher2: StorageHasher;
|
||||
/// The same as `StorageDoubleMap::Key2`.
|
||||
type Key2: FullCodec;
|
||||
/// The same as `StorageDoubleMap::Value`.
|
||||
type Value: FullCodec;
|
||||
|
||||
/// This is a copy of the
|
||||
/// `frame_support::storage::generator::StorageDoubleMap::storage_double_map_final_key`.
|
||||
///
|
||||
/// We're using it because to call `storage_double_map_final_key` directly, we need access
|
||||
/// to the runtime and pallet instance, which (sometimes) is impossible.
|
||||
fn final_key(pallet_prefix: &str, key1: &Self::Key1, key2: &Self::Key2) -> StorageKey {
|
||||
let key1_hashed = Self::Hasher1::hash(&key1.encode());
|
||||
let key2_hashed = Self::Hasher2::hash(&key2.encode());
|
||||
let pallet_prefix_hashed = frame_support::Twox128::hash(pallet_prefix.as_bytes());
|
||||
let storage_prefix_hashed = frame_support::Twox128::hash(Self::MAP_NAME.as_bytes());
|
||||
|
||||
let mut final_key = Vec::with_capacity(
|
||||
pallet_prefix_hashed.len() +
|
||||
storage_prefix_hashed.len() +
|
||||
key1_hashed.as_ref().len() +
|
||||
key2_hashed.as_ref().len(),
|
||||
);
|
||||
|
||||
final_key.extend_from_slice(&pallet_prefix_hashed[..]);
|
||||
final_key.extend_from_slice(&storage_prefix_hashed[..]);
|
||||
final_key.extend_from_slice(key1_hashed.as_ref());
|
||||
final_key.extend_from_slice(key2_hashed.as_ref());
|
||||
|
||||
StorageKey(final_key)
|
||||
}
|
||||
}
|
||||
|
||||
/// Error generated by the `OwnedBridgeModule` trait.
|
||||
#[derive(Encode, Decode, TypeInfo, PalletError)]
|
||||
pub enum OwnedBridgeModuleError {
|
||||
/// All pallet operations are halted.
|
||||
Halted,
|
||||
}
|
||||
|
||||
/// Operating mode for a bridge module.
|
||||
pub trait OperatingMode: Send + Copy + Debug + FullCodec {
|
||||
// Returns true if the bridge module is halted.
|
||||
fn is_halted(&self) -> bool;
|
||||
}
|
||||
|
||||
/// Basic operating modes for a bridges module (Normal/Halted).
|
||||
#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)]
|
||||
#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub enum BasicOperatingMode {
|
||||
/// Normal mode, when all operations are allowed.
|
||||
Normal,
|
||||
/// The pallet is halted. All operations (except operating mode change) are prohibited.
|
||||
Halted,
|
||||
}
|
||||
|
||||
impl Default for BasicOperatingMode {
|
||||
fn default() -> Self {
|
||||
Self::Normal
|
||||
}
|
||||
}
|
||||
|
||||
impl OperatingMode for BasicOperatingMode {
|
||||
fn is_halted(&self) -> bool {
|
||||
*self == BasicOperatingMode::Halted
|
||||
}
|
||||
}
|
||||
|
||||
/// Bridge module that has owner and operating mode
|
||||
pub trait OwnedBridgeModule<T: frame_system::Config> {
|
||||
/// The target that will be used when publishing logs related to this module.
|
||||
const LOG_TARGET: &'static str;
|
||||
|
||||
type OwnerStorage: StorageValue<T::AccountId, Query = Option<T::AccountId>>;
|
||||
type OperatingMode: OperatingMode;
|
||||
type OperatingModeStorage: StorageValue<Self::OperatingMode, Query = Self::OperatingMode>;
|
||||
|
||||
/// Check if the module is halted.
|
||||
fn is_halted() -> bool {
|
||||
Self::OperatingModeStorage::get().is_halted()
|
||||
}
|
||||
|
||||
/// Ensure that the origin is either root, or `PalletOwner`.
|
||||
fn ensure_owner_or_root(origin: T::RuntimeOrigin) -> Result<(), BadOrigin> {
|
||||
match origin.into() {
|
||||
Ok(RawOrigin::Root) => Ok(()),
|
||||
Ok(RawOrigin::Signed(ref signer))
|
||||
if Self::OwnerStorage::get().as_ref() == Some(signer) =>
|
||||
Ok(()),
|
||||
_ => Err(BadOrigin),
|
||||
}
|
||||
}
|
||||
|
||||
/// Ensure that the module is not halted.
|
||||
fn ensure_not_halted() -> Result<(), OwnedBridgeModuleError> {
|
||||
match Self::is_halted() {
|
||||
true => Err(OwnedBridgeModuleError::Halted),
|
||||
false => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Change the owner of the module.
|
||||
fn set_owner(origin: T::RuntimeOrigin, maybe_owner: Option<T::AccountId>) -> DispatchResult {
|
||||
Self::ensure_owner_or_root(origin)?;
|
||||
match maybe_owner {
|
||||
Some(owner) => {
|
||||
Self::OwnerStorage::put(&owner);
|
||||
log::info!(target: Self::LOG_TARGET, "Setting pallet Owner to: {:?}", owner);
|
||||
},
|
||||
None => {
|
||||
Self::OwnerStorage::kill();
|
||||
log::info!(target: Self::LOG_TARGET, "Removed Owner of pallet.");
|
||||
},
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Halt or resume all/some module operations.
|
||||
fn set_operating_mode(
|
||||
origin: T::RuntimeOrigin,
|
||||
operating_mode: Self::OperatingMode,
|
||||
) -> DispatchResult {
|
||||
Self::ensure_owner_or_root(origin)?;
|
||||
Self::OperatingModeStorage::put(operating_mode);
|
||||
log::info!(target: Self::LOG_TARGET, "Setting operating mode to {:?}.", operating_mode);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// All extra operations with weights that we need in bridges.
|
||||
pub trait WeightExtraOps {
|
||||
/// Checked division of individual components of two weights.
|
||||
///
|
||||
/// Divides components and returns minimal division result. Returns `None` if one
|
||||
/// of `other` weight components is zero.
|
||||
fn min_components_checked_div(&self, other: Weight) -> Option<u64>;
|
||||
}
|
||||
|
||||
impl WeightExtraOps for Weight {
|
||||
fn min_components_checked_div(&self, other: Weight) -> Option<u64> {
|
||||
Some(sp_std::cmp::min(
|
||||
self.ref_time().checked_div(other.ref_time())?,
|
||||
self.proof_size().checked_div(other.proof_size())?,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// Trait that provides a static `str`.
|
||||
pub trait StaticStrProvider {
|
||||
const STR: &'static str;
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! generate_static_str_provider {
|
||||
($str:expr) => {
|
||||
$crate::paste::item! {
|
||||
pub struct [<Str $str>];
|
||||
|
||||
impl $crate::StaticStrProvider for [<Str $str>] {
|
||||
const STR: &'static str = stringify!($str);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[derive(Encode, Decode, Clone, Eq, PartialEq, PalletError, TypeInfo)]
|
||||
#[scale_info(skip_type_params(T))]
|
||||
pub struct StrippableError<T> {
|
||||
_phantom_data: sp_std::marker::PhantomData<T>,
|
||||
#[codec(skip)]
|
||||
#[cfg(feature = "std")]
|
||||
message: String,
|
||||
}
|
||||
|
||||
impl<T: Debug> From<T> for StrippableError<T> {
|
||||
fn from(_err: T) -> Self {
|
||||
Self {
|
||||
_phantom_data: Default::default(),
|
||||
#[cfg(feature = "std")]
|
||||
message: format!("{:?}", _err),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Debug for StrippableError<T> {
|
||||
#[cfg(feature = "std")]
|
||||
fn fmt(&self, f: &mut sp_std::fmt::Formatter<'_>) -> sp_std::fmt::Result {
|
||||
f.write_str(&self.message)
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "std"))]
|
||||
fn fmt(&self, f: &mut sp_std::fmt::Formatter<'_>) -> sp_std::fmt::Result {
|
||||
f.write_str("Stripped error")
|
||||
}
|
||||
}
|
||||
|
||||
/// A trait defining helper methods for `RangeInclusive` (start..=end)
|
||||
pub trait RangeInclusiveExt<Idx> {
|
||||
/// Computes the length of the `RangeInclusive`, checking for underflow and overflow.
|
||||
fn checked_len(&self) -> Option<Idx>;
|
||||
}
|
||||
|
||||
impl<Idx> RangeInclusiveExt<Idx> for RangeInclusive<Idx>
|
||||
where
|
||||
Idx: CheckedSub + CheckedAdd + One,
|
||||
{
|
||||
fn checked_len(&self) -> Option<Idx> {
|
||||
self.end()
|
||||
.checked_sub(self.start())
|
||||
.and_then(|len| len.checked_add(&Idx::one()))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn storage_parameter_key_works() {
|
||||
assert_eq!(
|
||||
storage_parameter_key("MillauToRialtoConversionRate"),
|
||||
StorageKey(hex_literal::hex!("58942375551bb0af1682f72786b59d04").to_vec()),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn storage_value_key_works() {
|
||||
assert_eq!(
|
||||
storage_value_key("PalletTransactionPayment", "NextFeeMultiplier"),
|
||||
StorageKey(
|
||||
hex_literal::hex!(
|
||||
"f0e954dfcca51a255ab12c60c789256a3f2edf3bdf381debe331ab7446addfdc"
|
||||
)
|
||||
.to_vec()
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generate_static_str_provider_works() {
|
||||
generate_static_str_provider!(Test);
|
||||
assert_eq!(StrTest::STR, "Test");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Parity Bridges Common is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Primitives that may be used by different message delivery and dispatch mechanisms.
|
||||
|
||||
use codec::{Decode, Encode};
|
||||
use frame_support::{weights::Weight, RuntimeDebug};
|
||||
use scale_info::TypeInfo;
|
||||
|
||||
/// Message dispatch result.
|
||||
#[derive(Encode, Decode, RuntimeDebug, Clone, PartialEq, Eq, TypeInfo)]
|
||||
pub struct MessageDispatchResult<DispatchLevelResult> {
|
||||
/// Unspent dispatch weight. This weight that will be deducted from total delivery transaction
|
||||
/// weight, thus reducing the transaction cost. This shall not be zero in (at least) two cases:
|
||||
///
|
||||
/// 1) if message has been dispatched successfully, but post-dispatch weight is less than
|
||||
/// the weight, declared by the message sender;
|
||||
/// 2) if message has not been dispatched at all.
|
||||
pub unspent_weight: Weight,
|
||||
/// Fine-grained result of single message dispatch (for better diagnostic purposes)
|
||||
pub dispatch_level_result: DispatchLevelResult,
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Parity Bridges Common is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Logic for checking Substrate storage proofs.
|
||||
|
||||
use crate::StrippableError;
|
||||
use codec::{Decode, Encode};
|
||||
use frame_support::PalletError;
|
||||
use hash_db::{HashDB, Hasher, EMPTY_PREFIX};
|
||||
use scale_info::TypeInfo;
|
||||
use sp_std::{boxed::Box, collections::btree_set::BTreeSet, vec::Vec};
|
||||
use sp_trie::{
|
||||
read_trie_value, LayoutV1, MemoryDB, Recorder, StorageProof, Trie, TrieConfiguration,
|
||||
TrieDBBuilder, TrieError, TrieHash,
|
||||
};
|
||||
|
||||
/// Raw storage proof type (just raw trie nodes).
|
||||
pub type RawStorageProof = Vec<Vec<u8>>;
|
||||
|
||||
/// Storage proof size requirements.
|
||||
///
|
||||
/// This is currently used by benchmarks when generating storage proofs.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum ProofSize {
|
||||
/// The proof is expected to be minimal. If value size may be changed, then it is expected to
|
||||
/// have given size.
|
||||
Minimal(u32),
|
||||
/// The proof is expected to have at least given size and grow by increasing value that is
|
||||
/// stored in the trie.
|
||||
HasLargeLeaf(u32),
|
||||
}
|
||||
|
||||
/// This struct is used to read storage values from a subset of a Merklized database. The "proof"
|
||||
/// is a subset of the nodes in the Merkle structure of the database, so that it provides
|
||||
/// authentication against a known Merkle root as well as the values in the
|
||||
/// database themselves.
|
||||
pub struct StorageProofChecker<H>
|
||||
where
|
||||
H: Hasher,
|
||||
{
|
||||
proof_nodes_count: usize,
|
||||
root: H::Out,
|
||||
db: MemoryDB<H>,
|
||||
recorder: Recorder<LayoutV1<H>>,
|
||||
}
|
||||
|
||||
impl<H> StorageProofChecker<H>
|
||||
where
|
||||
H: Hasher,
|
||||
{
|
||||
/// Constructs a new storage proof checker.
|
||||
///
|
||||
/// This returns an error if the given proof is invalid with respect to the given root.
|
||||
pub fn new(root: H::Out, proof: RawStorageProof) -> Result<Self, Error> {
|
||||
// 1. we don't want extra items in the storage proof
|
||||
// 2. `StorageProof` is storing all trie nodes in the `BTreeSet`
|
||||
//
|
||||
// => someone could simply add duplicate items to the proof and we won't be
|
||||
// able to detect that by just using `StorageProof`
|
||||
//
|
||||
// => let's check it when we are converting our "raw proof" into `StorageProof`
|
||||
let proof_nodes_count = proof.len();
|
||||
let proof = StorageProof::new(proof);
|
||||
if proof_nodes_count != proof.iter_nodes().count() {
|
||||
return Err(Error::DuplicateNodesInProof)
|
||||
}
|
||||
|
||||
let db = proof.into_memory_db();
|
||||
if !db.contains(&root, EMPTY_PREFIX) {
|
||||
return Err(Error::StorageRootMismatch)
|
||||
}
|
||||
|
||||
let recorder = Recorder::default();
|
||||
let checker = StorageProofChecker { proof_nodes_count, root, db, recorder };
|
||||
Ok(checker)
|
||||
}
|
||||
|
||||
/// Returns error if the proof has some nodes that are left intact by previous `read_value`
|
||||
/// calls.
|
||||
pub fn ensure_no_unused_nodes(mut self) -> Result<(), Error> {
|
||||
let visited_nodes = self
|
||||
.recorder
|
||||
.drain()
|
||||
.into_iter()
|
||||
.map(|record| record.data)
|
||||
.collect::<BTreeSet<_>>();
|
||||
let visited_nodes_count = visited_nodes.len();
|
||||
if self.proof_nodes_count == visited_nodes_count {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::UnusedNodesInTheProof)
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads a value from the available subset of storage. If the value cannot be read due to an
|
||||
/// incomplete or otherwise invalid proof, this function returns an error.
|
||||
pub fn read_value(&mut self, key: &[u8]) -> Result<Option<Vec<u8>>, Error> {
|
||||
// LayoutV1 or LayoutV0 is identical for proof that only read values.
|
||||
read_trie_value::<LayoutV1<H>, _>(&self.db, &self.root, key, Some(&mut self.recorder), None)
|
||||
.map_err(|_| Error::StorageValueUnavailable)
|
||||
}
|
||||
|
||||
/// Reads and decodes a value from the available subset of storage. If the value cannot be read
|
||||
/// due to an incomplete or otherwise invalid proof, this function returns an error. If value is
|
||||
/// read, but decoding fails, this function returns an error.
|
||||
pub fn read_and_decode_value<T: Decode>(&mut self, key: &[u8]) -> Result<Option<T>, Error> {
|
||||
self.read_value(key).and_then(|v| {
|
||||
v.map(|v| T::decode(&mut &v[..]).map_err(|e| Error::StorageValueDecodeFailed(e.into())))
|
||||
.transpose()
|
||||
})
|
||||
}
|
||||
|
||||
/// Reads and decodes a value from the available subset of storage. If the value cannot be read
|
||||
/// due to an incomplete or otherwise invalid proof, or if the value is `None`, this function
|
||||
/// returns an error. If value is read, but decoding fails, this function returns an error.
|
||||
pub fn read_and_decode_mandatory_value<T: Decode>(&mut self, key: &[u8]) -> Result<T, Error> {
|
||||
self.read_and_decode_value(key)?.ok_or(Error::StorageValueEmpty)
|
||||
}
|
||||
|
||||
/// Reads and decodes a value from the available subset of storage. If the value cannot be read
|
||||
/// due to an incomplete or otherwise invalid proof, this function returns `Ok(None)`.
|
||||
/// If value is read, but decoding fails, this function returns an error.
|
||||
pub fn read_and_decode_opt_value<T: Decode>(&mut self, key: &[u8]) -> Result<Option<T>, Error> {
|
||||
match self.read_and_decode_value(key) {
|
||||
Ok(outbound_lane_data) => Ok(outbound_lane_data),
|
||||
Err(Error::StorageValueUnavailable) => Ok(None),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Storage proof related errors.
|
||||
#[derive(Encode, Decode, Clone, Eq, PartialEq, PalletError, Debug, TypeInfo)]
|
||||
pub enum Error {
|
||||
/// Duplicate trie nodes are found in the proof.
|
||||
DuplicateNodesInProof,
|
||||
/// Unused trie nodes are found in the proof.
|
||||
UnusedNodesInTheProof,
|
||||
/// Expected storage root is missing from the proof.
|
||||
StorageRootMismatch,
|
||||
/// Unable to reach expected storage value using provided trie nodes.
|
||||
StorageValueUnavailable,
|
||||
/// The storage value is `None`.
|
||||
StorageValueEmpty,
|
||||
/// Failed to decode storage value.
|
||||
StorageValueDecodeFailed(StrippableError<codec::Error>),
|
||||
}
|
||||
|
||||
/// Return valid storage proof and state root.
|
||||
///
|
||||
/// NOTE: This should only be used for **testing**.
|
||||
#[cfg(feature = "std")]
|
||||
pub fn craft_valid_storage_proof() -> (sp_core::H256, RawStorageProof) {
|
||||
use sp_state_machine::{backend::Backend, prove_read, InMemoryBackend};
|
||||
|
||||
let state_version = sp_runtime::StateVersion::default();
|
||||
|
||||
// construct storage proof
|
||||
let backend = <InMemoryBackend<sp_core::Blake2Hasher>>::from((
|
||||
vec![
|
||||
(None, vec![(b"key1".to_vec(), Some(b"value1".to_vec()))]),
|
||||
(None, vec![(b"key2".to_vec(), Some(b"value2".to_vec()))]),
|
||||
(None, vec![(b"key3".to_vec(), Some(b"value3".to_vec()))]),
|
||||
(None, vec![(b"key4".to_vec(), Some((42u64, 42u32, 42u16, 42u8).encode()))]),
|
||||
// Value is too big to fit in a branch node
|
||||
(None, vec![(b"key11".to_vec(), Some(vec![0u8; 32]))]),
|
||||
],
|
||||
state_version,
|
||||
));
|
||||
let root = backend.storage_root(std::iter::empty(), state_version).0;
|
||||
let proof =
|
||||
prove_read(backend, &[&b"key1"[..], &b"key2"[..], &b"key4"[..], &b"key22"[..]]).unwrap();
|
||||
|
||||
(root, proof.into_nodes().into_iter().collect())
|
||||
}
|
||||
|
||||
/// Record all keys for a given root.
|
||||
pub fn record_all_keys<L: TrieConfiguration, DB>(
|
||||
db: &DB,
|
||||
root: &TrieHash<L>,
|
||||
) -> Result<RawStorageProof, Box<TrieError<L>>>
|
||||
where
|
||||
DB: hash_db::HashDBRef<L::Hash, trie_db::DBValue>,
|
||||
{
|
||||
let mut recorder = Recorder::<L>::new();
|
||||
let trie = TrieDBBuilder::<L>::new(db, root).with_recorder(&mut recorder).build();
|
||||
for x in trie.iter()? {
|
||||
let (key, _) = x?;
|
||||
trie.get(&key)?;
|
||||
}
|
||||
|
||||
// recorder may record the same trie node multiple times and we don't want duplicate nodes
|
||||
// in our proofs => let's deduplicate it by collecting to the BTreeSet first
|
||||
Ok(recorder
|
||||
.drain()
|
||||
.into_iter()
|
||||
.map(|n| n.data.to_vec())
|
||||
.collect::<BTreeSet<_>>()
|
||||
.into_iter()
|
||||
.collect())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub mod tests {
|
||||
use super::*;
|
||||
use codec::Encode;
|
||||
|
||||
#[test]
|
||||
fn storage_proof_check() {
|
||||
let (root, proof) = craft_valid_storage_proof();
|
||||
|
||||
// check proof in runtime
|
||||
let mut checker =
|
||||
<StorageProofChecker<sp_core::Blake2Hasher>>::new(root, proof.clone()).unwrap();
|
||||
assert_eq!(checker.read_value(b"key1"), Ok(Some(b"value1".to_vec())));
|
||||
assert_eq!(checker.read_value(b"key2"), Ok(Some(b"value2".to_vec())));
|
||||
assert_eq!(checker.read_value(b"key4"), Ok(Some((42u64, 42u32, 42u16, 42u8).encode())));
|
||||
assert_eq!(checker.read_value(b"key11111"), Err(Error::StorageValueUnavailable));
|
||||
assert_eq!(checker.read_value(b"key22"), Ok(None));
|
||||
assert_eq!(checker.read_and_decode_value(b"key4"), Ok(Some((42u64, 42u32, 42u16, 42u8))),);
|
||||
assert!(matches!(
|
||||
checker.read_and_decode_value::<[u8; 64]>(b"key4"),
|
||||
Err(Error::StorageValueDecodeFailed(_)),
|
||||
));
|
||||
|
||||
// checking proof against invalid commitment fails
|
||||
assert_eq!(
|
||||
<StorageProofChecker<sp_core::Blake2Hasher>>::new(sp_core::H256::random(), proof).err(),
|
||||
Some(Error::StorageRootMismatch)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn proof_with_duplicate_items_is_rejected() {
|
||||
let (root, mut proof) = craft_valid_storage_proof();
|
||||
proof.push(proof.first().unwrap().clone());
|
||||
|
||||
assert_eq!(
|
||||
StorageProofChecker::<sp_core::Blake2Hasher>::new(root, proof).map(drop),
|
||||
Err(Error::DuplicateNodesInProof),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn proof_with_unused_items_is_rejected() {
|
||||
let (root, proof) = craft_valid_storage_proof();
|
||||
|
||||
let mut checker =
|
||||
StorageProofChecker::<sp_core::Blake2Hasher>::new(root, proof.clone()).unwrap();
|
||||
checker.read_value(b"key1").unwrap();
|
||||
checker.read_value(b"key2").unwrap();
|
||||
checker.read_value(b"key4").unwrap();
|
||||
checker.read_value(b"key22").unwrap();
|
||||
assert_eq!(checker.ensure_no_unused_nodes(), Ok(()));
|
||||
|
||||
let checker = StorageProofChecker::<sp_core::Blake2Hasher>::new(root, proof).unwrap();
|
||||
assert_eq!(checker.ensure_no_unused_nodes(), Err(Error::UnusedNodesInTheProof));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
// Copyright 2022 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Parity Bridges Common is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Wrapper for a runtime storage value that checks if value exceeds given maximum
|
||||
//! during conversion.
|
||||
|
||||
use codec::{Decode, Encode, MaxEncodedLen};
|
||||
use frame_support::{traits::Get, RuntimeDebug};
|
||||
use scale_info::{Type, TypeInfo};
|
||||
use sp_std::{marker::PhantomData, ops::Deref};
|
||||
|
||||
/// Error that is returned when the value size exceeds maximal configured size.
|
||||
#[derive(RuntimeDebug)]
|
||||
pub struct MaximalSizeExceededError {
|
||||
/// Size of the value.
|
||||
pub value_size: usize,
|
||||
/// Maximal configured size.
|
||||
pub maximal_size: usize,
|
||||
}
|
||||
|
||||
/// A bounded runtime storage value.
|
||||
#[derive(Clone, Decode, Encode, Eq, PartialEq)]
|
||||
pub struct BoundedStorageValue<B, V> {
|
||||
value: V,
|
||||
_phantom: PhantomData<B>,
|
||||
}
|
||||
|
||||
impl<B, V: sp_std::fmt::Debug> sp_std::fmt::Debug for BoundedStorageValue<B, V> {
|
||||
fn fmt(&self, fmt: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
|
||||
self.value.fmt(fmt)
|
||||
}
|
||||
}
|
||||
|
||||
impl<B: Get<u32>, V: Encode> BoundedStorageValue<B, V> {
|
||||
/// Construct `BoundedStorageValue` from the underlying `value` with all required checks.
|
||||
///
|
||||
/// Returns error if value size exceeds given bounds.
|
||||
pub fn try_from_inner(value: V) -> Result<Self, MaximalSizeExceededError> {
|
||||
// this conversion is heavy (since we do encoding here), so we may want to optimize it later
|
||||
// (e.g. by introducing custom Encode implementation, and turning `BoundedStorageValue` into
|
||||
// `enum BoundedStorageValue { Decoded(V), Encoded(Vec<u8>) }`)
|
||||
let value_size = value.encoded_size();
|
||||
let maximal_size = B::get() as usize;
|
||||
if value_size > maximal_size {
|
||||
Err(MaximalSizeExceededError { value_size, maximal_size })
|
||||
} else {
|
||||
Ok(BoundedStorageValue { value, _phantom: Default::default() })
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert into the inner type
|
||||
pub fn into_inner(self) -> V {
|
||||
self.value
|
||||
}
|
||||
}
|
||||
|
||||
impl<B, V> Deref for BoundedStorageValue<B, V> {
|
||||
type Target = V;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.value
|
||||
}
|
||||
}
|
||||
|
||||
impl<B: 'static, V: TypeInfo + 'static> TypeInfo for BoundedStorageValue<B, V> {
|
||||
type Identity = Self;
|
||||
|
||||
fn type_info() -> Type {
|
||||
V::type_info()
|
||||
}
|
||||
}
|
||||
|
||||
impl<B: Get<u32>, V: Encode> MaxEncodedLen for BoundedStorageValue<B, V> {
|
||||
fn max_encoded_len() -> usize {
|
||||
B::get() as usize
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
[package]
|
||||
name = "bp-test-utils"
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2021"
|
||||
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
|
||||
|
||||
[dependencies]
|
||||
bp-header-chain = { path = "../header-chain", default-features = false }
|
||||
codec = { package = "parity-scale-codec", version = "3.1.5", default-features = false }
|
||||
ed25519-dalek = { version = "1.0", default-features = false, features = ["u64_backend"] }
|
||||
finality-grandpa = { version = "0.16.2", default-features = false }
|
||||
sp-application-crypto = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-consensus-grandpa = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-std = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"bp-header-chain/std",
|
||||
"codec/std",
|
||||
"ed25519-dalek/std",
|
||||
"finality-grandpa/std",
|
||||
"sp-application-crypto/std",
|
||||
"sp-consensus-grandpa/std",
|
||||
"sp-runtime/std",
|
||||
"sp-std/std",
|
||||
]
|
||||
@@ -0,0 +1,94 @@
|
||||
// Copyright 2021 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Parity Bridges Common is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Utilities for working with test accounts.
|
||||
|
||||
use codec::Encode;
|
||||
use ed25519_dalek::{Keypair, PublicKey, SecretKey, Signature};
|
||||
use finality_grandpa::voter_set::VoterSet;
|
||||
use sp_consensus_grandpa::{AuthorityId, AuthorityList, AuthorityWeight};
|
||||
use sp_runtime::RuntimeDebug;
|
||||
use sp_std::prelude::*;
|
||||
|
||||
/// Set of test accounts with friendly names.
|
||||
pub const ALICE: Account = Account(0);
|
||||
pub const BOB: Account = Account(1);
|
||||
pub const CHARLIE: Account = Account(2);
|
||||
pub const DAVE: Account = Account(3);
|
||||
pub const EVE: Account = Account(4);
|
||||
pub const FERDIE: Account = Account(5);
|
||||
|
||||
/// A test account which can be used to sign messages.
|
||||
#[derive(RuntimeDebug, Clone, Copy)]
|
||||
pub struct Account(pub u16);
|
||||
|
||||
impl Account {
|
||||
pub fn public(&self) -> PublicKey {
|
||||
(&self.secret()).into()
|
||||
}
|
||||
|
||||
pub fn secret(&self) -> SecretKey {
|
||||
let data = self.0.encode();
|
||||
let mut bytes = [0_u8; 32];
|
||||
bytes[0..data.len()].copy_from_slice(&data);
|
||||
SecretKey::from_bytes(&bytes)
|
||||
.expect("A static array of the correct length is a known good.")
|
||||
}
|
||||
|
||||
pub fn pair(&self) -> Keypair {
|
||||
let mut pair: [u8; 64] = [0; 64];
|
||||
|
||||
let secret = self.secret();
|
||||
pair[..32].copy_from_slice(&secret.to_bytes());
|
||||
|
||||
let public = self.public();
|
||||
pair[32..].copy_from_slice(&public.to_bytes());
|
||||
|
||||
Keypair::from_bytes(&pair)
|
||||
.expect("We expect the SecretKey to be good, so this must also be good.")
|
||||
}
|
||||
|
||||
pub fn sign(&self, msg: &[u8]) -> Signature {
|
||||
use ed25519_dalek::Signer;
|
||||
self.pair().sign(msg)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Account> for AuthorityId {
|
||||
fn from(p: Account) -> Self {
|
||||
sp_application_crypto::UncheckedFrom::unchecked_from(p.public().to_bytes())
|
||||
}
|
||||
}
|
||||
|
||||
/// Get a valid set of voters for a Grandpa round.
|
||||
pub fn voter_set() -> VoterSet<AuthorityId> {
|
||||
VoterSet::new(authority_list()).unwrap()
|
||||
}
|
||||
|
||||
/// Convenience function to get a list of Grandpa authorities.
|
||||
pub fn authority_list() -> AuthorityList {
|
||||
test_keyring().iter().map(|(id, w)| (AuthorityId::from(*id), *w)).collect()
|
||||
}
|
||||
|
||||
/// Get the corresponding identities from the keyring for the "standard" authority set.
|
||||
pub fn test_keyring() -> Vec<(Account, AuthorityWeight)> {
|
||||
vec![(ALICE, 1), (BOB, 1), (CHARLIE, 1)]
|
||||
}
|
||||
|
||||
/// Get a list of "unique" accounts.
|
||||
pub fn accounts(len: u16) -> Vec<Account> {
|
||||
(0..len).map(Account).collect()
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
// Copyright 2021 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Parity Bridges Common is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Utilities for testing runtime code.
|
||||
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
use bp_header_chain::justification::{required_justification_precommits, GrandpaJustification};
|
||||
use codec::Encode;
|
||||
use sp_consensus_grandpa::{AuthorityId, AuthoritySignature, AuthorityWeight, SetId};
|
||||
use sp_runtime::traits::{Header as HeaderT, One, Zero};
|
||||
use sp_std::prelude::*;
|
||||
|
||||
// Re-export all our test account utilities
|
||||
pub use keyring::*;
|
||||
|
||||
mod keyring;
|
||||
|
||||
pub const TEST_GRANDPA_ROUND: u64 = 1;
|
||||
pub const TEST_GRANDPA_SET_ID: SetId = 1;
|
||||
|
||||
/// Configuration parameters when generating test GRANDPA justifications.
|
||||
#[derive(Clone)]
|
||||
pub struct JustificationGeneratorParams<H> {
|
||||
/// The header which we want to finalize.
|
||||
pub header: H,
|
||||
/// The GRANDPA round number for the current authority set.
|
||||
pub round: u64,
|
||||
/// The current authority set ID.
|
||||
pub set_id: SetId,
|
||||
/// The current GRANDPA authority set.
|
||||
///
|
||||
/// The size of the set will determine the number of pre-commits in our justification.
|
||||
pub authorities: Vec<(Account, AuthorityWeight)>,
|
||||
/// The total number of precommit ancestors in the `votes_ancestries` field our justification.
|
||||
///
|
||||
/// These may be distributed among many forks.
|
||||
pub ancestors: u32,
|
||||
/// The number of forks.
|
||||
///
|
||||
/// Useful for creating a "worst-case" scenario in which each authority is on its own fork.
|
||||
pub forks: u32,
|
||||
}
|
||||
|
||||
impl<H: HeaderT> Default for JustificationGeneratorParams<H> {
|
||||
fn default() -> Self {
|
||||
let required_signatures = required_justification_precommits(test_keyring().len() as _);
|
||||
Self {
|
||||
header: test_header(One::one()),
|
||||
round: TEST_GRANDPA_ROUND,
|
||||
set_id: TEST_GRANDPA_SET_ID,
|
||||
authorities: test_keyring().into_iter().take(required_signatures as _).collect(),
|
||||
ancestors: 2,
|
||||
forks: 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Make a valid GRANDPA justification with sensible defaults
|
||||
pub fn make_default_justification<H: HeaderT>(header: &H) -> GrandpaJustification<H> {
|
||||
let params = JustificationGeneratorParams::<H> { header: header.clone(), ..Default::default() };
|
||||
|
||||
make_justification_for_header(params)
|
||||
}
|
||||
|
||||
/// Generate justifications in a way where we are able to tune the number of pre-commits
|
||||
/// and vote ancestries which are included in the justification.
|
||||
///
|
||||
/// This is useful for benchmarkings where we want to generate valid justifications with
|
||||
/// a specific number of pre-commits (tuned with the number of "authorities") and/or a specific
|
||||
/// number of vote ancestries (tuned with the "votes" parameter).
|
||||
///
|
||||
/// Note: This needs at least three authorities or else the verifier will complain about
|
||||
/// being given an invalid commit.
|
||||
pub fn make_justification_for_header<H: HeaderT>(
|
||||
params: JustificationGeneratorParams<H>,
|
||||
) -> GrandpaJustification<H> {
|
||||
let JustificationGeneratorParams { header, round, set_id, authorities, mut ancestors, forks } =
|
||||
params;
|
||||
let (target_hash, target_number) = (header.hash(), *header.number());
|
||||
let mut votes_ancestries = vec![];
|
||||
let mut precommits = vec![];
|
||||
|
||||
assert!(forks != 0, "Need at least one fork to have a chain..");
|
||||
assert!(
|
||||
forks as usize <= authorities.len(),
|
||||
"If we have more forks than authorities we can't create valid pre-commits for all the forks."
|
||||
);
|
||||
|
||||
// Roughly, how many vote ancestries do we want per fork
|
||||
let target_depth = (ancestors + forks - 1) / forks;
|
||||
|
||||
let mut unsigned_precommits = vec![];
|
||||
for i in 0..forks {
|
||||
let depth = if ancestors >= target_depth {
|
||||
ancestors -= target_depth;
|
||||
target_depth
|
||||
} else {
|
||||
ancestors
|
||||
};
|
||||
|
||||
// Note: Adding 1 to account for the target header
|
||||
let chain = generate_chain(i, depth + 1, &header);
|
||||
|
||||
// We don't include our finality target header in the vote ancestries
|
||||
for child in &chain[1..] {
|
||||
votes_ancestries.push(child.clone());
|
||||
}
|
||||
|
||||
// The header we need to use when pre-commiting is the one at the highest height
|
||||
// on our chain.
|
||||
let precommit_candidate = chain.last().map(|h| (h.hash(), *h.number())).unwrap();
|
||||
unsigned_precommits.push(precommit_candidate);
|
||||
}
|
||||
|
||||
for (i, (id, _weight)) in authorities.iter().enumerate() {
|
||||
// Assign authorities to sign pre-commits in a round-robin fashion
|
||||
let target = unsigned_precommits[i % forks as usize];
|
||||
let precommit = signed_precommit::<H>(id, target, round, set_id);
|
||||
|
||||
precommits.push(precommit);
|
||||
}
|
||||
|
||||
GrandpaJustification {
|
||||
round,
|
||||
commit: finality_grandpa::Commit { target_hash, target_number, precommits },
|
||||
votes_ancestries,
|
||||
}
|
||||
}
|
||||
|
||||
fn generate_chain<H: HeaderT>(fork_id: u32, depth: u32, ancestor: &H) -> Vec<H> {
|
||||
let mut headers = vec![ancestor.clone()];
|
||||
|
||||
for i in 1..depth {
|
||||
let parent = &headers[(i - 1) as usize];
|
||||
let (hash, num) = (parent.hash(), *parent.number());
|
||||
|
||||
let mut header = test_header::<H>(num + One::one());
|
||||
header.set_parent_hash(hash);
|
||||
|
||||
// Modifying the digest so headers at the same height but in different forks have different
|
||||
// hashes
|
||||
header.digest_mut().logs.push(sp_runtime::DigestItem::Other(fork_id.encode()));
|
||||
|
||||
headers.push(header);
|
||||
}
|
||||
|
||||
headers
|
||||
}
|
||||
|
||||
/// Create signed precommit with given target.
|
||||
pub fn signed_precommit<H: HeaderT>(
|
||||
signer: &Account,
|
||||
target: (H::Hash, H::Number),
|
||||
round: u64,
|
||||
set_id: SetId,
|
||||
) -> finality_grandpa::SignedPrecommit<H::Hash, H::Number, AuthoritySignature, AuthorityId> {
|
||||
let precommit = finality_grandpa::Precommit { target_hash: target.0, target_number: target.1 };
|
||||
|
||||
let encoded = sp_consensus_grandpa::localized_payload(
|
||||
round,
|
||||
set_id,
|
||||
&finality_grandpa::Message::Precommit(precommit.clone()),
|
||||
);
|
||||
|
||||
let signature = signer.sign(&encoded);
|
||||
let raw_signature: Vec<u8> = signature.to_bytes().into();
|
||||
|
||||
// Need to wrap our signature and id types that they match what our `SignedPrecommit` is
|
||||
// expecting
|
||||
let signature = AuthoritySignature::try_from(raw_signature).expect(
|
||||
"We know our Keypair is good,
|
||||
so our signature must also be good.",
|
||||
);
|
||||
let id = (*signer).into();
|
||||
|
||||
finality_grandpa::SignedPrecommit { precommit, signature, id }
|
||||
}
|
||||
|
||||
/// Get a header for testing.
|
||||
///
|
||||
/// The correct parent hash will be used if given a non-zero header.
|
||||
pub fn test_header<H: HeaderT>(number: H::Number) -> H {
|
||||
let default = |num| {
|
||||
H::new(num, Default::default(), Default::default(), Default::default(), Default::default())
|
||||
};
|
||||
|
||||
let mut header = default(number);
|
||||
if number != Zero::zero() {
|
||||
let parent_hash = default(number - One::one()).hash();
|
||||
header.set_parent_hash(parent_hash);
|
||||
}
|
||||
|
||||
header
|
||||
}
|
||||
|
||||
/// Convenience function for generating a Header ID at a given block number.
|
||||
pub fn header_id<H: HeaderT>(index: u8) -> (H::Hash, H::Number) {
|
||||
(test_header::<H>(index.into()).hash(), index.into())
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
/// Adds methods for testing the `set_owner()` and `set_operating_mode()` for a pallet.
|
||||
/// Some values are hardcoded like:
|
||||
/// - `run_test()`
|
||||
/// - `Pallet::<TestRuntime>`
|
||||
/// - `PalletOwner::<TestRuntime>`
|
||||
/// - `PalletOperatingMode::<TestRuntime>`
|
||||
/// While this is not ideal, all the pallets use the same names, so it works for the moment.
|
||||
/// We can revisit this in the future if anything changes.
|
||||
macro_rules! generate_owned_bridge_module_tests {
|
||||
($normal_operating_mode: expr, $halted_operating_mode: expr) => {
|
||||
#[test]
|
||||
fn test_set_owner() {
|
||||
run_test(|| {
|
||||
PalletOwner::<TestRuntime>::put(1);
|
||||
|
||||
// The root should be able to change the owner.
|
||||
assert_ok!(Pallet::<TestRuntime>::set_owner(RuntimeOrigin::root(), Some(2)));
|
||||
assert_eq!(PalletOwner::<TestRuntime>::get(), Some(2));
|
||||
|
||||
// The owner should be able to change the owner.
|
||||
assert_ok!(Pallet::<TestRuntime>::set_owner(RuntimeOrigin::signed(2), Some(3)));
|
||||
assert_eq!(PalletOwner::<TestRuntime>::get(), Some(3));
|
||||
|
||||
// Other users shouldn't be able to change the owner.
|
||||
assert_noop!(
|
||||
Pallet::<TestRuntime>::set_owner(RuntimeOrigin::signed(1), Some(4)),
|
||||
DispatchError::BadOrigin
|
||||
);
|
||||
assert_eq!(PalletOwner::<TestRuntime>::get(), Some(3));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_set_operating_mode() {
|
||||
run_test(|| {
|
||||
PalletOwner::<TestRuntime>::put(1);
|
||||
PalletOperatingMode::<TestRuntime>::put($normal_operating_mode);
|
||||
|
||||
// The root should be able to halt the pallet.
|
||||
assert_ok!(Pallet::<TestRuntime>::set_operating_mode(
|
||||
RuntimeOrigin::root(),
|
||||
$halted_operating_mode
|
||||
));
|
||||
assert_eq!(PalletOperatingMode::<TestRuntime>::get(), $halted_operating_mode);
|
||||
// The root should be able to resume the pallet.
|
||||
assert_ok!(Pallet::<TestRuntime>::set_operating_mode(
|
||||
RuntimeOrigin::root(),
|
||||
$normal_operating_mode
|
||||
));
|
||||
assert_eq!(PalletOperatingMode::<TestRuntime>::get(), $normal_operating_mode);
|
||||
|
||||
// The owner should be able to halt the pallet.
|
||||
assert_ok!(Pallet::<TestRuntime>::set_operating_mode(
|
||||
RuntimeOrigin::signed(1),
|
||||
$halted_operating_mode
|
||||
));
|
||||
assert_eq!(PalletOperatingMode::<TestRuntime>::get(), $halted_operating_mode);
|
||||
// The owner should be able to resume the pallet.
|
||||
assert_ok!(Pallet::<TestRuntime>::set_operating_mode(
|
||||
RuntimeOrigin::signed(1),
|
||||
$normal_operating_mode
|
||||
));
|
||||
assert_eq!(PalletOperatingMode::<TestRuntime>::get(), $normal_operating_mode);
|
||||
|
||||
// Other users shouldn't be able to halt the pallet.
|
||||
assert_noop!(
|
||||
Pallet::<TestRuntime>::set_operating_mode(
|
||||
RuntimeOrigin::signed(2),
|
||||
$halted_operating_mode
|
||||
),
|
||||
DispatchError::BadOrigin
|
||||
);
|
||||
assert_eq!(PalletOperatingMode::<TestRuntime>::get(), $normal_operating_mode);
|
||||
// Other users shouldn't be able to resume the pallet.
|
||||
PalletOperatingMode::<TestRuntime>::put($halted_operating_mode);
|
||||
assert_noop!(
|
||||
Pallet::<TestRuntime>::set_operating_mode(
|
||||
RuntimeOrigin::signed(2),
|
||||
$normal_operating_mode
|
||||
),
|
||||
DispatchError::BadOrigin
|
||||
);
|
||||
assert_eq!(PalletOperatingMode::<TestRuntime>::get(), $halted_operating_mode);
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user