Drop Rialto <> Millau bridges (#2663) (#2694)

* drop Rialto <> Millau bridges

* clippy
This commit is contained in:
Svyatoslav Nikolsky
2023-11-14 11:50:26 +03:00
committed by Bastian Köcher
parent 1c2b6b21da
commit 7a8c87a450
114 changed files with 363 additions and 17323 deletions
+17 -158
View File
@@ -68,7 +68,7 @@ For example, consider the case below where we want to bridge two Substrate based
```
+---------------+ +---------------+
| | | |
| Rialto | | Millau |
| Rococo | | Westend |
| | | |
+-------+-------+ +-------+-------+
^ ^
@@ -79,9 +79,9 @@ For example, consider the case below where we want to bridge two Substrate based
+---------------+
```
The Millau chain must be able to accept Rialto headers and verify their integrity. It does this by using a runtime
The Rococo chain must be able to accept Westend headers and verify their integrity. It does this by using a runtime
module designed to track GRANDPA finality. Since two blockchains can't interact directly they need an external service,
called a relayer, to communicate. The relayer will subscribe to new Rialto headers via RPC and submit them to the Millau
called a relayer, to communicate. The relayer will subscribe to new Rococo headers via RPC and submit them to the Westend
chain for verification.
Take a look at [Bridge High Level Documentation](./docs/high-level-overview.md) for more in-depth description of the
@@ -94,164 +94,23 @@ Here's an overview of how the project is laid out. The main bits are the `bin`,
messages between chains.
```
├── bin // Node and Runtime for the various Substrate chains
── ...
├── deployments // Useful tools for deploying test networks
├── modules // Substrate Runtime Modules (a.k.a Pallets)
── beefy // On-Chain BEEFY Light Client (in progress)
├── grandpa // On-Chain GRANDPA Light Client
│ ├── messages // Cross Chain Message Passing
│ ├── parachains // On-Chain Parachains Light Client
│ ├── relayers // Relayer Rewards Registry
│ ├── xcm-bridge-hub // Multiple Dynamic Bridges Support
│ ├── xcm-bridge-hub-router // XCM Router that may be used to Connect to XCM Bridge Hub
├── primitives // Code shared between modules, runtimes, and relays
│ └── ...
├── modules // Substrate Runtime Modules (a.k.a Pallets)
│ ├── beefy // On-Chain BEEFY Light Client (in progress)
│ ├── grandpa // On-Chain GRANDPA Light Client
│ ├── messages // Cross Chain Message Passing
│ ├── parachains // On-Chain Parachains Light Client
│ ├── relayers // Relayer rewards registry
├── relays // Application for sending finality proofs and messages between chains
│ └── ...
── primitives // Code shared between modules, runtimes, and relays
│ └── ...
├── relays // Application for sending finality proofs and messages between chains
│ └── ...
└── scripts // Useful development and maintenance scripts
── scripts // Useful development and maintenance scripts
```
## Running the Bridge
To run the Bridge you need to be able to connect the bridge relay node to the RPC interface of nodes on each side of the
bridge (source and target chain).
There are 2 ways to run the bridge, described below:
- building & running from source: with this option, you'll be able to run the bridge between two standalone chains that
are running GRANDPA finality gadget to achieve finality;
- running a Docker Compose setup: this is a recommended option, where you'll see bridges with parachains, complex relays
and more.
### Using the Source
First you'll need to build the bridge nodes and relay. This can be done as follows:
```bash
# In `parity-bridges-common` folder
cargo build -p rialto-bridge-node
cargo build -p millau-bridge-node
cargo build -p substrate-relay
```
### Running a Dev network
We will launch a dev network to demonstrate how to relay a message between two Substrate based chains (named Rialto and
Millau).
To do this we will need two nodes, two relayers which will relay headers, and two relayers which will relay messages.
#### Running from local scripts
To run a simple dev network you can use the scripts located in the [`deployments/local-scripts`
folder](./deployments/local-scripts).
First, we must run the two Substrate nodes.
```bash
# In `parity-bridges-common` folder
./deployments/local-scripts/run-rialto-node.sh
./deployments/local-scripts/run-millau-node.sh
```
After the nodes are up we can run the header relayers.
```bash
./deployments/local-scripts/relay-millau-to-rialto.sh
./deployments/local-scripts/relay-rialto-to-millau.sh
```
At this point you should see the relayer submitting headers from the Millau Substrate chain to the Rialto Substrate
chain.
```
# Header Relayer Logs
[Millau_to_Rialto_Sync] [date] DEBUG bridge Going to submit finality proof of Millau header #147 to Rialto
[...] [date] INFO bridge Synced 147 of 147 headers
[...] [date] DEBUG bridge Going to submit finality proof of Millau header #148 to Rialto
[...] [date] INFO bridge Synced 148 of 149 headers
```
Finally, we can run the message relayers.
```bash
./deployments/local-scripts/relay-messages-millau-to-rialto.sh
./deployments/local-scripts/relay-messages-rialto-to-millau.sh
```
You will also see the message lane relayers listening for new messages.
```
# Message Relayer Logs
[Millau_to_Rialto_MessageLane_00000000] [date] DEBUG bridge Asking Millau::ReceivingConfirmationsDelivery about best message nonces
[...] [date] INFO bridge Synced Some(2) of Some(3) nonces in Millau::MessagesDelivery -> Rialto::MessagesDelivery race
[...] [date] DEBUG bridge Asking Millau::MessagesDelivery about message nonces
[...] [date] DEBUG bridge Received best nonces from Millau::ReceivingConfirmationsDelivery: TargetClientNonces {
latest_nonce: 0, nonces_data: () }
[...] [date] DEBUG bridge Asking Millau::ReceivingConfirmationsDelivery about finalized message nonces
[...] [date] DEBUG bridge Received finalized nonces from Millau::ReceivingConfirmationsDelivery: TargetClientNonces {
latest_nonce: 0, nonces_data: () }
[...] [date] DEBUG bridge Received nonces from Millau::MessagesDelivery: SourceClientNonces { new_nonces: {}, confirmed_nonce: Some(0) }
[...] [date] DEBUG bridge Asking Millau node about its state
[...] [date] DEBUG bridge Received state from Millau node: ClientState { best_self: HeaderId(1593, 0xacac***), best_finalized_self:
HeaderId(1590, 0x0be81d...), best_finalized_peer_at_best_self: HeaderId(0, 0xdcdd89...) }
```
To send a message see the ["How to send a message" section](#how-to-send-a-message).
### How to send a message
In this section we'll show you how to quickly send a bridge message. The message is just an encoded XCM `Trap(43)`
message.
```bash
# In `parity-bridges-common` folder
./scripts/send-message-from-millau-rialto.sh
```
After sending a message you will see the following logs showing a message was successfully sent:
```
INFO bridge Sending message to Rialto. Size: 11.
TRACE bridge Sent transaction to Millau node: 0x5e68...
```
And at the Rialto node logs you'll something like this:
```
... runtime::bridge-messages: Received messages: total=1, valid=1. Weight used: Weight(ref_time: 1215065371, proof_size:
48559)/Weight(ref_time: 1215065371, proof_size: 54703).
```
It means that the message has been delivered and dispatched. Message may be dispatched with an error, though - the goal
of our test bridge is to ensure that messages are successfully delivered and all involved components are working.
## Full Network Docker Compose Setup
For a more sophisticated deployment which includes bidirectional header sync, message passing, monitoring dashboards,
etc. see the [Deployments README](./deployments/README.md).
You should note that you can find images for all the bridge components published on [Docker
Hub](https://hub.docker.com/u/paritytech).
To run a Rialto node for example, you can use the following command:
```bash
docker run -p 30333:30333 -p 9933:9933 -p 9944:9944 \
-it paritytech/rialto-bridge-node --dev --tmp \
--rpc-cors=all --unsafe-rpc-external
```
## Community
Main hangout for the community is [Element](https://element.io/) (formerly Riot). Element is a chat server like, for
example, Discord. Most discussions around Polkadot and Substrate happen in various Element "rooms" (channels). So,
joining Element might be a good idea, anyway.
If you are interested in information exchange and development of Polkadot related bridges please feel free to join the
[Polkadot Bridges](https://app.element.io/#/room/#bridges:web3.foundation) Element channel.
The [Substrate Technical](https://app.element.io/#/room/#substrate-technical:matrix.org) Element channel is most suited
for discussions regarding Substrate itself.
Apart from live Rococo <> Westend bridge, you may spin up local networks and test see how it works locally. More
details may be found in
[this document](https://github.com/paritytech/polkadot-sdk/tree/master//cumulus/parachains/runtimes/bridge-hubs/README.md).
-61
View File
@@ -1,61 +0,0 @@
[package]
name = "millau-bridge-node"
description = "Substrate node compatible with Millau runtime"
version = "0.1.0"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2021"
build = "build.rs"
repository = "https://github.com/paritytech/parity-bridges-common/"
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
[dependencies]
clap = { version = "4.4.8", features = ["derive"] }
futures = "0.3.29"
jsonrpsee = { version = "0.16.2", features = ["server"] }
serde_json = "1.0.108"
# Bridge dependencies
millau-runtime = { path = "../runtime" }
# Substrate Dependencies
sc-consensus-beefy = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sc-consensus-beefy-rpc = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sp-consensus-beefy = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
frame-benchmarking = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
frame-benchmarking-cli = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
node-inspect = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
mmr-rpc = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
pallet-transaction-payment-rpc = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sc-basic-authorship = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sc-cli = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master"}
sc-client-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sc-consensus = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sc-consensus-aura = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sc-executor = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sc-consensus-grandpa = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sc-consensus-grandpa-rpc = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sc-keystore = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sc-network = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sc-offchain = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sc-rpc = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sc-service = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sc-telemetry = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sc-transaction-pool = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sc-transaction-pool-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sp-consensus-aura = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sp-core = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sp-consensus-grandpa = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sp-timestamp = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
substrate-frame-rpc-system = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sc-network-common = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
[build-dependencies]
substrate-build-script-utils = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
frame-benchmarking-cli = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
[features]
default = []
runtime-benchmarks = [ "millau-runtime/runtime-benchmarks" ]
-23
View File
@@ -1,23 +0,0 @@
// 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 substrate_build_script_utils::{generate_cargo_keys, rerun_if_git_head_changed};
fn main() {
generate_cargo_keys();
rerun_if_git_head_changed();
}
-237
View File
@@ -1,237 +0,0 @@
// 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 millau_runtime::{
AccountId, AuraConfig, BalancesConfig, BeefyConfig, BridgeRialtoMessagesConfig,
BridgeRialtoParachainMessagesConfig, BridgeWestendGrandpaConfig, GrandpaConfig,
RuntimeGenesisConfig, SessionConfig, SessionKeys, Signature, SudoConfig, SystemConfig,
WASM_BINARY,
};
use sp_consensus_aura::sr25519::AuthorityId as AuraId;
use sp_consensus_beefy::ecdsa_crypto::AuthorityId as BeefyId;
use sp_consensus_grandpa::AuthorityId as GrandpaId;
use sp_core::{sr25519, Pair, Public};
use sp_runtime::traits::{IdentifyAccount, Verify};
/// "Names" of the authorities accounts at local testnet.
const LOCAL_AUTHORITIES_ACCOUNTS: [&str; 5] = ["Alice", "Bob", "Charlie", "Dave", "Eve"];
/// "Names" of the authorities accounts at development testnet.
const DEV_AUTHORITIES_ACCOUNTS: [&str; 1] = [LOCAL_AUTHORITIES_ACCOUNTS[0]];
/// "Names" of all possible authorities accounts.
const ALL_AUTHORITIES_ACCOUNTS: [&str; 5] = LOCAL_AUTHORITIES_ACCOUNTS;
/// "Name" of the `sudo` account.
const SUDO_ACCOUNT: &str = "Sudo";
/// "Name" of the account, which owns the with-Westend GRANDPA pallet.
const WESTEND_GRANDPA_PALLET_OWNER: &str = "Westend.GrandpaOwner";
/// "Name" of the account, which owns the with-Rialto messages pallet.
const RIALTO_MESSAGES_PALLET_OWNER: &str = "Rialto.MessagesOwner";
/// "Name" of the account, which owns the with-RialtoParachain messages pallet.
const RIALTO_PARACHAIN_MESSAGES_PALLET_OWNER: &str = "RialtoParachain.MessagesOwner";
/// Specialized `ChainSpec`. This is a specialization of the general Substrate ChainSpec type.
pub type ChainSpec = sc_service::GenericChainSpec<RuntimeGenesisConfig>;
/// The chain specification option. This is expected to come in from the CLI and
/// is little more than one of a number of alternatives which can easily be converted
/// from a string (`--chain=...`) into a `ChainSpec`.
#[derive(Clone, Debug)]
pub enum Alternative {
/// Whatever the current runtime is, with just Alice as an auth.
Development,
/// Whatever the current runtime is, with simple Alice/Bob/Charlie/Dave/Eve auths.
LocalTestnet,
}
/// Helper function to generate a crypto pair from seed
pub fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public {
TPublic::Pair::from_string(&format!("//{seed}"), None)
.expect("static values are valid; qed")
.public()
}
type AccountPublic = <Signature as Verify>::Signer;
/// Helper function to generate an account ID from seed
pub fn get_account_id_from_seed<TPublic: Public>(seed: &str) -> AccountId
where
AccountPublic: From<<TPublic::Pair as Pair>::Public>,
{
AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account()
}
/// Helper function to generate an authority key for Aura
pub fn get_authority_keys_from_seed(s: &str) -> (AccountId, AuraId, BeefyId, GrandpaId) {
(
get_account_id_from_seed::<sr25519::Public>(s),
get_from_seed::<AuraId>(s),
get_from_seed::<BeefyId>(s),
get_from_seed::<GrandpaId>(s),
)
}
impl Alternative {
/// Get an actual chain config from one of the alternatives.
pub(crate) fn load(self) -> ChainSpec {
let properties = Some(
serde_json::json!({
"tokenDecimals": 9,
"tokenSymbol": "MLAU"
})
.as_object()
.expect("Map given; qed")
.clone(),
);
match self {
Alternative::Development => ChainSpec::from_genesis(
"Millau Development",
"millau_dev",
sc_service::ChainType::Development,
|| {
testnet_genesis(
DEV_AUTHORITIES_ACCOUNTS
.into_iter()
.map(get_authority_keys_from_seed)
.collect(),
get_account_id_from_seed::<sr25519::Public>(SUDO_ACCOUNT),
endowed_accounts(),
true,
)
},
vec![],
None,
None,
None,
properties,
None,
),
Alternative::LocalTestnet => ChainSpec::from_genesis(
"Millau Local",
"millau_local",
sc_service::ChainType::Local,
|| {
testnet_genesis(
LOCAL_AUTHORITIES_ACCOUNTS
.into_iter()
.map(get_authority_keys_from_seed)
.collect(),
get_account_id_from_seed::<sr25519::Public>(SUDO_ACCOUNT),
endowed_accounts(),
true,
)
},
vec![],
None,
None,
None,
properties,
None,
),
}
}
}
/// We're using the same set of endowed accounts on all Millau chains (dev/local) to make
/// sure that all accounts, required for bridge to be functional (e.g. relayers fund account,
/// accounts used by relayers in our test deployments, accounts used for demonstration
/// purposes), are all available on these chains.
fn endowed_accounts() -> Vec<AccountId> {
let all_authorities = ALL_AUTHORITIES_ACCOUNTS.iter().flat_map(|x| {
[
get_account_id_from_seed::<sr25519::Public>(x),
get_account_id_from_seed::<sr25519::Public>(&format!("{x}//stash")),
]
});
vec![
// Sudo account
get_account_id_from_seed::<sr25519::Public>(SUDO_ACCOUNT),
// Regular (unused) accounts
get_account_id_from_seed::<sr25519::Public>("Ferdie"),
get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"),
// Accounts, used by Westend<>Millau bridge
get_account_id_from_seed::<sr25519::Public>(WESTEND_GRANDPA_PALLET_OWNER),
get_account_id_from_seed::<sr25519::Public>("Westend.HeadersRelay1"),
get_account_id_from_seed::<sr25519::Public>("Westend.HeadersRelay2"),
get_account_id_from_seed::<sr25519::Public>("Westend.AssetHubWestendHeaders1"),
get_account_id_from_seed::<sr25519::Public>("Westend.AssetHubWestendHeaders2"),
// Accounts, used by Rialto<>Millau bridge
get_account_id_from_seed::<sr25519::Public>(RIALTO_MESSAGES_PALLET_OWNER),
get_account_id_from_seed::<sr25519::Public>("Rialto.HeadersAndMessagesRelay"),
get_account_id_from_seed::<sr25519::Public>("Rialto.OutboundMessagesRelay.Lane00000001"),
get_account_id_from_seed::<sr25519::Public>("Rialto.InboundMessagesRelay.Lane00000001"),
get_account_id_from_seed::<sr25519::Public>("Rialto.MessagesSender"),
// Accounts, used by RialtoParachain<>Millau bridge
get_account_id_from_seed::<sr25519::Public>(RIALTO_PARACHAIN_MESSAGES_PALLET_OWNER),
get_account_id_from_seed::<sr25519::Public>("RialtoParachain.HeadersAndMessagesRelay1"),
get_account_id_from_seed::<sr25519::Public>("RialtoParachain.HeadersAndMessagesRelay2"),
get_account_id_from_seed::<sr25519::Public>("RialtoParachain.RialtoHeadersRelay1"),
get_account_id_from_seed::<sr25519::Public>("RialtoParachain.RialtoHeadersRelay2"),
get_account_id_from_seed::<sr25519::Public>("RialtoParachain.MessagesSender"),
]
.into_iter()
.chain(all_authorities)
.collect()
}
fn session_keys(aura: AuraId, beefy: BeefyId, grandpa: GrandpaId) -> SessionKeys {
SessionKeys { aura, beefy, grandpa }
}
fn testnet_genesis(
initial_authorities: Vec<(AccountId, AuraId, BeefyId, GrandpaId)>,
root_key: AccountId,
endowed_accounts: Vec<AccountId>,
_enable_println: bool,
) -> RuntimeGenesisConfig {
RuntimeGenesisConfig {
system: SystemConfig {
code: WASM_BINARY.expect("Millau development WASM not available").to_vec(),
..Default::default()
},
balances: BalancesConfig {
balances: endowed_accounts.iter().cloned().map(|k| (k, 1 << 50)).collect(),
},
aura: AuraConfig { authorities: Vec::new() },
beefy: BeefyConfig::default(),
grandpa: GrandpaConfig { authorities: Vec::new(), ..Default::default() },
sudo: SudoConfig { key: Some(root_key) },
session: SessionConfig {
keys: initial_authorities
.iter()
.map(|x| {
(x.0.clone(), x.0.clone(), session_keys(x.1.clone(), x.2.clone(), x.3.clone()))
})
.collect::<Vec<_>>(),
},
bridge_westend_grandpa: BridgeWestendGrandpaConfig {
// for our deployments to avoid multiple same-nonces transactions:
// //Alice is already used to initialize Rialto<->Millau bridge
// => let's use //Westend.GrandpaOwner to initialize Westend->Millau bridge
owner: Some(get_account_id_from_seed::<sr25519::Public>(WESTEND_GRANDPA_PALLET_OWNER)),
..Default::default()
},
bridge_rialto_messages: BridgeRialtoMessagesConfig {
owner: Some(get_account_id_from_seed::<sr25519::Public>(RIALTO_MESSAGES_PALLET_OWNER)),
..Default::default()
},
bridge_rialto_parachain_messages: BridgeRialtoParachainMessagesConfig {
owner: Some(get_account_id_from_seed::<sr25519::Public>(
RIALTO_PARACHAIN_MESSAGES_PALLET_OWNER,
)),
..Default::default()
},
xcm_pallet: Default::default(),
}
}
-73
View File
@@ -1,73 +0,0 @@
// 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 clap::Parser;
use sc_cli::RunCmd;
#[derive(Debug, Parser)]
pub struct Cli {
#[structopt(subcommand)]
pub subcommand: Option<Subcommand>,
#[structopt(flatten)]
pub run: RunCmd,
}
/// Possible subcommands of the main binary.
#[derive(Debug, Parser)]
#[allow(clippy::large_enum_variant)]
pub enum Subcommand {
/// Key management CLI utilities
#[clap(subcommand)]
Key(sc_cli::KeySubcommand),
/// Verify a signature for a message, provided on `STDIN`, with a given (public or secret) key.
Verify(sc_cli::VerifyCmd),
/// Generate a seed that provides a vanity address.
Vanity(sc_cli::VanityCmd),
/// Sign a message, with a given (secret) key.
Sign(sc_cli::SignCmd),
/// Build a chain specification.
BuildSpec(sc_cli::BuildSpecCmd),
/// Validate blocks.
CheckBlock(sc_cli::CheckBlockCmd),
/// Export blocks.
ExportBlocks(sc_cli::ExportBlocksCmd),
/// Export the state of a given block into a chain spec.
ExportState(sc_cli::ExportStateCmd),
/// Import blocks.
ImportBlocks(sc_cli::ImportBlocksCmd),
/// Remove the whole chain.
PurgeChain(sc_cli::PurgeChainCmd),
/// Revert the chain to a previous state.
Revert(sc_cli::RevertCmd),
/// Inspect blocks or extrinsics.
Inspect(node_inspect::cli::InspectCmd),
/// Benchmark runtime pallets.
#[clap(subcommand)]
Benchmark(frame_benchmarking_cli::BenchmarkCmd),
}
-154
View File
@@ -1,154 +0,0 @@
// 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::{
cli::{Cli, Subcommand},
service,
service::new_partial,
};
use frame_benchmarking_cli::BenchmarkCmd;
use millau_runtime::{Block, RuntimeApi};
use sc_cli::SubstrateCli;
use sc_service::PartialComponents;
impl SubstrateCli for Cli {
fn impl_name() -> String {
"Millau Bridge Node".into()
}
fn impl_version() -> String {
env!("CARGO_PKG_VERSION").into()
}
fn description() -> String {
"Millau Bridge Node".into()
}
fn author() -> String {
"Parity Technologies".into()
}
fn support_url() -> String {
"https://github.com/paritytech/parity-bridges-common/".into()
}
fn copyright_start_year() -> i32 {
2019
}
fn executable_name() -> String {
"millau-bridge-node".into()
}
fn load_spec(&self, id: &str) -> Result<Box<dyn sc_service::ChainSpec>, String> {
Ok(Box::new(
match id {
"" | "dev" => crate::chain_spec::Alternative::Development,
"local" => crate::chain_spec::Alternative::LocalTestnet,
_ => return Err(format!("Unsupported chain specification: {id}")),
}
.load(),
))
}
}
/// Parse and run command line arguments
pub fn run() -> sc_cli::Result<()> {
let cli = Cli::from_args();
// make sure to set correct crypto version.
sp_core::crypto::set_default_ss58_version(sp_core::crypto::Ss58AddressFormat::custom(
millau_runtime::SS58Prefix::get() as u16,
));
match &cli.subcommand {
Some(Subcommand::Benchmark(cmd)) => {
let runner = cli.create_runner(cmd)?;
match cmd {
BenchmarkCmd::Pallet(cmd) =>
if cfg!(feature = "runtime-benchmarks") {
runner.sync_run(|config| cmd.run::<Block, ()>(config))
} else {
println!(
"Benchmarking wasn't enabled when building the node. \
You can enable it with `--features runtime-benchmarks`."
);
Ok(())
},
_ => Err("Unsupported benchmarking subcommand".into()),
}
},
Some(Subcommand::Key(cmd)) => cmd.run(&cli),
Some(Subcommand::Sign(cmd)) => cmd.run(),
Some(Subcommand::Verify(cmd)) => cmd.run(),
Some(Subcommand::Vanity(cmd)) => cmd.run(),
Some(Subcommand::BuildSpec(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.sync_run(|config| cmd.run(config.chain_spec, config.network))
},
Some(Subcommand::CheckBlock(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.async_run(|config| {
let PartialComponents { client, task_manager, import_queue, .. } =
new_partial(&config)?;
Ok((cmd.run(client, import_queue), task_manager))
})
},
Some(Subcommand::ExportBlocks(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.async_run(|config| {
let PartialComponents { client, task_manager, .. } = new_partial(&config)?;
Ok((cmd.run(client, config.database), task_manager))
})
},
Some(Subcommand::ExportState(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.async_run(|config| {
let PartialComponents { client, task_manager, .. } = new_partial(&config)?;
Ok((cmd.run(client, config.chain_spec), task_manager))
})
},
Some(Subcommand::ImportBlocks(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.async_run(|config| {
let PartialComponents { client, task_manager, import_queue, .. } =
new_partial(&config)?;
Ok((cmd.run(client, import_queue), task_manager))
})
},
Some(Subcommand::PurgeChain(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.sync_run(|config| cmd.run(config.database))
},
Some(Subcommand::Revert(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.async_run(|config| {
let PartialComponents { client, task_manager, backend, .. } = new_partial(&config)?;
Ok((cmd.run(client, backend, None), task_manager))
})
},
Some(Subcommand::Inspect(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner
.sync_run(|config| cmd.run::<Block, RuntimeApi, service::ExecutorDispatch>(config))
},
None => {
let runner = cli.create_runner(&cli.run)?;
runner.run_node_until_exit(|config| async move {
service::new_full(config).map_err(sc_cli::Error::Service)
})
},
}
}
-32
View File
@@ -1,32 +0,0 @@
// 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/>.
//! Substrate Node Template CLI library.
#![warn(missing_docs)]
mod chain_spec;
#[macro_use]
mod service;
mod cli;
mod command;
/// Node run result.
pub type Result = sc_cli::Result<()>;
/// Run node.
pub fn run() -> Result {
command::run()
}
-30
View File
@@ -1,30 +0,0 @@
// 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/>.
//! Millau bridge node.
#![warn(missing_docs)]
mod chain_spec;
#[macro_use]
mod service;
mod cli;
mod command;
/// Run the Millau Node
fn main() -> sc_cli::Result<()> {
command::run()
}
-479
View File
@@ -1,479 +0,0 @@
// 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/>.
//! Service and ServiceFactory implementation. Specialized wrapper over substrate service.
use jsonrpsee::RpcModule;
use millau_runtime::{self, opaque::Block, RuntimeApi};
use sc_client_api::{Backend, BlockBackend};
use sc_consensus_aura::{CompatibilityMode, ImportQueueParams, SlotProportion, StartAuraParams};
use sc_consensus_grandpa::SharedVoterState;
pub use sc_executor::NativeElseWasmExecutor;
use sc_executor::{HeapAllocStrategy, WasmExecutor, DEFAULT_HEAP_ALLOC_STRATEGY};
use sc_service::{error::Error as ServiceError, Configuration, TaskManager};
use sc_telemetry::{Telemetry, TelemetryWorker};
use sc_transaction_pool_api::OffchainTransactionPoolFactory;
use sp_consensus_aura::sr25519::AuthorityPair as AuraPair;
use std::{sync::Arc, time::Duration};
// Our native executor instance.
pub struct ExecutorDispatch;
impl sc_executor::NativeExecutionDispatch for ExecutorDispatch {
/// Only enable the benchmarking host functions when we actually want to benchmark.
#[cfg(feature = "runtime-benchmarks")]
type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;
/// Otherwise we only use the default Substrate host functions.
#[cfg(not(feature = "runtime-benchmarks"))]
type ExtendHostFunctions = ();
fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {
millau_runtime::api::dispatch(method, data)
}
fn native_version() -> sc_executor::NativeVersion {
millau_runtime::native_version()
}
}
type FullClient =
sc_service::TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<ExecutorDispatch>>;
type FullBackend = sc_service::TFullBackend<Block>;
type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;
#[allow(clippy::type_complexity)]
pub fn new_partial(
config: &Configuration,
) -> Result<
sc_service::PartialComponents<
FullClient,
FullBackend,
FullSelectChain,
sc_consensus::DefaultImportQueue<Block>,
sc_transaction_pool::FullPool<Block, FullClient>,
(
sc_consensus_grandpa::GrandpaBlockImport<
FullBackend,
Block,
FullClient,
FullSelectChain,
>,
sc_consensus_grandpa::LinkHalf<Block, FullClient, FullSelectChain>,
sc_consensus_beefy::BeefyVoterLinks<Block>,
sc_consensus_beefy::BeefyRPCLinks<Block>,
Option<Telemetry>,
),
>,
ServiceError,
> {
let telemetry = config
.telemetry_endpoints
.clone()
.filter(|x| !x.is_empty())
.map(|endpoints| -> Result<_, sc_telemetry::Error> {
let worker = TelemetryWorker::new(16)?;
let telemetry = worker.handle().new_telemetry(endpoints);
Ok((worker, telemetry))
})
.transpose()?;
let heap_pages = config
.default_heap_pages
.map_or(DEFAULT_HEAP_ALLOC_STRATEGY, |h| HeapAllocStrategy::Static { extra_pages: h as _ });
let executor = NativeElseWasmExecutor::<ExecutorDispatch>::new_with_wasm_executor(
WasmExecutor::builder()
.with_execution_method(config.wasm_method)
.with_onchain_heap_alloc_strategy(heap_pages)
.with_offchain_heap_alloc_strategy(heap_pages)
.with_max_runtime_instances(config.max_runtime_instances)
.with_runtime_cache_size(config.runtime_cache_size)
.build(),
);
let (client, backend, keystore_container, task_manager) =
sc_service::new_full_parts::<Block, RuntimeApi, _>(
config,
telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),
executor,
)?;
let client = Arc::new(client);
let telemetry = telemetry.map(|(worker, telemetry)| {
task_manager.spawn_handle().spawn("telemetry", None, worker.run());
telemetry
});
let select_chain = sc_consensus::LongestChain::new(backend.clone());
let transaction_pool = sc_transaction_pool::BasicPool::new_full(
config.transaction_pool.clone(),
config.role.is_authority().into(),
config.prometheus_registry(),
task_manager.spawn_essential_handle(),
client.clone(),
);
let (grandpa_block_import, grandpa_link) = sc_consensus_grandpa::block_import(
client.clone(),
512,
&client,
select_chain.clone(),
telemetry.as_ref().map(|x| x.handle()),
)?;
let (beefy_block_import, beefy_voter_links, beefy_rpc_links) =
sc_consensus_beefy::beefy_block_import_and_links(
grandpa_block_import.clone(),
backend.clone(),
client.clone(),
config.prometheus_registry().cloned(),
);
let slot_duration = sc_consensus_aura::slot_duration(&*client)?;
let import_queue =
sc_consensus_aura::import_queue::<AuraPair, _, _, _, _, _>(ImportQueueParams {
block_import: beefy_block_import,
justification_import: Some(Box::new(grandpa_block_import.clone())),
client: client.clone(),
create_inherent_data_providers: move |_, ()| async move {
let timestamp = sp_timestamp::InherentDataProvider::from_system_time();
let slot =
sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(
*timestamp,
slot_duration,
);
Ok((slot, timestamp))
},
spawner: &task_manager.spawn_essential_handle(),
registry: config.prometheus_registry(),
check_for_equivocation: Default::default(),
telemetry: telemetry.as_ref().map(|x| x.handle()),
compatibility_mode: CompatibilityMode::None,
})?;
Ok(sc_service::PartialComponents {
client,
backend,
task_manager,
import_queue,
keystore_container,
select_chain,
transaction_pool,
other: (grandpa_block_import, grandpa_link, beefy_voter_links, beefy_rpc_links, telemetry),
})
}
/// Builds a new service for a full client.
pub fn new_full(config: Configuration) -> Result<TaskManager, ServiceError> {
use sc_service::WarpSyncParams;
let sc_service::PartialComponents {
client,
backend,
mut task_manager,
import_queue,
keystore_container,
select_chain,
transaction_pool,
other: (block_import, grandpa_link, beefy_voter_links, beefy_rpc_links, mut telemetry),
} = new_partial(&config)?;
let genesis_hash = client.block_hash(0).ok().flatten().expect("Genesis block exists; qed");
let mut net_config = sc_network::config::FullNetworkConfiguration::new(&config.network);
// Note: GrandPa is pushed before the Polkadot-specific protocols. This doesn't change
// anything in terms of behaviour, but makes the logs more consistent with the other
// Substrate nodes.
let grandpa_protocol_name = sc_consensus_grandpa::protocol_standard_name(
&client.block_hash(0).ok().flatten().expect("Genesis block exists; qed"),
&config.chain_spec,
);
net_config.add_notification_protocol(sc_consensus_grandpa::grandpa_peers_set_config(
grandpa_protocol_name.clone(),
));
let beefy_gossip_proto_name =
sc_consensus_beefy::gossip_protocol_name(genesis_hash, config.chain_spec.fork_id());
// `beefy_on_demand_justifications_handler` is given to `beefy-gadget` task to be run,
// while `beefy_req_resp_cfg` is added to `config.network.request_response_protocols`.
let (beefy_on_demand_justifications_handler, beefy_req_resp_cfg) =
sc_consensus_beefy::communication::request_response::BeefyJustifsRequestHandler::new(
genesis_hash,
config.chain_spec.fork_id(),
client.clone(),
config.prometheus_registry().cloned(),
);
net_config.add_notification_protocol(
sc_consensus_beefy::communication::beefy_peers_set_config(beefy_gossip_proto_name.clone()),
);
net_config.add_request_response_protocol(beefy_req_resp_cfg);
let role = config.role.clone();
let warp_sync = Arc::new(sc_consensus_grandpa::warp_proof::NetworkProvider::new(
backend.clone(),
grandpa_link.shared_authority_set().clone(),
Vec::default(),
));
let (network, system_rpc_tx, tx_handler_controller, network_starter, sync_service) =
sc_service::build_network(sc_service::BuildNetworkParams {
config: &config,
net_config,
client: client.clone(),
transaction_pool: transaction_pool.clone(),
spawn_handle: task_manager.spawn_handle(),
import_queue,
block_announce_validator_builder: None,
warp_sync_params: Some(WarpSyncParams::WithProvider(warp_sync)),
block_relay: None,
})?;
if config.offchain_worker.enabled {
use futures::FutureExt;
task_manager.spawn_handle().spawn(
"offchain-workers-runner",
"offchain-work",
sc_offchain::OffchainWorkers::new(sc_offchain::OffchainWorkerOptions {
runtime_api_provider: client.clone(),
keystore: Some(keystore_container.keystore()),
offchain_db: backend.offchain_storage(),
transaction_pool: Some(OffchainTransactionPoolFactory::new(
transaction_pool.clone(),
)),
network_provider: network.clone(),
is_validator: role.is_authority(),
enable_http_requests: false,
custom_extensions: move |_| vec![],
})
.run(client.clone(), task_manager.spawn_handle())
.boxed(),
);
}
let force_authoring = config.force_authoring;
let backoff_authoring_blocks: Option<()> = None;
let name = config.network.node_name.clone();
let enable_grandpa = !config.disable_grandpa;
let prometheus_registry = config.prometheus_registry().cloned();
let shared_voter_state = SharedVoterState::empty();
let rpc_extensions_builder = {
use sc_consensus_grandpa::FinalityProofProvider as GrandpaFinalityProofProvider;
use mmr_rpc::{Mmr, MmrApiServer};
use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer};
use sc_consensus_beefy_rpc::{Beefy, BeefyApiServer};
use sc_consensus_grandpa_rpc::{Grandpa, GrandpaApiServer};
use sc_rpc::DenyUnsafe;
use substrate_frame_rpc_system::{System, SystemApiServer};
let backend = backend.clone();
let client = client.clone();
let pool = transaction_pool.clone();
let justification_stream = grandpa_link.justification_stream();
let shared_authority_set = grandpa_link.shared_authority_set().clone();
let shared_voter_state = shared_voter_state.clone();
let finality_proof_provider = GrandpaFinalityProofProvider::new_for_service(
backend.clone(),
Some(shared_authority_set.clone()),
);
Box::new(move |_, subscription_executor: sc_rpc::SubscriptionTaskExecutor| {
let mut io = RpcModule::new(());
let map_err = |e| sc_service::Error::Other(format!("{e}"));
io.merge(System::new(client.clone(), pool.clone(), DenyUnsafe::No).into_rpc())
.map_err(map_err)?;
io.merge(TransactionPayment::new(client.clone()).into_rpc()).map_err(map_err)?;
io.merge(
Grandpa::new(
subscription_executor.clone(),
shared_authority_set.clone(),
shared_voter_state.clone(),
justification_stream.clone(),
finality_proof_provider.clone(),
)
.into_rpc(),
)
.map_err(map_err)?;
io.merge(
Beefy::<Block>::new(
beefy_rpc_links.from_voter_justif_stream.clone(),
beefy_rpc_links.from_voter_best_beefy_stream.clone(),
subscription_executor,
)
.map_err(|e| sc_service::Error::Other(format!("{e}")))?
.into_rpc(),
)
.map_err(map_err)?;
io.merge(
Mmr::new(
client.clone(),
backend
.offchain_storage()
.ok_or("Backend doesn't provide the required offchain storage")?,
)
.into_rpc(),
)
.map_err(map_err)?;
Ok(io)
})
};
let _rpc_handlers = sc_service::spawn_tasks(sc_service::SpawnTasksParams {
network: network.clone(),
client: client.clone(),
keystore: keystore_container.keystore(),
task_manager: &mut task_manager,
transaction_pool: transaction_pool.clone(),
sync_service: sync_service.clone(),
rpc_builder: rpc_extensions_builder,
backend: backend.clone(),
system_rpc_tx,
config,
tx_handler_controller,
telemetry: telemetry.as_mut(),
})?;
if role.is_authority() {
let proposer_factory = sc_basic_authorship::ProposerFactory::new(
task_manager.spawn_handle(),
client.clone(),
transaction_pool.clone(),
prometheus_registry.as_ref(),
telemetry.as_ref().map(|x| x.handle()),
);
let slot_duration = sc_consensus_aura::slot_duration(&*client)?;
let aura = sc_consensus_aura::start_aura::<AuraPair, _, _, _, _, _, _, _, _, _, _>(
StartAuraParams {
slot_duration,
client: client.clone(),
select_chain,
block_import,
proposer_factory,
create_inherent_data_providers: move |_, ()| async move {
let timestamp = sp_timestamp::InherentDataProvider::from_system_time();
let slot =
sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(
*timestamp,
slot_duration,
);
Ok((slot, timestamp))
},
force_authoring,
backoff_authoring_blocks,
keystore: keystore_container.keystore(),
sync_oracle: sync_service.clone(),
justification_sync_link: sync_service.clone(),
block_proposal_slot_portion: SlotProportion::new(2f32 / 3f32),
max_block_proposal_slot_portion: None,
telemetry: telemetry.as_ref().map(|x| x.handle()),
compatibility_mode: CompatibilityMode::None,
},
)?;
// the AURA authoring task is considered essential, i.e. if it
// fails we take down the service with it.
task_manager
.spawn_essential_handle()
.spawn_blocking("aura", Some("block-authoring"), aura);
}
// if the node isn't actively participating in consensus then it doesn't
// need a keystore, regardless of which protocol we use below.
let keystore = if role.is_authority() { Some(keystore_container.keystore()) } else { None };
let justifications_protocol_name = beefy_on_demand_justifications_handler.protocol_name();
let payload_provider = sp_consensus_beefy::mmr::MmrRootProvider::new(client.clone());
let beefy_params = sc_consensus_beefy::BeefyParams {
client: client.clone(),
backend,
payload_provider,
runtime: client,
key_store: keystore.clone(),
network_params: sc_consensus_beefy::BeefyNetworkParams {
network: network.clone(),
sync: sync_service.clone(),
gossip_protocol_name: beefy_gossip_proto_name,
justifications_protocol_name,
_phantom: core::marker::PhantomData::<Block>,
},
min_block_delta: 2,
prometheus_registry: prometheus_registry.clone(),
links: beefy_voter_links,
on_demand_justifications_handler: beefy_on_demand_justifications_handler,
};
// Start the BEEFY bridge gadget.
task_manager.spawn_essential_handle().spawn_blocking(
"beefy-gadget",
None,
sc_consensus_beefy::start_beefy_gadget::<_, _, _, _, _, _, _>(beefy_params),
);
let grandpa_config = sc_consensus_grandpa::Config {
// FIXME #1578 make this available through chainspec
gossip_duration: Duration::from_millis(333),
justification_generation_period: 512,
name: Some(name),
observer_enabled: false,
keystore,
local_role: role,
telemetry: telemetry.as_ref().map(|x| x.handle()),
protocol_name: grandpa_protocol_name,
};
if enable_grandpa {
// start the full GRANDPA voter
// NOTE: non-authorities could run the GRANDPA observer protocol, but at
// this point the full voter should provide better guarantees of block
// and vote data availability than the observer. The observer has not
// been tested extensively yet and having most nodes in a network run it
// could lead to finality stalls.
let grandpa_config = sc_consensus_grandpa::GrandpaParams {
config: grandpa_config,
link: grandpa_link,
network,
sync: sync_service,
voting_rule: sc_consensus_grandpa::VotingRulesBuilder::default().build(),
prometheus_registry,
shared_voter_state,
telemetry: telemetry.as_ref().map(|x| x.handle()),
offchain_tx_pool_factory: OffchainTransactionPoolFactory::new(transaction_pool),
};
// the GRANDPA voter task is considered infallible, i.e.
// if it fails we take down the service with it.
task_manager.spawn_essential_handle().spawn_blocking(
"grandpa-voter",
None,
sc_consensus_grandpa::run_grandpa_voter(grandpa_config)?,
);
}
network_starter.start_network();
Ok(task_manager)
}
-155
View File
@@ -1,155 +0,0 @@
[package]
name = "millau-runtime"
version = "0.1.0"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2021"
repository = "https://github.com/paritytech/parity-bridges-common/"
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
[dependencies]
hex-literal = "0.4"
codec = { package = "parity-scale-codec", version = "3.1.5", default-features = false, features = ["derive"] }
scale-info = { version = "2.10.0", default-features = false, features = ["derive"] }
# Bridge dependencies
bp-header-chain = { path = "../../../primitives/header-chain", default-features = false }
bp-messages = { path = "../../../primitives/messages", default-features = false }
bp-millau = { path = "../../../primitives/chain-millau", default-features = false }
bp-parachains = { path = "../../../primitives/parachains", default-features = false }
bp-polkadot-core = { path = "../../../primitives/polkadot-core", default-features = false }
bp-relayers = { path = "../../../primitives/relayers", default-features = false }
bp-rialto = { path = "../../../primitives/chain-rialto", default-features = false }
bp-rialto-parachain = { path = "../../../primitives/chain-rialto-parachain", default-features = false }
bp-runtime = { path = "../../../primitives/runtime", default-features = false }
bp-westend = { path = "../../../primitives/chain-westend", default-features = false }
bp-xcm-bridge-hub-router = { path = "../../../primitives/xcm-bridge-hub-router", default-features = false }
bridge-runtime-common = { path = "../../runtime-common", default-features = false }
pallet-bridge-grandpa = { path = "../../../modules/grandpa", default-features = false }
pallet-bridge-messages = { path = "../../../modules/messages", default-features = false }
pallet-bridge-parachains = { path = "../../../modules/parachains", default-features = false }
pallet-bridge-relayers = { path = "../../../modules/relayers", default-features = false }
pallet-shift-session-manager = { path = "../../../modules/shift-session-manager", default-features = false }
pallet-xcm-bridge-hub-router = { path = "../../../modules/xcm-bridge-hub-router", default-features = false }
# Substrate Dependencies
sp-consensus-beefy = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
frame-benchmarking = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false, optional = true }
frame-executive = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
frame-support = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
frame-system = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
frame-system-rpc-runtime-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
pallet-aura = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
pallet-authorship = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
pallet-balances = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
pallet-beefy = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
pallet-beefy-mmr = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
pallet-grandpa = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
pallet-mmr = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
pallet-offences = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
pallet-session = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false, features = ["historical"]}
pallet-sudo = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
pallet-timestamp = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
pallet-transaction-payment = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
pallet-transaction-payment-rpc-runtime-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
pallet-utility = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-block-builder = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-consensus-aura = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-core = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-inherents = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-io = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-offchain = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-session = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-std = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-transaction-pool = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-version = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
# Polkadot Dependencies
pallet-xcm = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
xcm = { package = "staging-xcm", git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
xcm-builder = { package = "staging-xcm-builder", git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
xcm-executor = { package = "staging-xcm-executor", git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
[dev-dependencies]
bridge-runtime-common = { path = "../../runtime-common", features = ["integrity-test", "std"] }
env_logger = "0.10"
static_assertions = "1.1"
[build-dependencies]
substrate-wasm-builder = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
[features]
default = [ "std" ]
std = [
"bp-messages/std",
"bp-millau/std",
"bp-parachains/std",
"bp-polkadot-core/std",
"bp-relayers/std",
"bp-rialto-parachain/std",
"bp-rialto/std",
"bp-runtime/std",
"bp-westend/std",
"bp-xcm-bridge-hub-router/std",
"bridge-runtime-common/std",
"codec/std",
"frame-executive/std",
"frame-support/std",
"frame-system-rpc-runtime-api/std",
"frame-system/std",
"pallet-aura/std",
"pallet-authorship/std",
"pallet-balances/std",
"pallet-beefy-mmr/std",
"pallet-beefy/std",
"pallet-bridge-grandpa/std",
"pallet-bridge-messages/std",
"pallet-bridge-parachains/std",
"pallet-bridge-relayers/std",
"pallet-grandpa/std",
"pallet-mmr/std",
"pallet-offences/std",
"pallet-session/std",
"pallet-shift-session-manager/std",
"pallet-sudo/std",
"pallet-timestamp/std",
"pallet-transaction-payment-rpc-runtime-api/std",
"pallet-transaction-payment/std",
"pallet-utility/std",
"pallet-xcm-bridge-hub-router/std",
"pallet-xcm/std",
"scale-info/std",
"sp-api/std",
"sp-block-builder/std",
"sp-consensus-aura/std",
"sp-consensus-beefy/std",
"sp-core/std",
"sp-inherents/std",
"sp-io/std",
"sp-offchain/std",
"sp-runtime/std",
"sp-session/std",
"sp-std/std",
"sp-transaction-pool/std",
"sp-version/std",
"xcm-builder/std",
"xcm-executor/std",
"xcm/std",
]
runtime-benchmarks = [
"bridge-runtime-common/runtime-benchmarks",
"frame-benchmarking/runtime-benchmarks",
"frame-support/runtime-benchmarks",
"frame-system/runtime-benchmarks",
"pallet-bridge-grandpa/runtime-benchmarks",
"pallet-bridge-messages/runtime-benchmarks",
"pallet-bridge-parachains/runtime-benchmarks",
"pallet-bridge-relayers/runtime-benchmarks",
"pallet-xcm-bridge-hub-router/runtime-benchmarks",
"pallet-xcm/runtime-benchmarks",
"sp-runtime/runtime-benchmarks",
"xcm-builder/runtime-benchmarks",
]
-26
View File
@@ -1,26 +0,0 @@
// 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 substrate_wasm_builder::WasmBuilder;
fn main() {
WasmBuilder::new()
.with_current_project()
.import_memory()
.export_heap_base()
.disable_runtime_version_section_check()
.build()
}
File diff suppressed because it is too large Load Diff
@@ -1,216 +0,0 @@
// 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/>.
//! Everything required to serve Millau <-> Rialto messages.
use crate::{RialtoGrandpaInstance, Runtime, RuntimeOrigin, WithRialtoMessagesInstance};
use bp_messages::LaneId;
use bridge_runtime_common::{
messages::{
self, source::TargetHeaderChainAdapter, target::SourceHeaderChainAdapter, MessageBridge,
},
messages_xcm_extension::{SenderAndLane, XcmBlobHauler, XcmBlobHaulerAdapter},
};
use frame_support::{parameter_types, weights::Weight};
use pallet_bridge_relayers::WeightInfoExt as _;
use sp_runtime::RuntimeDebug;
use xcm::latest::prelude::*;
use xcm_builder::HaulBlobExporter;
/// Default lane that is used to send messages to Rialto.
pub const XCM_LANE: LaneId = LaneId([0, 0, 0, 0]);
/// Weight of 2 XCM instructions is for simple `Trap(42)` program, coming through bridge
/// (it is prepended with `UniversalOrigin` instruction). It is used just for simplest manual
/// tests, confirming that we don't break encoding somewhere between.
pub const BASE_XCM_WEIGHT_TWICE: Weight = crate::xcm_config::BaseXcmWeight::get().saturating_mul(2);
parameter_types! {
/// Weight credit for our test messages.
///
/// 2 XCM instructions is for simple `Trap(42)` program, coming through bridge
/// (it is prepended with `UniversalOrigin` instruction).
pub const WeightCredit: Weight = BASE_XCM_WEIGHT_TWICE;
/// Lane used by the with-Rialto bridge.
pub RialtoSenderAndLane: SenderAndLane = SenderAndLane::new(Here.into(), XCM_LANE);
/// Dummy message used in configuration.
pub DummyXcmMessage: Xcm<()> = Xcm::new();
}
/// Message payload for Millau -> Rialto messages.
pub type ToRialtoMessagePayload = messages::source::FromThisChainMessagePayload;
/// Message verifier for Millau -> Rialto messages.
pub type ToRialtoMessageVerifier =
messages::source::FromThisChainMessageVerifier<WithRialtoMessageBridge>;
/// Message payload for Rialto -> Millau messages.
pub type FromRialtoMessagePayload = messages::target::FromBridgedChainMessagePayload;
/// Messages proof for Rialto -> Millau messages.
pub type FromRialtoMessagesProof = messages::target::FromBridgedChainMessagesProof<bp_rialto::Hash>;
/// Messages delivery proof for Millau -> Rialto messages.
pub type ToRialtoMessagesDeliveryProof =
messages::source::FromBridgedChainMessagesDeliveryProof<bp_rialto::Hash>;
/// Call-dispatch based message dispatch for Rialto -> Millau messages.
pub type FromRialtoMessageDispatch =
bridge_runtime_common::messages_xcm_extension::XcmBlobMessageDispatch<
crate::xcm_config::OnMillauBlobDispatcher,
(),
(),
>;
/// Maximal outbound payload size of Millau -> Rialto messages.
pub type ToRialtoMaximalOutboundPayloadSize =
messages::source::FromThisChainMaximalOutboundPayloadSize<WithRialtoMessageBridge>;
/// Millau <-> Rialto message bridge.
#[derive(RuntimeDebug, Clone, Copy)]
pub struct WithRialtoMessageBridge;
impl MessageBridge for WithRialtoMessageBridge {
const BRIDGED_MESSAGES_PALLET_NAME: &'static str = bp_millau::WITH_MILLAU_MESSAGES_PALLET_NAME;
type ThisChain = Millau;
type BridgedChain = Rialto;
type BridgedHeaderChain =
pallet_bridge_grandpa::GrandpaChainHeaders<Runtime, RialtoGrandpaInstance>;
}
/// Millau chain from message lane point of view.
#[derive(RuntimeDebug, Clone, Copy)]
pub struct Millau;
impl messages::UnderlyingChainProvider for Millau {
type Chain = bp_millau::Millau;
}
impl messages::ThisChainWithMessages for Millau {
type RuntimeOrigin = RuntimeOrigin;
}
/// Rialto chain from message lane point of view.
#[derive(RuntimeDebug, Clone, Copy)]
pub struct Rialto;
/// Rialto as source header chain.
pub type RialtoAsSourceHeaderChain = SourceHeaderChainAdapter<WithRialtoMessageBridge>;
/// Rialto as target header chain.
pub type RialtoAsTargetHeaderChain = TargetHeaderChainAdapter<WithRialtoMessageBridge>;
impl messages::UnderlyingChainProvider for Rialto {
type Chain = bp_rialto::Rialto;
}
impl messages::BridgedChainWithMessages for Rialto {}
/// Export XCM messages to be relayed to Rialto.
pub type ToRialtoBlobExporter = HaulBlobExporter<
XcmBlobHaulerAdapter<ToRialtoXcmBlobHauler>,
crate::xcm_config::RialtoNetwork,
(),
>;
/// To-Rialto XCM hauler.
pub struct ToRialtoXcmBlobHauler;
impl XcmBlobHauler for ToRialtoXcmBlobHauler {
type Runtime = Runtime;
type MessagesInstance = WithRialtoMessagesInstance;
type SenderAndLane = RialtoSenderAndLane;
type ToSourceChainSender = crate::xcm_config::XcmRouter;
type CongestedMessage = DummyXcmMessage;
type UncongestedMessage = DummyXcmMessage;
}
impl pallet_bridge_messages::WeightInfoExt for crate::weights::RialtoMessagesWeightInfo<Runtime> {
fn expected_extra_storage_proof_size() -> u32 {
bp_rialto::EXTRA_STORAGE_PROOF_SIZE
}
fn receive_messages_proof_overhead_from_runtime() -> Weight {
pallet_bridge_relayers::weights::BridgeWeight::<Runtime>::receive_messages_proof_overhead_from_runtime()
}
fn receive_messages_delivery_proof_overhead_from_runtime() -> Weight {
pallet_bridge_relayers::weights::BridgeWeight::<Runtime>::receive_messages_delivery_proof_overhead_from_runtime()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Runtime, WithRialtoMessagesInstance};
use bridge_runtime_common::{
assert_complete_bridge_types,
integrity::{
assert_complete_bridge_constants, check_message_lane_weights,
AssertBridgeMessagesPalletConstants, AssertBridgePalletNames, AssertChainConstants,
AssertCompleteBridgeConstants,
},
};
#[test]
fn ensure_millau_message_lane_weights_are_correct() {
check_message_lane_weights::<bp_millau::Millau, Runtime, WithRialtoMessagesInstance>(
bp_rialto::EXTRA_STORAGE_PROOF_SIZE,
bp_millau::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX,
bp_millau::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX,
false,
);
}
#[test]
fn ensure_bridge_integrity() {
assert_complete_bridge_types!(
runtime: Runtime,
with_bridged_chain_grandpa_instance: RialtoGrandpaInstance,
with_bridged_chain_messages_instance: WithRialtoMessagesInstance,
bridge: WithRialtoMessageBridge,
this_chain: bp_millau::Millau,
bridged_chain: bp_rialto::Rialto,
);
assert_complete_bridge_constants::<
Runtime,
RialtoGrandpaInstance,
WithRialtoMessagesInstance,
WithRialtoMessageBridge,
>(AssertCompleteBridgeConstants {
this_chain_constants: AssertChainConstants {
block_length: bp_millau::BlockLength::get(),
block_weights: bp_millau::BlockWeights::get(),
},
messages_pallet_constants: AssertBridgeMessagesPalletConstants {
max_unrewarded_relayers_in_bridged_confirmation_tx:
bp_rialto::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX,
max_unconfirmed_messages_in_bridged_confirmation_tx:
bp_rialto::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX,
bridged_chain_id: bp_runtime::RIALTO_CHAIN_ID,
},
pallet_names: AssertBridgePalletNames {
with_this_chain_messages_pallet_name: bp_millau::WITH_MILLAU_MESSAGES_PALLET_NAME,
with_bridged_chain_grandpa_pallet_name: bp_rialto::WITH_RIALTO_GRANDPA_PALLET_NAME,
with_bridged_chain_messages_pallet_name:
bp_rialto::WITH_RIALTO_MESSAGES_PALLET_NAME,
},
});
}
}
@@ -1,227 +0,0 @@
// 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/>.
//! Everything required to serve Millau <-> RialtoParachain messages.
use crate::{
Runtime, RuntimeOrigin, WithRialtoParachainMessagesInstance, WithRialtoParachainsInstance,
};
use bp_messages::LaneId;
use bridge_runtime_common::{
messages::{
self, source::TargetHeaderChainAdapter, target::SourceHeaderChainAdapter, MessageBridge,
},
messages_xcm_extension::{SenderAndLane, XcmBlobHauler, XcmBlobHaulerAdapter},
};
use frame_support::{parameter_types, weights::Weight};
use pallet_bridge_relayers::WeightInfoExt as _;
use sp_runtime::RuntimeDebug;
use xcm::latest::prelude::*;
use xcm_builder::HaulBlobExporter;
/// Default lane that is used to send messages to Rialto parachain.
pub const XCM_LANE: LaneId = LaneId([0, 0, 0, 0]);
/// Weight of 2 XCM instructions is for simple `Trap(42)` program, coming through bridge
/// (it is prepended with `UniversalOrigin` instruction). It is used just for simplest manual
/// tests, confirming that we don't break encoding somewhere between.
pub const BASE_XCM_WEIGHT_TWICE: Weight = crate::xcm_config::BaseXcmWeight::get().saturating_mul(2);
parameter_types! {
/// Weight credit for our test messages.
///
/// 2 XCM instructions is for simple `Trap(42)` program, coming through bridge
/// (it is prepended with `UniversalOrigin` instruction).
pub const WeightCredit: Weight = BASE_XCM_WEIGHT_TWICE;
/// Lane used by the with-RialtoParachain bridge.
pub RialtoParachainSenderAndLane: SenderAndLane = SenderAndLane::new(Here.into(), XCM_LANE);
/// Dummy message used in configuration.
pub DummyXcmMessage: Xcm<()> = Xcm::new();
}
/// Message payload for Millau -> RialtoParachain messages.
pub type ToRialtoParachainMessagePayload = messages::source::FromThisChainMessagePayload;
/// Message verifier for Millau -> RialtoParachain messages.
pub type ToRialtoParachainMessageVerifier =
messages::source::FromThisChainMessageVerifier<WithRialtoParachainMessageBridge>;
/// Message payload for RialtoParachain -> Millau messages.
pub type FromRialtoParachainMessagePayload = messages::target::FromBridgedChainMessagePayload;
/// Call-dispatch based message dispatch for RialtoParachain -> Millau messages.
pub type FromRialtoParachainMessageDispatch =
bridge_runtime_common::messages_xcm_extension::XcmBlobMessageDispatch<
crate::xcm_config::OnMillauBlobDispatcher,
(),
(),
>;
/// Maximal outbound payload size of Millau -> RialtoParachain messages.
pub type ToRialtoParachainMaximalOutboundPayloadSize =
messages::source::FromThisChainMaximalOutboundPayloadSize<WithRialtoParachainMessageBridge>;
/// Millau <-> RialtoParachain message bridge.
#[derive(RuntimeDebug, Clone, Copy)]
pub struct WithRialtoParachainMessageBridge;
impl MessageBridge for WithRialtoParachainMessageBridge {
const BRIDGED_MESSAGES_PALLET_NAME: &'static str = bp_millau::WITH_MILLAU_MESSAGES_PALLET_NAME;
type ThisChain = Millau;
type BridgedChain = RialtoParachain;
type BridgedHeaderChain = pallet_bridge_parachains::ParachainHeaders<
Runtime,
WithRialtoParachainsInstance,
bp_rialto_parachain::RialtoParachain,
>;
}
/// Millau chain from message lane point of view.
#[derive(RuntimeDebug, Clone, Copy)]
pub struct Millau;
impl messages::UnderlyingChainProvider for Millau {
type Chain = bp_millau::Millau;
}
impl messages::ThisChainWithMessages for Millau {
type RuntimeOrigin = RuntimeOrigin;
}
/// RialtoParachain chain from message lane point of view.
#[derive(RuntimeDebug, Clone, Copy)]
pub struct RialtoParachain;
/// RialtoParachain as source header chain.
pub type RialtoParachainAsSourceHeaderChain =
SourceHeaderChainAdapter<WithRialtoParachainMessageBridge>;
/// RialtoParachain as target header chain.
pub type RialtoParachainAsTargetHeaderChain =
TargetHeaderChainAdapter<WithRialtoParachainMessageBridge>;
impl messages::UnderlyingChainProvider for RialtoParachain {
type Chain = bp_rialto_parachain::RialtoParachain;
}
impl messages::BridgedChainWithMessages for RialtoParachain {}
/// Export XCM messages to be relayed to Rialto.
pub type ToRialtoParachainBlobExporter = HaulBlobExporter<
XcmBlobHaulerAdapter<ToRialtoParachainXcmBlobHauler>,
crate::xcm_config::RialtoParachainNetwork,
(),
>;
/// To-RialtoParachain XCM hauler.
pub struct ToRialtoParachainXcmBlobHauler;
impl XcmBlobHauler for ToRialtoParachainXcmBlobHauler {
type Runtime = Runtime;
type MessagesInstance = WithRialtoParachainMessagesInstance;
type SenderAndLane = RialtoParachainSenderAndLane;
type ToSourceChainSender = crate::xcm_config::XcmRouter;
type CongestedMessage = DummyXcmMessage;
type UncongestedMessage = DummyXcmMessage;
}
impl pallet_bridge_messages::WeightInfoExt
for crate::weights::RialtoParachainMessagesWeightInfo<Runtime>
{
fn expected_extra_storage_proof_size() -> u32 {
bp_rialto_parachain::EXTRA_STORAGE_PROOF_SIZE
}
fn receive_messages_proof_overhead_from_runtime() -> Weight {
pallet_bridge_relayers::weights::BridgeWeight::<Runtime>::receive_messages_proof_overhead_from_runtime()
}
fn receive_messages_delivery_proof_overhead_from_runtime() -> Weight {
pallet_bridge_relayers::weights::BridgeWeight::<Runtime>::receive_messages_delivery_proof_overhead_from_runtime()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
PriorityBoostPerMessage, RialtoGrandpaInstance, Runtime,
WithRialtoParachainMessagesInstance,
};
use bridge_runtime_common::{
assert_complete_bridge_types,
integrity::{
assert_complete_bridge_constants, check_message_lane_weights,
AssertBridgeMessagesPalletConstants, AssertBridgePalletNames, AssertChainConstants,
AssertCompleteBridgeConstants,
},
};
#[test]
fn ensure_millau_message_lane_weights_are_correct() {
check_message_lane_weights::<bp_millau::Millau, Runtime, WithRialtoParachainMessagesInstance>(
bp_rialto_parachain::EXTRA_STORAGE_PROOF_SIZE,
bp_millau::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX,
bp_millau::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX,
true,
);
}
#[test]
fn ensure_bridge_integrity() {
assert_complete_bridge_types!(
runtime: Runtime,
with_bridged_chain_grandpa_instance: RialtoGrandpaInstance,
with_bridged_chain_messages_instance: WithRialtoParachainMessagesInstance,
bridge: WithRialtoParachainMessageBridge,
this_chain: bp_millau::Millau,
bridged_chain: bp_rialto::Rialto,
);
assert_complete_bridge_constants::<
Runtime,
RialtoGrandpaInstance,
WithRialtoParachainMessagesInstance,
WithRialtoParachainMessageBridge,
>(AssertCompleteBridgeConstants {
this_chain_constants: AssertChainConstants {
block_length: bp_millau::BlockLength::get(),
block_weights: bp_millau::BlockWeights::get(),
},
messages_pallet_constants: AssertBridgeMessagesPalletConstants {
max_unrewarded_relayers_in_bridged_confirmation_tx:
bp_rialto_parachain::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX,
max_unconfirmed_messages_in_bridged_confirmation_tx:
bp_rialto_parachain::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX,
bridged_chain_id: bp_runtime::RIALTO_PARACHAIN_CHAIN_ID,
},
pallet_names: AssertBridgePalletNames {
with_this_chain_messages_pallet_name: bp_millau::WITH_MILLAU_MESSAGES_PALLET_NAME,
with_bridged_chain_grandpa_pallet_name: bp_rialto::WITH_RIALTO_GRANDPA_PALLET_NAME,
with_bridged_chain_messages_pallet_name:
bp_rialto_parachain::WITH_RIALTO_PARACHAIN_MESSAGES_PALLET_NAME,
},
});
bridge_runtime_common::priority_calculator::ensure_priority_boost_is_sane::<
Runtime,
WithRialtoParachainMessagesInstance,
PriorityBoostPerMessage,
>(1_000_000);
}
}
@@ -1,21 +0,0 @@
// 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/>.
mod pallet_bridge_messages_messages_bench_runtime_with_rialto_messages_instance;
mod pallet_bridge_messages_messages_bench_runtime_with_rialto_parachain_messages_instance;
pub use pallet_bridge_messages_messages_bench_runtime_with_rialto_messages_instance::WeightInfo as RialtoMessagesWeightInfo;
pub use pallet_bridge_messages_messages_bench_runtime_with_rialto_parachain_messages_instance::WeightInfo as RialtoParachainMessagesWeightInfo;
@@ -1,188 +0,0 @@
//! Autogenerated weights for `pallet_bridge_messages`
//!
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
//! DATE: 2023-05-01, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! WORST CASE MAP SIZE: `1000000`
//! HOSTNAME: `covid`, CPU: `11th Gen Intel(R) Core(TM) i7-11800H @ 2.30GHz`
//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024
// Executed Command:
// target/release/millau-bridge-node
// benchmark
// pallet
// --chain=dev
// --steps=50
// --repeat=20
// --pallet=pallet_bridge_messages
// --extrinsic=*
// --execution=wasm
// --wasm-execution=Compiled
// --heap-pages=4096
// --output=./bin/millau/runtime/src/weights/
#![cfg_attr(rustfmt, rustfmt_skip)]
#![allow(unused_parens)]
#![allow(unused_imports)]
use frame_support::{traits::Get, weights::Weight};
use core::marker::PhantomData;
/// Weight functions for `pallet_bridge_messages`.
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> pallet_bridge_messages::WeightInfo for WeightInfo<T> {
/// Storage: BridgeRialtoMessages PalletOperatingMode (r:1 w:0)
/// Proof: BridgeRialtoMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2), added: 497, mode: MaxEncodedLen)
/// Storage: BridgeRialtoGrandpa ImportedHeaders (r:1 w:0)
/// Proof: BridgeRialtoGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68), added: 2048, mode: MaxEncodedLen)
/// Storage: BridgeRialtoMessages InboundLanes (r:1 w:1)
/// Proof: BridgeRialtoMessages InboundLanes (max_values: None, max_size: Some(49180), added: 51655, mode: MaxEncodedLen)
fn receive_single_message_proof() -> Weight {
// Proof Size summary in bytes:
// Measured: `490`
// Estimated: `57170`
// Minimum execution time: 51_189_000 picoseconds.
Weight::from_parts(52_881_000, 0)
.saturating_add(Weight::from_parts(0, 57170))
.saturating_add(T::DbWeight::get().reads(3))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: BridgeRialtoMessages PalletOperatingMode (r:1 w:0)
/// Proof: BridgeRialtoMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2), added: 497, mode: MaxEncodedLen)
/// Storage: BridgeRialtoGrandpa ImportedHeaders (r:1 w:0)
/// Proof: BridgeRialtoGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68), added: 2048, mode: MaxEncodedLen)
/// Storage: BridgeRialtoMessages InboundLanes (r:1 w:1)
/// Proof: BridgeRialtoMessages InboundLanes (max_values: None, max_size: Some(49180), added: 51655, mode: MaxEncodedLen)
fn receive_two_messages_proof() -> Weight {
// Proof Size summary in bytes:
// Measured: `490`
// Estimated: `57170`
// Minimum execution time: 65_083_000 picoseconds.
Weight::from_parts(66_878_000, 0)
.saturating_add(Weight::from_parts(0, 57170))
.saturating_add(T::DbWeight::get().reads(3))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: BridgeRialtoMessages PalletOperatingMode (r:1 w:0)
/// Proof: BridgeRialtoMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2), added: 497, mode: MaxEncodedLen)
/// Storage: BridgeRialtoGrandpa ImportedHeaders (r:1 w:0)
/// Proof: BridgeRialtoGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68), added: 2048, mode: MaxEncodedLen)
/// Storage: BridgeRialtoMessages InboundLanes (r:1 w:1)
/// Proof: BridgeRialtoMessages InboundLanes (max_values: None, max_size: Some(49180), added: 51655, mode: MaxEncodedLen)
fn receive_single_message_proof_with_outbound_lane_state() -> Weight {
// Proof Size summary in bytes:
// Measured: `490`
// Estimated: `57170`
// Minimum execution time: 57_919_000 picoseconds.
Weight::from_parts(58_927_000, 0)
.saturating_add(Weight::from_parts(0, 57170))
.saturating_add(T::DbWeight::get().reads(3))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: BridgeRialtoMessages PalletOperatingMode (r:1 w:0)
/// Proof: BridgeRialtoMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2), added: 497, mode: MaxEncodedLen)
/// Storage: BridgeRialtoGrandpa ImportedHeaders (r:1 w:0)
/// Proof: BridgeRialtoGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68), added: 2048, mode: MaxEncodedLen)
/// Storage: BridgeRialtoMessages InboundLanes (r:1 w:1)
/// Proof: BridgeRialtoMessages InboundLanes (max_values: None, max_size: Some(49180), added: 51655, mode: MaxEncodedLen)
fn receive_single_message_proof_1_kb() -> Weight {
// Proof Size summary in bytes:
// Measured: `490`
// Estimated: `57170`
// Minimum execution time: 52_202_000 picoseconds.
Weight::from_parts(53_617_000, 0)
.saturating_add(Weight::from_parts(0, 57170))
.saturating_add(T::DbWeight::get().reads(3))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: BridgeRialtoMessages PalletOperatingMode (r:1 w:0)
/// Proof: BridgeRialtoMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2), added: 497, mode: MaxEncodedLen)
/// Storage: BridgeRialtoGrandpa ImportedHeaders (r:1 w:0)
/// Proof: BridgeRialtoGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68), added: 2048, mode: MaxEncodedLen)
/// Storage: BridgeRialtoMessages InboundLanes (r:1 w:1)
/// Proof: BridgeRialtoMessages InboundLanes (max_values: None, max_size: Some(49180), added: 51655, mode: MaxEncodedLen)
fn receive_single_message_proof_16_kb() -> Weight {
// Proof Size summary in bytes:
// Measured: `490`
// Estimated: `57170`
// Minimum execution time: 74_726_000 picoseconds.
Weight::from_parts(76_379_000, 0)
.saturating_add(Weight::from_parts(0, 57170))
.saturating_add(T::DbWeight::get().reads(3))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: BridgeRialtoMessages PalletOperatingMode (r:1 w:0)
/// Proof: BridgeRialtoMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2), added: 497, mode: MaxEncodedLen)
/// Storage: BridgeRialtoGrandpa ImportedHeaders (r:1 w:0)
/// Proof: BridgeRialtoGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68), added: 2048, mode: MaxEncodedLen)
/// Storage: BridgeRialtoMessages OutboundLanes (r:1 w:1)
/// Proof: BridgeRialtoMessages OutboundLanes (max_values: Some(1), max_size: Some(44), added: 539, mode: MaxEncodedLen)
/// Storage: BridgeRelayers RelayerRewards (r:1 w:1)
/// Proof: BridgeRelayers RelayerRewards (max_values: None, max_size: Some(65), added: 2540, mode: MaxEncodedLen)
fn receive_delivery_proof_for_single_message() -> Weight {
// Proof Size summary in bytes:
// Measured: `515`
// Estimated: `9584`
// Minimum execution time: 45_156_000 picoseconds.
Weight::from_parts(46_535_000, 0)
.saturating_add(Weight::from_parts(0, 9584))
.saturating_add(T::DbWeight::get().reads(4))
.saturating_add(T::DbWeight::get().writes(2))
}
/// Storage: BridgeRialtoMessages PalletOperatingMode (r:1 w:0)
/// Proof: BridgeRialtoMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2), added: 497, mode: MaxEncodedLen)
/// Storage: BridgeRialtoGrandpa ImportedHeaders (r:1 w:0)
/// Proof: BridgeRialtoGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68), added: 2048, mode: MaxEncodedLen)
/// Storage: BridgeRialtoMessages OutboundLanes (r:1 w:1)
/// Proof: BridgeRialtoMessages OutboundLanes (max_values: Some(1), max_size: Some(44), added: 539, mode: MaxEncodedLen)
/// Storage: BridgeRelayers RelayerRewards (r:1 w:1)
/// Proof: BridgeRelayers RelayerRewards (max_values: None, max_size: Some(65), added: 2540, mode: MaxEncodedLen)
fn receive_delivery_proof_for_two_messages_by_single_relayer() -> Weight {
// Proof Size summary in bytes:
// Measured: `532`
// Estimated: `9584`
// Minimum execution time: 44_104_000 picoseconds.
Weight::from_parts(45_602_000, 0)
.saturating_add(Weight::from_parts(0, 9584))
.saturating_add(T::DbWeight::get().reads(4))
.saturating_add(T::DbWeight::get().writes(2))
}
/// Storage: BridgeRialtoMessages PalletOperatingMode (r:1 w:0)
/// Proof: BridgeRialtoMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2), added: 497, mode: MaxEncodedLen)
/// Storage: BridgeRialtoGrandpa ImportedHeaders (r:1 w:0)
/// Proof: BridgeRialtoGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68), added: 2048, mode: MaxEncodedLen)
/// Storage: BridgeRialtoMessages OutboundLanes (r:1 w:1)
/// Proof: BridgeRialtoMessages OutboundLanes (max_values: Some(1), max_size: Some(44), added: 539, mode: MaxEncodedLen)
/// Storage: BridgeRelayers RelayerRewards (r:2 w:2)
/// Proof: BridgeRelayers RelayerRewards (max_values: None, max_size: Some(65), added: 2540, mode: MaxEncodedLen)
fn receive_delivery_proof_for_two_messages_by_two_relayers() -> Weight {
// Proof Size summary in bytes:
// Measured: `532`
// Estimated: `12124`
// Minimum execution time: 46_880_000 picoseconds.
Weight::from_parts(48_472_000, 0)
.saturating_add(Weight::from_parts(0, 12124))
.saturating_add(T::DbWeight::get().reads(5))
.saturating_add(T::DbWeight::get().writes(3))
}
/// Storage: BridgeRialtoMessages PalletOperatingMode (r:1 w:0)
/// Proof: BridgeRialtoMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2), added: 497, mode: MaxEncodedLen)
/// Storage: BridgeRialtoGrandpa ImportedHeaders (r:1 w:0)
/// Proof: BridgeRialtoGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68), added: 2048, mode: MaxEncodedLen)
/// Storage: BridgeRialtoMessages InboundLanes (r:1 w:1)
/// Proof: BridgeRialtoMessages InboundLanes (max_values: None, max_size: Some(49180), added: 51655, mode: MaxEncodedLen)
/// The range of component `i` is `[128, 2048]`.
/// The range of component `i` is `[128, 2048]`.
fn receive_single_message_proof_with_dispatch(i: u32, ) -> Weight {
// Proof Size summary in bytes:
// Measured: `490`
// Estimated: `57170`
// Minimum execution time: 107_297_000 picoseconds.
Weight::from_parts(98_819_194, 0)
.saturating_add(Weight::from_parts(0, 57170))
// Standard Error: 2_195
.saturating_add(Weight::from_parts(448_268, 0).saturating_mul(i.into()))
.saturating_add(T::DbWeight::get().reads(3))
.saturating_add(T::DbWeight::get().writes(1))
}
}
@@ -1,188 +0,0 @@
//! Autogenerated weights for `pallet_bridge_messages`
//!
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
//! DATE: 2023-05-01, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! WORST CASE MAP SIZE: `1000000`
//! HOSTNAME: `covid`, CPU: `11th Gen Intel(R) Core(TM) i7-11800H @ 2.30GHz`
//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024
// Executed Command:
// target/release/millau-bridge-node
// benchmark
// pallet
// --chain=dev
// --steps=50
// --repeat=20
// --pallet=pallet_bridge_messages
// --extrinsic=*
// --execution=wasm
// --wasm-execution=Compiled
// --heap-pages=4096
// --output=./bin/millau/runtime/src/weights/
#![cfg_attr(rustfmt, rustfmt_skip)]
#![allow(unused_parens)]
#![allow(unused_imports)]
use frame_support::{traits::Get, weights::Weight};
use core::marker::PhantomData;
/// Weight functions for `pallet_bridge_messages`.
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> pallet_bridge_messages::WeightInfo for WeightInfo<T> {
/// Storage: BridgeRialtoParachainMessages PalletOperatingMode (r:1 w:0)
/// Proof: BridgeRialtoParachainMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2), added: 497, mode: MaxEncodedLen)
/// Storage: BridgeRialtoParachains ImportedParaHeads (r:1 w:0)
/// Proof: BridgeRialtoParachains ImportedParaHeads (max_values: Some(1024), max_size: Some(196), added: 1681, mode: MaxEncodedLen)
/// Storage: BridgeRialtoParachainMessages InboundLanes (r:1 w:1)
/// Proof: BridgeRialtoParachainMessages InboundLanes (max_values: None, max_size: Some(49180), added: 51655, mode: MaxEncodedLen)
fn receive_single_message_proof() -> Weight {
// Proof Size summary in bytes:
// Measured: `428`
// Estimated: `56803`
// Minimum execution time: 49_949_000 picoseconds.
Weight::from_parts(51_439_000, 0)
.saturating_add(Weight::from_parts(0, 56803))
.saturating_add(T::DbWeight::get().reads(3))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: BridgeRialtoParachainMessages PalletOperatingMode (r:1 w:0)
/// Proof: BridgeRialtoParachainMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2), added: 497, mode: MaxEncodedLen)
/// Storage: BridgeRialtoParachains ImportedParaHeads (r:1 w:0)
/// Proof: BridgeRialtoParachains ImportedParaHeads (max_values: Some(1024), max_size: Some(196), added: 1681, mode: MaxEncodedLen)
/// Storage: BridgeRialtoParachainMessages InboundLanes (r:1 w:1)
/// Proof: BridgeRialtoParachainMessages InboundLanes (max_values: None, max_size: Some(49180), added: 51655, mode: MaxEncodedLen)
fn receive_two_messages_proof() -> Weight {
// Proof Size summary in bytes:
// Measured: `428`
// Estimated: `56803`
// Minimum execution time: 62_552_000 picoseconds.
Weight::from_parts(64_899_000, 0)
.saturating_add(Weight::from_parts(0, 56803))
.saturating_add(T::DbWeight::get().reads(3))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: BridgeRialtoParachainMessages PalletOperatingMode (r:1 w:0)
/// Proof: BridgeRialtoParachainMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2), added: 497, mode: MaxEncodedLen)
/// Storage: BridgeRialtoParachains ImportedParaHeads (r:1 w:0)
/// Proof: BridgeRialtoParachains ImportedParaHeads (max_values: Some(1024), max_size: Some(196), added: 1681, mode: MaxEncodedLen)
/// Storage: BridgeRialtoParachainMessages InboundLanes (r:1 w:1)
/// Proof: BridgeRialtoParachainMessages InboundLanes (max_values: None, max_size: Some(49180), added: 51655, mode: MaxEncodedLen)
fn receive_single_message_proof_with_outbound_lane_state() -> Weight {
// Proof Size summary in bytes:
// Measured: `428`
// Estimated: `56803`
// Minimum execution time: 56_795_000 picoseconds.
Weight::from_parts(58_441_000, 0)
.saturating_add(Weight::from_parts(0, 56803))
.saturating_add(T::DbWeight::get().reads(3))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: BridgeRialtoParachainMessages PalletOperatingMode (r:1 w:0)
/// Proof: BridgeRialtoParachainMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2), added: 497, mode: MaxEncodedLen)
/// Storage: BridgeRialtoParachains ImportedParaHeads (r:1 w:0)
/// Proof: BridgeRialtoParachains ImportedParaHeads (max_values: Some(1024), max_size: Some(196), added: 1681, mode: MaxEncodedLen)
/// Storage: BridgeRialtoParachainMessages InboundLanes (r:1 w:1)
/// Proof: BridgeRialtoParachainMessages InboundLanes (max_values: None, max_size: Some(49180), added: 51655, mode: MaxEncodedLen)
fn receive_single_message_proof_1_kb() -> Weight {
// Proof Size summary in bytes:
// Measured: `428`
// Estimated: `56803`
// Minimum execution time: 51_340_000 picoseconds.
Weight::from_parts(52_533_000, 0)
.saturating_add(Weight::from_parts(0, 56803))
.saturating_add(T::DbWeight::get().reads(3))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: BridgeRialtoParachainMessages PalletOperatingMode (r:1 w:0)
/// Proof: BridgeRialtoParachainMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2), added: 497, mode: MaxEncodedLen)
/// Storage: BridgeRialtoParachains ImportedParaHeads (r:1 w:0)
/// Proof: BridgeRialtoParachains ImportedParaHeads (max_values: Some(1024), max_size: Some(196), added: 1681, mode: MaxEncodedLen)
/// Storage: BridgeRialtoParachainMessages InboundLanes (r:1 w:1)
/// Proof: BridgeRialtoParachainMessages InboundLanes (max_values: None, max_size: Some(49180), added: 51655, mode: MaxEncodedLen)
fn receive_single_message_proof_16_kb() -> Weight {
// Proof Size summary in bytes:
// Measured: `428`
// Estimated: `56803`
// Minimum execution time: 74_022_000 picoseconds.
Weight::from_parts(75_115_000, 0)
.saturating_add(Weight::from_parts(0, 56803))
.saturating_add(T::DbWeight::get().reads(3))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: BridgeRialtoParachainMessages PalletOperatingMode (r:1 w:0)
/// Proof: BridgeRialtoParachainMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2), added: 497, mode: MaxEncodedLen)
/// Storage: BridgeRialtoParachains ImportedParaHeads (r:1 w:0)
/// Proof: BridgeRialtoParachains ImportedParaHeads (max_values: Some(1024), max_size: Some(196), added: 1681, mode: MaxEncodedLen)
/// Storage: BridgeRialtoParachainMessages OutboundLanes (r:1 w:1)
/// Proof: BridgeRialtoParachainMessages OutboundLanes (max_values: Some(1), max_size: Some(44), added: 539, mode: MaxEncodedLen)
/// Storage: BridgeRelayers RelayerRewards (r:1 w:1)
/// Proof: BridgeRelayers RelayerRewards (max_values: None, max_size: Some(65), added: 2540, mode: MaxEncodedLen)
fn receive_delivery_proof_for_single_message() -> Weight {
// Proof Size summary in bytes:
// Measured: `453`
// Estimated: `9217`
// Minimum execution time: 43_296_000 picoseconds.
Weight::from_parts(45_022_000, 0)
.saturating_add(Weight::from_parts(0, 9217))
.saturating_add(T::DbWeight::get().reads(4))
.saturating_add(T::DbWeight::get().writes(2))
}
/// Storage: BridgeRialtoParachainMessages PalletOperatingMode (r:1 w:0)
/// Proof: BridgeRialtoParachainMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2), added: 497, mode: MaxEncodedLen)
/// Storage: BridgeRialtoParachains ImportedParaHeads (r:1 w:0)
/// Proof: BridgeRialtoParachains ImportedParaHeads (max_values: Some(1024), max_size: Some(196), added: 1681, mode: MaxEncodedLen)
/// Storage: BridgeRialtoParachainMessages OutboundLanes (r:1 w:1)
/// Proof: BridgeRialtoParachainMessages OutboundLanes (max_values: Some(1), max_size: Some(44), added: 539, mode: MaxEncodedLen)
/// Storage: BridgeRelayers RelayerRewards (r:1 w:1)
/// Proof: BridgeRelayers RelayerRewards (max_values: None, max_size: Some(65), added: 2540, mode: MaxEncodedLen)
fn receive_delivery_proof_for_two_messages_by_single_relayer() -> Weight {
// Proof Size summary in bytes:
// Measured: `470`
// Estimated: `9217`
// Minimum execution time: 42_618_000 picoseconds.
Weight::from_parts(43_972_000, 0)
.saturating_add(Weight::from_parts(0, 9217))
.saturating_add(T::DbWeight::get().reads(4))
.saturating_add(T::DbWeight::get().writes(2))
}
/// Storage: BridgeRialtoParachainMessages PalletOperatingMode (r:1 w:0)
/// Proof: BridgeRialtoParachainMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2), added: 497, mode: MaxEncodedLen)
/// Storage: BridgeRialtoParachains ImportedParaHeads (r:1 w:0)
/// Proof: BridgeRialtoParachains ImportedParaHeads (max_values: Some(1024), max_size: Some(196), added: 1681, mode: MaxEncodedLen)
/// Storage: BridgeRialtoParachainMessages OutboundLanes (r:1 w:1)
/// Proof: BridgeRialtoParachainMessages OutboundLanes (max_values: Some(1), max_size: Some(44), added: 539, mode: MaxEncodedLen)
/// Storage: BridgeRelayers RelayerRewards (r:2 w:2)
/// Proof: BridgeRelayers RelayerRewards (max_values: None, max_size: Some(65), added: 2540, mode: MaxEncodedLen)
fn receive_delivery_proof_for_two_messages_by_two_relayers() -> Weight {
// Proof Size summary in bytes:
// Measured: `470`
// Estimated: `11757`
// Minimum execution time: 45_954_000 picoseconds.
Weight::from_parts(46_892_000, 0)
.saturating_add(Weight::from_parts(0, 11757))
.saturating_add(T::DbWeight::get().reads(5))
.saturating_add(T::DbWeight::get().writes(3))
}
/// Storage: BridgeRialtoParachainMessages PalletOperatingMode (r:1 w:0)
/// Proof: BridgeRialtoParachainMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2), added: 497, mode: MaxEncodedLen)
/// Storage: BridgeRialtoParachains ImportedParaHeads (r:1 w:0)
/// Proof: BridgeRialtoParachains ImportedParaHeads (max_values: Some(1024), max_size: Some(196), added: 1681, mode: MaxEncodedLen)
/// Storage: BridgeRialtoParachainMessages InboundLanes (r:1 w:1)
/// Proof: BridgeRialtoParachainMessages InboundLanes (max_values: None, max_size: Some(49180), added: 51655, mode: MaxEncodedLen)
/// The range of component `i` is `[128, 2048]`.
/// The range of component `i` is `[128, 2048]`.
fn receive_single_message_proof_with_dispatch(i: u32, ) -> Weight {
// Proof Size summary in bytes:
// Measured: `428`
// Estimated: `56803`
// Minimum execution time: 107_766_000 picoseconds.
Weight::from_parts(97_865_035, 0)
.saturating_add(Weight::from_parts(0, 56803))
// Standard Error: 2_179
.saturating_add(Weight::from_parts(447_749, 0).saturating_mul(i.into()))
.saturating_add(T::DbWeight::get().reads(3))
.saturating_add(T::DbWeight::get().writes(1))
}
}
@@ -1,410 +0,0 @@
// 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/>.
//! XCM configurations for the Millau runtime.
use super::{
rialto_messages::ToRialtoBlobExporter,
rialto_parachain_messages::ToRialtoParachainBlobExporter, AccountId, AllPalletsWithSystem,
Balances, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, XcmPallet,
};
use bp_millau::WeightToFee;
use bridge_runtime_common::CustomNetworkId;
use frame_support::{
parameter_types,
traits::{ConstU32, Everything, Nothing},
weights::Weight,
};
use frame_system::EnsureRoot;
use xcm::latest::prelude::*;
use xcm_builder::{
AccountId32Aliases, CurrencyAdapter as XcmCurrencyAdapter, IsConcrete, MintLocation,
SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,
UsingComponents,
};
use xcm_executor::traits::ExportXcm;
parameter_types! {
/// The location of the `MLAU` token, from the context of this chain. Since this token is native to this
/// chain, we make it synonymous with it and thus it is the `Here` location, which means "equivalent to
/// the context".
pub const TokenLocation: MultiLocation = Here.into_location();
/// Token asset identifier.
pub TokenAssetId: AssetId = TokenLocation::get().into();
/// The Millau network ID.
pub const ThisNetwork: NetworkId = CustomNetworkId::Millau.as_network_id();
/// The Rialto network ID.
pub const RialtoNetwork: NetworkId = CustomNetworkId::Rialto.as_network_id();
/// The RialtoParachain network ID.
pub const RialtoParachainNetwork: NetworkId = CustomNetworkId::RialtoParachain.as_network_id();
/// Our XCM location ancestry - i.e. our location within the Consensus Universe.
///
/// Since Kusama is a top-level relay-chain with its own consensus, it's just our network ID.
pub UniversalLocation: InteriorMultiLocation = ThisNetwork::get().into();
/// The check account, which holds any native assets that have been teleported out and not back in (yet).
pub CheckAccount: (AccountId, MintLocation) = (XcmPallet::check_account(), MintLocation::Local);
}
/// The canonical means of converting a `MultiLocation` into an `AccountId`, used when we want to
/// determine the sovereign account controlled by a location.
pub type SovereignAccountOf = (
// We can directly alias an `AccountId32` into a local account.
AccountId32Aliases<ThisNetwork, AccountId>,
);
/// Our asset transactor. This is what allows us to interest with the runtime facilities from the
/// point of view of XCM-only concepts like `MultiLocation` and `MultiAsset`.
///
/// Ours is only aware of the Balances pallet, which is mapped to `TokenLocation`.
pub type LocalAssetTransactor = XcmCurrencyAdapter<
// Use this currency:
Balances,
// Use this currency when it is a fungible asset matching the given location or name:
IsConcrete<TokenLocation>,
// We can convert the MultiLocations with our converter above:
SovereignAccountOf,
// Our chain's account ID type (we can't get away without mentioning it explicitly):
AccountId,
// We track our teleports in/out to keep total issuance correct.
CheckAccount,
>;
/// The means that we convert the XCM message origin location into a local dispatch origin.
type LocalOriginConverter = (
// A `Signed` origin of the sovereign account that the original location controls.
SovereignSignedViaLocation<SovereignAccountOf, RuntimeOrigin>,
// The AccountId32 location type can be expressed natively as a `Signed` origin.
SignedAccountId32AsNative<ThisNetwork, RuntimeOrigin>,
);
parameter_types! {
/// The amount of weight an XCM operation takes. This is a safe overestimate.
pub const BaseXcmWeight: Weight = Weight::from_parts(1_000_000_000, 64 * 1024);
/// Maximum number of instructions in a single XCM fragment. A sanity check against weight
/// calculations getting too crazy.
pub const MaxInstructions: u32 = 100;
}
/// The XCM router. We are not sending messages to sibling/parent/child chains here.
pub type XcmRouter = EmulatedSiblingXcmpChannel;
/// The barriers one of which must be passed for an XCM message to be executed.
pub type Barrier = (
// Weight that is paid for may be consumed.
TakeWeightCredit,
);
/// Dispatches received XCM messages from other chain.
pub type OnMillauBlobDispatcher = xcm_builder::BridgeBlobDispatcher<
crate::xcm_config::XcmRouter,
crate::xcm_config::UniversalLocation,
(),
>;
/// XCM weigher type.
pub type XcmWeigher = xcm_builder::FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
pub struct XcmConfig;
impl xcm_executor::Config for XcmConfig {
type RuntimeCall = RuntimeCall;
type XcmSender = ();
type AssetTransactor = LocalAssetTransactor;
type OriginConverter = LocalOriginConverter;
type IsReserve = ();
type IsTeleporter = ();
type UniversalLocation = UniversalLocation;
type Barrier = Barrier;
type Weigher = XcmWeigher;
// The weight trader piggybacks on the existing transaction-fee conversion logic.
type Trader = UsingComponents<WeightToFee, TokenLocation, AccountId, Balances, ()>;
type ResponseHandler = XcmPallet;
type AssetTrap = XcmPallet;
type AssetLocker = ();
type AssetExchanger = ();
type AssetClaims = XcmPallet;
type SubscriptionService = XcmPallet;
type PalletInstancesInfo = AllPalletsWithSystem;
type MaxAssetsIntoHolding = ConstU32<64>;
type FeeManager = ();
type MessageExporter = ToRialtoOrRialtoParachainSwitchExporter;
type UniversalAliases = Nothing;
type CallDispatcher = RuntimeCall;
type SafeCallFilter = Everything;
type Aliasers = Nothing;
}
/// Type to convert an `Origin` type value into a `MultiLocation` value which represents an interior
/// location of this chain.
pub type LocalOriginToLocation = (
// Usual Signed origin to be used in XCM as a corresponding AccountId32
SignedToAccountId32<RuntimeOrigin, AccountId, ThisNetwork>,
);
#[cfg(feature = "runtime-benchmarks")]
parameter_types! {
pub ReachableDest: Option<MultiLocation> = None;
}
impl pallet_xcm::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
// We don't allow any messages to be sent via the transaction yet. This is basically safe to
// enable, (safe the possibility of someone spamming the parachain if they're willing to pay
// the DOT to send from the Relay-chain). But it's useless until we bring in XCM v3 which will
// make `DescendOrigin` a bit more useful.
type SendXcmOrigin = xcm_builder::EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
type XcmRouter = ();
// Anyone can execute XCM messages locally.
type ExecuteXcmOrigin = xcm_builder::EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
type XcmExecuteFilter = Everything;
type XcmExecutor = xcm_executor::XcmExecutor<XcmConfig>;
// Anyone is able to use teleportation regardless of who they are and what they want to
// teleport.
type XcmTeleportFilter = Everything;
// Anyone is able to use reserve transfers regardless of who they are and what they want to
// transfer.
type XcmReserveTransferFilter = Everything;
type Weigher = XcmWeigher;
type UniversalLocation = UniversalLocation;
type RuntimeOrigin = RuntimeOrigin;
type RuntimeCall = RuntimeCall;
const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
type Currency = Balances;
type CurrencyMatcher = ();
type TrustedLockers = ();
type SovereignAccountOf = SovereignAccountOf;
type MaxLockers = frame_support::traits::ConstU32<8>;
type WeightInfo = pallet_xcm::TestWeightInfo;
#[cfg(feature = "runtime-benchmarks")]
type ReachableDest = ReachableDest;
type AdminOrigin = EnsureRoot<AccountId>;
type MaxRemoteLockConsumers = ConstU32<0>;
type RemoteLockConsumerIdentifier = ();
}
pub struct ToRialtoOrRialtoParachainSwitchExporter;
impl ExportXcm for ToRialtoOrRialtoParachainSwitchExporter {
type Ticket = (NetworkId, (sp_std::prelude::Vec<u8>, XcmHash));
fn validate(
network: NetworkId,
channel: u32,
universal_source: &mut Option<InteriorMultiLocation>,
destination: &mut Option<InteriorMultiLocation>,
message: &mut Option<Xcm<()>>,
) -> SendResult<Self::Ticket> {
if network == RialtoNetwork::get() {
ToRialtoBlobExporter::validate(network, channel, universal_source, destination, message)
.map(|result| ((RialtoNetwork::get(), result.0), result.1))
} else if network == RialtoParachainNetwork::get() {
ToRialtoParachainBlobExporter::validate(
network,
channel,
universal_source,
destination,
message,
)
.map(|result| ((RialtoParachainNetwork::get(), result.0), result.1))
} else {
Err(SendError::Unroutable)
}
}
fn deliver(ticket: Self::Ticket) -> Result<XcmHash, SendError> {
let (network, ticket) = ticket;
if network == RialtoNetwork::get() {
ToRialtoBlobExporter::deliver(ticket)
} else if network == RialtoParachainNetwork::get() {
ToRialtoParachainBlobExporter::deliver(ticket)
} else {
Err(SendError::Unroutable)
}
}
}
/// Emulating XCMP channel with sibling chain. We don't have required infra here, at Millau,
/// so we have to provide at least something to be able to run benchmarks.
pub struct EmulatedSiblingXcmpChannel;
impl SendXcm for EmulatedSiblingXcmpChannel {
type Ticket = ();
fn validate(
_destination: &mut Option<MultiLocation>,
_message: &mut Option<Xcm<()>>,
) -> SendResult<Self::Ticket> {
Ok(((), Default::default()))
}
fn deliver(_ticket: Self::Ticket) -> Result<XcmHash, SendError> {
Ok(XcmHash::default())
}
}
impl EmulatedSiblingXcmpChannel {
/// Start emulating congested channel.
pub fn make_congested() {
frame_support::storage::unhashed::put(b"EmulatedSiblingXcmpChannel.Congested", &true);
}
}
impl bp_xcm_bridge_hub_router::XcmChannelStatusProvider for EmulatedSiblingXcmpChannel {
fn is_congested() -> bool {
frame_support::storage::unhashed::get_or_default(b"EmulatedSiblingXcmpChannel.Congested")
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
rialto_messages::FromRialtoMessageDispatch, WithRialtoMessagesInstance,
WithRialtoParachainMessagesInstance,
};
use bp_messages::{
target_chain::{DispatchMessage, DispatchMessageData, MessageDispatch},
LaneId, MessageKey,
};
use bridge_runtime_common::messages_xcm_extension::XcmBlobMessageDispatchResult;
use codec::Encode;
use pallet_bridge_messages::OutboundLanes;
use sp_runtime::BuildStorage;
use xcm_executor::XcmExecutor;
fn new_test_ext() -> sp_io::TestExternalities {
sp_io::TestExternalities::new(
frame_system::GenesisConfig::<Runtime>::default().build_storage().unwrap(),
)
}
fn prepare_outbound_xcm_message(destination: NetworkId) -> Xcm<RuntimeCall> {
vec![ExportMessage {
network: destination,
destination: destination.into(),
xcm: vec![Instruction::Trap(42)].into(),
}]
.into()
}
#[test]
fn xcm_messages_to_rialto_are_sent_using_bridge_exporter() {
new_test_ext().execute_with(|| {
// ensure that the there are no messages queued
assert_eq!(
OutboundLanes::<Runtime, WithRialtoMessagesInstance>::get(
crate::rialto_messages::XCM_LANE
)
.latest_generated_nonce,
0,
);
// export message instruction "sends" message to Rialto
XcmExecutor::<XcmConfig>::execute_xcm_in_credit(
Here,
prepare_outbound_xcm_message(RialtoNetwork::get()),
Default::default(),
Weight::MAX,
Weight::MAX,
)
.ensure_complete()
.expect("runtime configuration must be correct");
// ensure that the message has been queued
assert_eq!(
OutboundLanes::<Runtime, WithRialtoMessagesInstance>::get(
crate::rialto_messages::XCM_LANE
)
.latest_generated_nonce,
1,
);
})
}
#[test]
fn xcm_messages_to_rialto_parachain_are_sent_using_bridge_exporter() {
new_test_ext().execute_with(|| {
// ensure that the there are no messages queued
assert_eq!(
OutboundLanes::<Runtime, WithRialtoParachainMessagesInstance>::get(
crate::rialto_parachain_messages::XCM_LANE
)
.latest_generated_nonce,
0,
);
// export message instruction "sends" message to Rialto
XcmExecutor::<XcmConfig>::execute_xcm_in_credit(
Here,
prepare_outbound_xcm_message(RialtoParachainNetwork::get()),
Default::default(),
Weight::MAX,
Weight::MAX,
)
.ensure_complete()
.expect("runtime configuration must be correct");
// ensure that the message has been queued
assert_eq!(
OutboundLanes::<Runtime, WithRialtoParachainMessagesInstance>::get(
crate::rialto_parachain_messages::XCM_LANE
)
.latest_generated_nonce,
1,
);
})
}
fn prepare_inbound_bridge_message() -> DispatchMessage<Vec<u8>> {
let xcm = xcm::VersionedXcm::<RuntimeCall>::V3(vec![Instruction::Trap(42)].into());
let location =
xcm::VersionedInteriorMultiLocation::V3(X1(GlobalConsensus(ThisNetwork::get())));
// this is the `BridgeMessage` from polkadot xcm builder, but it has no constructor
// or public fields, so just tuple
let bridge_message = (location, xcm).encode();
DispatchMessage {
key: MessageKey { lane_id: LaneId([0, 0, 0, 0]), nonce: 1 },
data: DispatchMessageData { payload: Ok(bridge_message) },
}
}
#[test]
fn xcm_messages_from_rialto_are_dispatched() {
let incoming_message = prepare_inbound_bridge_message();
// we care only about handing message to the XCM dispatcher, so we don't care about its
// actual dispatch
let dispatch_result = FromRialtoMessageDispatch::dispatch(incoming_message);
assert!(matches!(
dispatch_result.dispatch_level_result,
XcmBlobMessageDispatchResult::Dispatched,
));
}
#[test]
fn xcm_messages_from_rialto_parachain_are_dispatched() {
let incoming_message = prepare_inbound_bridge_message();
// we care only about handing message to the XCM dispatcher, so we don't care about its
// actual dispatch
let dispatch_result = FromRialtoMessageDispatch::dispatch(incoming_message);
assert!(matches!(
dispatch_result.dispatch_level_result,
XcmBlobMessageDispatchResult::Dispatched,
));
}
}
@@ -1,81 +0,0 @@
[package]
name = "rialto-parachain-collator"
version = "0.1.0"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2021"
repository = "https://github.com/paritytech/parity-bridges-common/"
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
[build-dependencies]
substrate-build-script-utils = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
[[bin]]
name = 'rialto-parachain-collator'
[features]
default = []
runtime-benchmarks = [ 'rialto-parachain-runtime/runtime-benchmarks' ]
[dependencies]
clap = { version = "4.4.8", features = ["derive"] }
log = '0.4.20'
codec = { package = 'parity-scale-codec', version = '3.1.5' }
serde = { version = '1.0', features = ['derive'] }
# RPC related Dependencies
jsonrpsee = { version = "0.16.2", features = ["server"] }
# Local Dependencies
rialto-parachain-runtime = { path = '../runtime' }
# Substrate Dependencies
frame-benchmarking = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
frame-benchmarking-cli = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
pallet-transaction-payment-rpc = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
substrate-frame-rpc-system = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
substrate-prometheus-endpoint = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
## Substrate Client Dependencies
sc-basic-authorship = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sc-chain-spec = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sc-cli = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sc-client-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sc-consensus = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sc-executor = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sc-network = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sc-network-sync = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sc-rpc = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sc-rpc-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sc-service = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master"}
sc-telemetry = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sc-transaction-pool = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sc-tracing = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
## Substrate Primitive Dependencies
sp-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sp-block-builder = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sp-consensus-aura = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sp-core = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sp-keystore = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sp-offchain = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sp-session = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sp-timestamp = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sp-transaction-pool = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
# Cumulus dependencies
cumulus-client-consensus-aura = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
cumulus-client-consensus-common = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
cumulus-client-cli = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
cumulus-client-network = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
cumulus-client-service = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
cumulus-primitives-core = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
cumulus-primitives-parachain-inherent = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
cumulus-relay-chain-interface = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
# Polkadot dependencies
polkadot-cli = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
polkadot-primitives = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
polkadot-service = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
@@ -1,22 +0,0 @@
// 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 substrate_build_script_utils::{generate_cargo_keys, rerun_if_git_head_changed};
fn main() {
generate_cargo_keys();
rerun_if_git_head_changed();
}
@@ -1,202 +0,0 @@
// 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/>.
use cumulus_primitives_core::ParaId;
use rialto_parachain_runtime::{AccountId, AuraId, BridgeMillauMessagesConfig, Signature};
use sc_chain_spec::{ChainSpecExtension, ChainSpecGroup};
use sc_service::ChainType;
use serde::{Deserialize, Serialize};
use sp_core::{sr25519, Pair, Public};
use sp_runtime::traits::{IdentifyAccount, Verify};
/// "Names" of the authorities accounts at local testnet.
const LOCAL_AUTHORITIES_ACCOUNTS: [&str; 2] = ["Alice", "Bob"];
/// "Names" of the authorities accounts at development testnet.
const DEV_AUTHORITIES_ACCOUNTS: [&str; 2] = LOCAL_AUTHORITIES_ACCOUNTS;
/// "Names" of all possible authorities accounts.
const ALL_AUTHORITIES_ACCOUNTS: [&str; 2] = LOCAL_AUTHORITIES_ACCOUNTS;
/// "Name" of the `sudo` account.
const SUDO_ACCOUNT: &str = "Sudo";
/// "Name" of the account, which owns the with-Millau messages pallet.
const MILLAU_MESSAGES_PALLET_OWNER: &str = "Millau.MessagesOwner";
/// Specialized `ChainSpec` for the normal parachain runtime.
pub type ChainSpec =
sc_service::GenericChainSpec<rialto_parachain_runtime::RuntimeGenesisConfig, Extensions>;
/// Helper function to generate a crypto pair from seed
pub fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public {
TPublic::Pair::from_string(&format!("//{seed}"), None)
.expect("static values are valid; qed")
.public()
}
/// The extensions for the [`ChainSpec`].
#[derive(
Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ChainSpecGroup, ChainSpecExtension,
)]
#[serde(deny_unknown_fields)]
pub struct Extensions {
/// The relay chain of the Parachain.
pub relay_chain: String,
/// The id of the Parachain.
pub para_id: u32,
}
impl Extensions {
/// Try to get the extension from the given `ChainSpec`.
pub fn try_get(chain_spec: &dyn sc_service::ChainSpec) -> Option<&Self> {
sc_chain_spec::get_extension(chain_spec.extensions())
}
}
type AccountPublic = <Signature as Verify>::Signer;
/// Helper function to generate an account ID from seed
pub fn get_account_id_from_seed<TPublic: Public>(seed: &str) -> AccountId
where
AccountPublic: From<<TPublic::Pair as Pair>::Public>,
{
AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account()
}
/// We're using the same set of endowed accounts on all RialtoParachain chains (dev/local) to make
/// sure that all accounts, required for bridge to be functional (e.g. relayers fund account,
/// accounts used by relayers in our test deployments, accounts used for demonstration
/// purposes), are all available on these chains.
fn endowed_accounts() -> Vec<AccountId> {
let all_authorities = ALL_AUTHORITIES_ACCOUNTS.iter().flat_map(|x| {
[
get_account_id_from_seed::<sr25519::Public>(x),
get_account_id_from_seed::<sr25519::Public>(&format!("{x}//stash")),
]
});
vec![
// Sudo account
get_account_id_from_seed::<sr25519::Public>(SUDO_ACCOUNT),
// Regular (unused) accounts
get_account_id_from_seed::<sr25519::Public>("Charlie"),
get_account_id_from_seed::<sr25519::Public>("Dave"),
get_account_id_from_seed::<sr25519::Public>("Eve"),
get_account_id_from_seed::<sr25519::Public>("Ferdie"),
get_account_id_from_seed::<sr25519::Public>("Charlie//stash"),
get_account_id_from_seed::<sr25519::Public>("Dave//stash"),
get_account_id_from_seed::<sr25519::Public>("Eve//stash"),
get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"),
// Accounts, used by RialtoParachain<>Millau bridge
get_account_id_from_seed::<sr25519::Public>(MILLAU_MESSAGES_PALLET_OWNER),
get_account_id_from_seed::<sr25519::Public>("Millau.HeadersAndMessagesRelay1"),
get_account_id_from_seed::<sr25519::Public>("Millau.HeadersAndMessagesRelay2"),
get_account_id_from_seed::<sr25519::Public>("Millau.MessagesSender"),
]
.into_iter()
.chain(all_authorities)
.collect()
}
pub fn development_config(id: ParaId) -> ChainSpec {
// Give your base currency a unit name and decimal places
let mut properties = sc_chain_spec::Properties::new();
properties.insert("tokenSymbol".into(), "UNIT".into());
properties.insert("tokenDecimals".into(), 12.into());
ChainSpec::from_genesis(
// Name
"Development",
// ID
"dev",
ChainType::Local,
move || {
testnet_genesis(
get_account_id_from_seed::<sr25519::Public>(SUDO_ACCOUNT),
DEV_AUTHORITIES_ACCOUNTS.into_iter().map(get_from_seed::<AuraId>).collect(),
endowed_accounts(),
id,
)
},
vec![],
None,
None,
None,
None,
Extensions {
relay_chain: "rococo-local".into(), // You MUST set this to the correct network!
para_id: id.into(),
},
)
}
pub fn local_testnet_config(id: ParaId) -> ChainSpec {
// Give your base currency a unit name and decimal places
let mut properties = sc_chain_spec::Properties::new();
properties.insert("tokenSymbol".into(), "UNIT".into());
properties.insert("tokenDecimals".into(), 12.into());
ChainSpec::from_genesis(
// Name
"Local Testnet",
// ID
"local_testnet",
ChainType::Local,
move || {
testnet_genesis(
get_account_id_from_seed::<sr25519::Public>(SUDO_ACCOUNT),
LOCAL_AUTHORITIES_ACCOUNTS.into_iter().map(get_from_seed::<AuraId>).collect(),
endowed_accounts(),
id,
)
},
Vec::new(),
None,
None,
None,
None,
Extensions {
relay_chain: "rococo-local".into(), // You MUST set this to the correct network!
para_id: id.into(),
},
)
}
fn testnet_genesis(
root_key: AccountId,
initial_authorities: Vec<AuraId>,
endowed_accounts: Vec<AccountId>,
id: ParaId,
) -> rialto_parachain_runtime::RuntimeGenesisConfig {
rialto_parachain_runtime::RuntimeGenesisConfig {
system: rialto_parachain_runtime::SystemConfig {
code: rialto_parachain_runtime::WASM_BINARY
.expect("WASM binary was not build, please build it!")
.to_vec(),
..Default::default()
},
balances: rialto_parachain_runtime::BalancesConfig {
balances: endowed_accounts.iter().cloned().map(|k| (k, 1 << 60)).collect(),
},
sudo: rialto_parachain_runtime::SudoConfig { key: Some(root_key) },
parachain_info: rialto_parachain_runtime::ParachainInfoConfig {
parachain_id: id,
..Default::default()
},
aura: rialto_parachain_runtime::AuraConfig { authorities: initial_authorities },
aura_ext: Default::default(),
bridge_millau_messages: BridgeMillauMessagesConfig {
owner: Some(get_account_id_from_seed::<sr25519::Public>(MILLAU_MESSAGES_PALLET_OWNER)),
..Default::default()
},
}
}
@@ -1,109 +0,0 @@
// 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/>.
#![allow(clippy::large_enum_variant)]
use crate::chain_spec;
use clap::Parser;
use cumulus_client_cli::{ExportGenesisStateCommand, ExportGenesisWasmCommand};
use std::path::PathBuf;
/// Sub-commands supported by the collator.
#[derive(Debug, Parser)]
pub enum Subcommand {
/// Export the genesis state of the parachain.
#[clap(name = "export-genesis-state")]
ExportGenesisState(ExportGenesisStateCommand),
/// Export the genesis wasm of the parachain.
#[clap(name = "export-genesis-wasm")]
ExportGenesisWasm(ExportGenesisWasmCommand),
/// Build a chain specification.
BuildSpec(sc_cli::BuildSpecCmd),
/// Validate blocks.
CheckBlock(sc_cli::CheckBlockCmd),
/// Export blocks.
ExportBlocks(sc_cli::ExportBlocksCmd),
/// Export the state of a given block into a chain spec.
ExportState(sc_cli::ExportStateCmd),
/// Import blocks.
ImportBlocks(sc_cli::ImportBlocksCmd),
/// Remove the whole chain.
PurgeChain(cumulus_client_cli::PurgeChainCmd),
/// Revert the chain to a previous state.
Revert(sc_cli::RevertCmd),
/// The custom benchmark subcommand benchmarking runtime pallets.
#[clap(subcommand)]
Benchmark(frame_benchmarking_cli::BenchmarkCmd),
}
#[derive(Debug, Parser)]
#[clap(
propagate_version = true,
args_conflicts_with_subcommands = true,
subcommand_negates_reqs = true
)]
pub struct Cli {
#[clap(subcommand)]
pub subcommand: Option<Subcommand>,
#[clap(long)]
pub parachain_id: Option<u32>,
#[clap(flatten)]
pub run: cumulus_client_cli::RunCmd,
/// Relaychain arguments
#[clap(raw = true)]
pub relaychain_args: Vec<String>,
}
#[derive(Debug)]
pub struct RelayChainCli {
/// The actual relay chain CLI object.
pub base: polkadot_cli::RunCmd,
/// Optional chain id that should be passed to the relay chain.
pub chain_id: Option<String>,
/// The base path that should be used by the relay chain.
pub base_path: Option<PathBuf>,
}
impl RelayChainCli {
/// Parse the relay chain CLI parameters using the para chain `Configuration`.
pub fn new<'a>(
para_config: &sc_service::Configuration,
relay_chain_args: impl Iterator<Item = &'a String>,
) -> Self {
let extension = chain_spec::Extensions::try_get(&*para_config.chain_spec);
let chain_id = extension.map(|e| e.relay_chain.clone());
let base_path = para_config.base_path.path().join("rialto-bridge-node");
Self {
base_path: Some(base_path),
chain_id,
base: polkadot_cli::RunCmd::parse_from(relay_chain_args),
}
}
}
@@ -1,372 +0,0 @@
// 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/>.
use crate::{
chain_spec,
cli::{Cli, RelayChainCli, Subcommand},
service::new_partial,
};
use cumulus_primitives_core::ParaId;
use frame_benchmarking_cli::BenchmarkCmd;
use log::info;
use rialto_parachain_runtime::{Block, RuntimeApi};
use sc_cli::{
ChainSpec, CliConfiguration, DefaultConfigurationValues, ImportParams, KeystoreParams,
NetworkParams, Result, SharedParams, SubstrateCli,
};
use sc_service::config::{BasePath, PrometheusConfig};
use std::net::SocketAddr;
fn load_spec(
id: &str,
para_id: ParaId,
) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {
Ok(match id {
"dev" => Box::new(chain_spec::development_config(para_id)),
"" | "local" => Box::new(chain_spec::local_testnet_config(para_id)),
path => Box::new(chain_spec::ChainSpec::from_json_file(std::path::PathBuf::from(path))?),
})
}
impl SubstrateCli for Cli {
fn impl_name() -> String {
"Parachain Collator Template".into()
}
fn impl_version() -> String {
env!("SUBSTRATE_CLI_IMPL_VERSION").into()
}
fn description() -> String {
format!(
"Parachain Collator Template\n\nThe command-line arguments provided first will be \
passed to the parachain node, while the arguments provided after -- will be passed \
to the relaychain node.\n\n\
{} [parachain-args] -- [relaychain-args]",
Self::executable_name()
)
}
fn author() -> String {
env!("CARGO_PKG_AUTHORS").into()
}
fn support_url() -> String {
"https://github.com/substrate-developer-hub/substrate-parachain-template/issues/new".into()
}
fn copyright_start_year() -> i32 {
2017
}
fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {
load_spec(id, self.parachain_id.unwrap_or(2000).into())
}
}
impl SubstrateCli for RelayChainCli {
fn impl_name() -> String {
"Parachain Collator Template".into()
}
fn impl_version() -> String {
env!("SUBSTRATE_CLI_IMPL_VERSION").into()
}
fn description() -> String {
"Parachain Collator Template\n\nThe command-line arguments provided first will be \
passed to the parachain node, while the arguments provided after -- will be passed \
to the relaychain node.\n\n\
parachain-collator [parachain-args] -- [relaychain-args]"
.into()
}
fn author() -> String {
env!("CARGO_PKG_AUTHORS").into()
}
fn support_url() -> String {
"https://github.com/substrate-developer-hub/substrate-parachain-template/issues/new".into()
}
fn copyright_start_year() -> i32 {
2017
}
fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {
polkadot_cli::Cli::from_iter([RelayChainCli::executable_name()].iter()).load_spec(id)
}
}
macro_rules! construct_async_run {
(|$components:ident, $cli:ident, $cmd:ident, $config:ident| $( $code:tt )* ) => {{
let runner = $cli.create_runner($cmd)?;
runner.async_run(|$config| {
let $components = new_partial::<
RuntimeApi,
_
>(
&$config,
crate::service::parachain_build_import_queue,
)?;
let task_manager = $components.task_manager;
{ $( $code )* }.map(|v| (v, task_manager))
})
}}
}
/// Parse command line arguments into service configuration.
pub fn run() -> Result<()> {
let cli = Cli::from_args();
sp_core::crypto::set_default_ss58_version(sp_core::crypto::Ss58AddressFormat::custom(
rialto_parachain_runtime::SS58Prefix::get() as u16,
));
match &cli.subcommand {
Some(Subcommand::BuildSpec(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.sync_run(|config| cmd.run(config.chain_spec, config.network))
},
Some(Subcommand::CheckBlock(cmd)) => {
construct_async_run!(|components, cli, cmd, config| {
Ok(cmd.run(components.client, components.import_queue))
})
},
Some(Subcommand::ExportBlocks(cmd)) => {
construct_async_run!(|components, cli, cmd, config| Ok(
cmd.run(components.client, config.database)
))
},
Some(Subcommand::ExportState(cmd)) => {
construct_async_run!(|components, cli, cmd, config| Ok(
cmd.run(components.client, config.chain_spec)
))
},
Some(Subcommand::ImportBlocks(cmd)) => {
construct_async_run!(|components, cli, cmd, config| {
Ok(cmd.run(components.client, components.import_queue))
})
},
Some(Subcommand::PurgeChain(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.sync_run(|config| {
let polkadot_cli = RelayChainCli::new(
&config,
[RelayChainCli::executable_name()].iter().chain(cli.relaychain_args.iter()),
);
let polkadot_config = SubstrateCli::create_configuration(
&polkadot_cli,
&polkadot_cli,
config.tokio_handle.clone(),
)
.map_err(|err| format!("Relay chain argument error: {err}"))?;
cmd.run(config, polkadot_config)
})
},
Some(Subcommand::Revert(cmd)) => {
construct_async_run!(|components, cli, cmd, config| Ok(cmd.run(
components.client,
components.backend,
None
)))
},
Some(Subcommand::ExportGenesisState(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.sync_run(|config| {
let partials = new_partial::<RuntimeApi, _>(
&config,
crate::service::parachain_build_import_queue,
)?;
cmd.run(&*config.chain_spec, &*partials.client)
})
},
Some(Subcommand::ExportGenesisWasm(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.sync_run(|_config| {
let spec = cli.load_spec(&cmd.shared_params.chain.clone().unwrap_or_default())?;
cmd.run(&*spec)
})
},
Some(Subcommand::Benchmark(cmd)) => {
let runner = cli.create_runner(cmd)?;
match cmd {
BenchmarkCmd::Pallet(cmd) =>
if cfg!(feature = "runtime-benchmarks") {
runner.sync_run(|config| cmd.run::<Block, ()>(config))
} else {
println!(
"Benchmarking wasn't enabled when building the node. \
You can enable it with `--features runtime-benchmarks`."
);
Ok(())
},
_ => Err("Unsupported benchmarking subcommand".into()),
}
},
None => {
let runner = cli.create_runner(&cli.run.normalize())?;
let collator_options = cli.run.collator_options();
runner.run_node_until_exit(|config| async move {
let para_id =
chain_spec::Extensions::try_get(&*config.chain_spec).map(|e| e.para_id);
let polkadot_cli = RelayChainCli::new(
&config,
[RelayChainCli::executable_name()].iter().chain(cli.relaychain_args.iter()),
);
let id = ParaId::from(cli.parachain_id.or(para_id).expect("Missing ParaId"));
let polkadot_config = SubstrateCli::create_configuration(
&polkadot_cli,
&polkadot_cli,
config.tokio_handle.clone(),
)
.map_err(|err| format!("Relay chain argument error: {err}"))?;
info!("Parachain id: {:?}", id);
info!("Is collating: {}", if config.role.is_authority() { "yes" } else { "no" });
crate::service::start_node(config, polkadot_config, collator_options, id)
.await
.map(|r| r.0)
.map_err(Into::into)
})
},
}
}
impl DefaultConfigurationValues for RelayChainCli {
fn p2p_listen_port() -> u16 {
30334
}
fn rpc_listen_port() -> u16 {
9945
}
fn prometheus_listen_port() -> u16 {
9616
}
}
impl CliConfiguration<Self> for RelayChainCli {
fn shared_params(&self) -> &SharedParams {
self.base.base.shared_params()
}
fn import_params(&self) -> Option<&ImportParams> {
self.base.base.import_params()
}
fn network_params(&self) -> Option<&NetworkParams> {
self.base.base.network_params()
}
fn keystore_params(&self) -> Option<&KeystoreParams> {
self.base.base.keystore_params()
}
fn base_path(&self) -> Result<Option<BasePath>> {
Ok(self
.shared_params()
.base_path()?
.or_else(|| self.base_path.clone().map(Into::into)))
}
fn rpc_addr(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {
self.base.base.rpc_addr(default_listen_port)
}
fn prometheus_config(
&self,
default_listen_port: u16,
chain_spec: &Box<dyn ChainSpec>,
) -> Result<Option<PrometheusConfig>> {
self.base.base.prometheus_config(default_listen_port, chain_spec)
}
fn init<F>(
&self,
_support_url: &String,
_impl_version: &String,
_logger_hook: F,
_config: &sc_service::Configuration,
) -> Result<()>
where
F: FnOnce(&mut sc_cli::LoggerBuilder, &sc_service::Configuration),
{
unreachable!("PolkadotCli is never initialized; qed");
}
fn chain_id(&self, is_dev: bool) -> Result<String> {
let chain_id = self.base.base.chain_id(is_dev)?;
Ok(if chain_id.is_empty() { self.chain_id.clone().unwrap_or_default() } else { chain_id })
}
fn role(&self, is_dev: bool) -> Result<sc_service::Role> {
self.base.base.role(is_dev)
}
fn transaction_pool(&self, is_dev: bool) -> Result<sc_service::config::TransactionPoolOptions> {
self.base.base.transaction_pool(is_dev)
}
fn rpc_methods(&self) -> Result<sc_service::config::RpcMethods> {
self.base.base.rpc_methods()
}
fn rpc_max_connections(&self) -> Result<u32> {
self.base.base.rpc_max_connections()
}
fn rpc_cors(&self, is_dev: bool) -> Result<Option<Vec<String>>> {
self.base.base.rpc_cors(is_dev)
}
fn default_heap_pages(&self) -> Result<Option<u64>> {
self.base.base.default_heap_pages()
}
fn force_authoring(&self) -> Result<bool> {
self.base.base.force_authoring()
}
fn disable_grandpa(&self) -> Result<bool> {
self.base.base.disable_grandpa()
}
fn max_runtime_instances(&self) -> Result<Option<usize>> {
self.base.base.max_runtime_instances()
}
fn announce_block(&self) -> Result<bool> {
self.base.base.announce_block()
}
fn telemetry_endpoints(
&self,
chain_spec: &Box<dyn ChainSpec>,
) -> Result<Option<sc_telemetry::TelemetryEndpoints>> {
self.base.base.telemetry_endpoints(chain_spec)
}
}
@@ -1,19 +0,0 @@
// 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/>.
pub mod chain_spec;
#[allow(deprecated)]
pub mod service;
@@ -1,30 +0,0 @@
// 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/>.
//! Substrate Parachain Node Template CLI
#![warn(missing_docs)]
mod chain_spec;
#[macro_use]
#[allow(deprecated)]
mod service;
mod cli;
mod command;
fn main() -> sc_cli::Result<()> {
command::run()
}
@@ -1,505 +0,0 @@
// 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/>.
//! Rialto parachain node service.
//!
//! The code is mostly copy of `polkadot-parachains/src/service.rs` file from Cumulus
//! repository with some parts removed. We have added two RPC extensions to the original
//! service: `pallet_transaction_payment_rpc::TransactionPaymentApi` and
//! `substrate_frame_rpc_system::SystemApi`.
// std
use std::{sync::Arc, time::Duration};
// Local Runtime Types
use rialto_parachain_runtime::RuntimeApi;
// Cumulus Imports
use cumulus_client_cli::CollatorOptions;
use cumulus_client_consensus_aura::{AuraConsensus, BuildAuraConsensusParams, SlotProportion};
use cumulus_client_consensus_common::{
ParachainBlockImport as TParachainBlockImport, ParachainConsensus,
};
use cumulus_client_network::RequireSecondedInBlockAnnounce;
use cumulus_client_service::{
prepare_node_config, start_collator, start_full_node, StartCollatorParams, StartFullNodeParams,
};
use cumulus_primitives_core::ParaId;
use cumulus_relay_chain_interface::RelayChainInterface;
use sc_consensus::ImportQueue;
// Substrate Imports
use sc_executor::{
HeapAllocStrategy, NativeElseWasmExecutor, NativeExecutionDispatch, WasmExecutor,
DEFAULT_HEAP_ALLOC_STRATEGY,
};
use sc_network::{config::FullNetworkConfiguration, NetworkBlock};
use sc_network_sync::SyncingService;
use sc_service::{Configuration, PartialComponents, TFullBackend, TFullClient, TaskManager};
use sc_telemetry::{Telemetry, TelemetryHandle, TelemetryWorker, TelemetryWorkerHandle};
use sp_api::ConstructRuntimeApi;
use sp_keystore::KeystorePtr;
use sp_runtime::traits::BlakeTwo256;
use substrate_prometheus_endpoint::Registry;
// Runtime type overrides
type BlockNumber = u32;
type Header = sp_runtime::generic::Header<BlockNumber, sp_runtime::traits::BlakeTwo256>;
pub type Block = sp_runtime::generic::Block<Header, sp_runtime::OpaqueExtrinsic>;
type ParachainClient<RuntimeApi> =
TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<ParachainRuntimeExecutor>>;
type ParachainBackend = TFullBackend<Block>;
type ParachainBlockImport<RuntimeApi> =
TParachainBlockImport<Block, Arc<ParachainClient<RuntimeApi>>, ParachainBackend>;
pub type ParachainRuntimeExecutor = ExecutorDispatch;
// Our native executor instance.
pub struct ExecutorDispatch;
impl NativeExecutionDispatch for ExecutorDispatch {
type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;
fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {
rialto_parachain_runtime::api::dispatch(method, data)
}
fn native_version() -> sc_executor::NativeVersion {
rialto_parachain_runtime::native_version()
}
}
/// Starts a `ServiceBuilder` for a full service.
///
/// Use this macro if you don't actually need the full service, but just the builder in order to
/// be able to perform chain operations.
#[allow(clippy::type_complexity)]
pub fn new_partial<RuntimeApi, BIQ>(
config: &Configuration,
build_import_queue: BIQ,
) -> Result<
PartialComponents<
ParachainClient<RuntimeApi>,
ParachainBackend,
(),
sc_consensus::DefaultImportQueue<Block>,
sc_transaction_pool::FullPool<Block, ParachainClient<RuntimeApi>>,
(ParachainBlockImport<RuntimeApi>, Option<Telemetry>, Option<TelemetryWorkerHandle>),
>,
sc_service::Error,
>
where
RuntimeApi: ConstructRuntimeApi<Block, ParachainClient<RuntimeApi>> + Send + Sync + 'static,
RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>
+ sp_api::Metadata<Block>
+ sp_session::SessionKeys<Block>
+ sp_api::ApiExt<Block>
+ sp_offchain::OffchainWorkerApi<Block>
+ sp_block_builder::BlockBuilder<Block>,
sc_client_api::StateBackendFor<ParachainBackend, Block>: sp_api::StateBackend<BlakeTwo256>,
BIQ: FnOnce(
Arc<ParachainClient<RuntimeApi>>,
ParachainBlockImport<RuntimeApi>,
&Configuration,
Option<TelemetryHandle>,
&TaskManager,
) -> Result<sc_consensus::DefaultImportQueue<Block>, sc_service::Error>,
{
let telemetry = config
.telemetry_endpoints
.clone()
.filter(|x| !x.is_empty())
.map(|endpoints| -> Result<_, sc_telemetry::Error> {
let worker = TelemetryWorker::new(16)?;
let telemetry = worker.handle().new_telemetry(endpoints);
Ok((worker, telemetry))
})
.transpose()?;
let heap_pages = config
.default_heap_pages
.map_or(DEFAULT_HEAP_ALLOC_STRATEGY, |h| HeapAllocStrategy::Static { extra_pages: h as _ });
let executor =
sc_executor::NativeElseWasmExecutor::<ParachainRuntimeExecutor>::new_with_wasm_executor(
WasmExecutor::builder()
.with_execution_method(config.wasm_method)
.with_onchain_heap_alloc_strategy(heap_pages)
.with_offchain_heap_alloc_strategy(heap_pages)
.with_max_runtime_instances(config.max_runtime_instances)
.with_runtime_cache_size(config.runtime_cache_size)
.build(),
);
let (client, backend, keystore_container, task_manager) =
sc_service::new_full_parts::<Block, RuntimeApi, _>(
config,
telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),
executor,
)?;
let client = Arc::new(client);
let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());
let telemetry = telemetry.map(|(worker, telemetry)| {
task_manager.spawn_handle().spawn("telemetry", None, worker.run());
telemetry
});
let transaction_pool = sc_transaction_pool::BasicPool::new_full(
config.transaction_pool.clone(),
config.role.is_authority().into(),
config.prometheus_registry(),
task_manager.spawn_essential_handle(),
client.clone(),
);
let block_import = ParachainBlockImport::new(client.clone(), backend.clone());
let import_queue = build_import_queue(
client.clone(),
block_import.clone(),
config,
telemetry.as_ref().map(|telemetry| telemetry.handle()),
&task_manager,
)?;
let params = PartialComponents {
backend,
client,
import_queue,
keystore_container,
task_manager,
transaction_pool,
select_chain: (),
other: (block_import, telemetry, telemetry_worker_handle),
};
Ok(params)
}
/// Start a node with the given parachain `Configuration` and relay chain `Configuration`.
///
/// This is the actual implementation that is abstract over the executor and the runtime api.
#[sc_tracing::logging::prefix_logs_with("Parachain")]
async fn start_node_impl<RuntimeApi, RB, BIQ, BIC>(
parachain_config: Configuration,
polkadot_config: Configuration,
collator_options: CollatorOptions,
id: ParaId,
rpc_ext_builder: RB,
build_import_queue: BIQ,
build_consensus: BIC,
) -> sc_service::error::Result<(TaskManager, Arc<ParachainClient<RuntimeApi>>)>
where
RuntimeApi: ConstructRuntimeApi<Block, ParachainClient<RuntimeApi>> + Send + Sync + 'static,
RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>
+ sp_api::Metadata<Block>
+ sp_session::SessionKeys<Block>
+ sp_api::ApiExt<Block>
+ sp_offchain::OffchainWorkerApi<Block>
+ sp_block_builder::BlockBuilder<Block>
+ cumulus_primitives_core::CollectCollationInfo<Block>,
sc_client_api::StateBackendFor<ParachainBackend, Block>: sp_api::StateBackend<BlakeTwo256>,
RB: Fn(
sc_rpc_api::DenyUnsafe,
Arc<ParachainClient<RuntimeApi>>,
Arc<sc_transaction_pool::FullPool<Block, ParachainClient<RuntimeApi>>>,
) -> Result<jsonrpsee::RpcModule<()>, sc_service::Error>
+ Send
+ Clone
+ 'static,
BIQ: FnOnce(
Arc<ParachainClient<RuntimeApi>>,
ParachainBlockImport<RuntimeApi>,
&Configuration,
Option<TelemetryHandle>,
&TaskManager,
) -> Result<sc_consensus::DefaultImportQueue<Block>, sc_service::Error>,
BIC: FnOnce(
Arc<ParachainClient<RuntimeApi>>,
ParachainBlockImport<RuntimeApi>,
Option<&Registry>,
Option<TelemetryHandle>,
&TaskManager,
Arc<dyn RelayChainInterface>,
Arc<sc_transaction_pool::FullPool<Block, ParachainClient<RuntimeApi>>>,
Arc<SyncingService<Block>>,
KeystorePtr,
bool,
) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>,
{
let parachain_config = prepare_node_config(parachain_config);
let params = new_partial::<RuntimeApi, BIQ>(&parachain_config, build_import_queue)?;
let (block_import, mut telemetry, telemetry_worker_handle) = params.other;
let mut task_manager = params.task_manager;
let (relay_chain_interface, collator_key) =
cumulus_client_service::build_relay_chain_interface(
polkadot_config,
&parachain_config,
telemetry_worker_handle,
&mut task_manager,
collator_options,
None,
)
.await
.map_err(|e| sc_service::Error::Application(Box::new(e) as Box<_>))?;
let client = params.client.clone();
let backend = params.backend.clone();
let block_announce_validator =
RequireSecondedInBlockAnnounce::new(relay_chain_interface.clone(), id);
let force_authoring = parachain_config.force_authoring;
let validator = parachain_config.role.is_authority();
let prometheus_registry = parachain_config.prometheus_registry().cloned();
let transaction_pool = params.transaction_pool.clone();
let import_queue_service = params.import_queue.service();
let net_config = FullNetworkConfiguration::new(&parachain_config.network);
let (network, system_rpc_tx, tx_handler_controller, start_network, sync_service) =
sc_service::build_network(sc_service::BuildNetworkParams {
config: &parachain_config,
net_config,
client: client.clone(),
transaction_pool: transaction_pool.clone(),
spawn_handle: task_manager.spawn_handle(),
import_queue: params.import_queue,
block_announce_validator_builder: Some(Box::new(|_| {
Box::new(block_announce_validator)
})),
warp_sync_params: None,
block_relay: None,
})?;
let rpc_client = client.clone();
let rpc_transaction_pool = transaction_pool.clone();
let rpc_extensions_builder = Box::new(move |deny_unsafe, _| {
rpc_ext_builder(deny_unsafe, rpc_client.clone(), rpc_transaction_pool.clone())
});
sc_service::spawn_tasks(sc_service::SpawnTasksParams {
rpc_builder: rpc_extensions_builder.clone(),
client: client.clone(),
transaction_pool: transaction_pool.clone(),
task_manager: &mut task_manager,
config: parachain_config,
keystore: params.keystore_container.keystore(),
backend: backend.clone(),
network: network.clone(),
sync_service: sync_service.clone(),
system_rpc_tx,
tx_handler_controller,
telemetry: telemetry.as_mut(),
})?;
let announce_block = {
let sync_service = sync_service.clone();
Arc::new(move |hash, data| sync_service.announce_block(hash, data))
};
let relay_chain_slot_duration = Duration::from_secs(6);
let overseer_handle = relay_chain_interface
.overseer_handle()
.map_err(|e| sc_service::Error::Application(Box::new(e)))?;
if validator {
let parachain_consensus = build_consensus(
client.clone(),
block_import,
prometheus_registry.as_ref(),
telemetry.as_ref().map(|t| t.handle()),
&task_manager,
relay_chain_interface.clone(),
transaction_pool,
sync_service.clone(),
params.keystore_container.keystore(),
force_authoring,
)?;
let spawner = task_manager.spawn_handle();
let params = StartCollatorParams {
para_id: id,
block_status: client.clone(),
announce_block,
client: client.clone(),
task_manager: &mut task_manager,
relay_chain_interface,
spawner,
parachain_consensus,
import_queue: import_queue_service,
collator_key: collator_key.expect("Command line arguments do not allow this. qed"),
relay_chain_slot_duration,
recovery_handle: Box::new(overseer_handle),
sync_service,
};
start_collator(params).await?;
} else {
let params = StartFullNodeParams {
client: client.clone(),
announce_block,
task_manager: &mut task_manager,
para_id: id,
relay_chain_interface,
relay_chain_slot_duration,
import_queue: import_queue_service,
recovery_handle: Box::new(overseer_handle),
sync_service,
};
start_full_node(params)?;
}
start_network.start_network();
Ok((task_manager, client))
}
/// Build the import queue for the the parachain runtime.
#[allow(clippy::type_complexity)]
pub fn parachain_build_import_queue(
client: Arc<ParachainClient<RuntimeApi>>,
block_import: ParachainBlockImport<RuntimeApi>,
config: &Configuration,
telemetry: Option<TelemetryHandle>,
task_manager: &TaskManager,
) -> Result<sc_consensus::DefaultImportQueue<Block>, sc_service::Error> {
let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;
cumulus_client_consensus_aura::import_queue::<
sp_consensus_aura::sr25519::AuthorityPair,
_,
_,
_,
_,
_,
>(cumulus_client_consensus_aura::ImportQueueParams {
block_import,
client,
create_inherent_data_providers: move |_, _| async move {
let timestamp = sp_timestamp::InherentDataProvider::from_system_time();
let slot =
sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(
*timestamp,
slot_duration,
);
Ok((slot, timestamp))
},
registry: config.prometheus_registry(),
spawner: &task_manager.spawn_essential_handle(),
telemetry,
})
.map_err(Into::into)
}
/// Start a normal parachain node.
pub async fn start_node(
parachain_config: Configuration,
polkadot_config: Configuration,
collator_options: CollatorOptions,
id: ParaId,
) -> sc_service::error::Result<(TaskManager, Arc<ParachainClient<RuntimeApi>>)> {
start_node_impl::<RuntimeApi, _, _, _>(
parachain_config,
polkadot_config,
collator_options,
id,
|_deny_unsafe, client, pool| {
use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer};
use sc_rpc::DenyUnsafe;
use substrate_frame_rpc_system::{System, SystemApiServer};
let mut io = jsonrpsee::RpcModule::new(());
let map_err = |e| sc_service::Error::Other(format!("{e}"));
io.merge(System::new(client.clone(), pool, DenyUnsafe::No).into_rpc())
.map_err(map_err)?;
io.merge(TransactionPayment::new(client).into_rpc()).map_err(map_err)?;
Ok(io)
},
parachain_build_import_queue,
|client,
block_import,
prometheus_registry,
telemetry,
task_manager,
relay_chain_interface,
transaction_pool,
sync_oracle,
keystore,
force_authoring| {
let client2 = client.clone();
let block_import2 = block_import;
let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;
let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(
task_manager.spawn_handle(),
client,
transaction_pool,
prometheus_registry,
telemetry.clone(),
);
Ok(AuraConsensus::build::<sp_consensus_aura::sr25519::AuthorityPair, _, _, _, _, _, _>(
BuildAuraConsensusParams {
proposer_factory,
create_inherent_data_providers: move |_, (relay_parent, validation_data)| {
let relay_chain_interface = relay_chain_interface.clone();
async move {
let parachain_inherent =
cumulus_primitives_parachain_inherent::ParachainInherentData::create_at(
relay_parent,
&relay_chain_interface,
&validation_data,
id,
).await;
let time = sp_timestamp::InherentDataProvider::from_system_time();
let slot = sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(
*time,
slot_duration,
);
let parachain_inherent = parachain_inherent.ok_or_else(|| {
Box::<dyn std::error::Error + Send + Sync>::from(
"Failed to create parachain inherent",
)
})?;
Ok((slot, time, parachain_inherent))
}
},
block_import: block_import2,
para_client: client2,
backoff_authoring_blocks: Option::<()>::None,
sync_oracle,
keystore,
force_authoring,
slot_duration,
// We got around 1000ms for proposing
block_proposal_slot_portion: SlotProportion::new(1f32 / 12f32),
telemetry,
max_block_proposal_slot_portion: None,
},
))
},
)
.await
}
@@ -1,146 +0,0 @@
[package]
name = "rialto-parachain-runtime"
version = "0.1.0"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2021"
repository = "https://github.com/paritytech/parity-bridges-common/"
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
[build-dependencies]
substrate-wasm-builder = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
[dependencies]
codec = { package = 'parity-scale-codec', version = '3.1.5', default-features = false, features = ['derive']}
hex-literal = "0.4"
scale-info = { version = "2.10.0", default-features = false, features = ["derive"] }
# Bridge depedencies
bp-header-chain = { path = "../../../primitives/header-chain", default-features = false }
bp-messages = { path = "../../../primitives/messages", default-features = false }
bp-millau = { path = "../../../primitives/chain-millau", default-features = false }
bp-polkadot-core = { path = "../../../primitives/polkadot-core", default-features = false }
bp-relayers = { path = "../../../primitives/relayers", default-features = false }
bp-runtime = { path = "../../../primitives/runtime", default-features = false }
bp-rialto-parachain = { path = "../../../primitives/chain-rialto-parachain", default-features = false }
bridge-runtime-common = { path = "../../runtime-common", default-features = false }
pallet-bridge-grandpa = { path = "../../../modules/grandpa", default-features = false }
pallet-bridge-messages = { path = "../../../modules/messages", default-features = false }
pallet-bridge-relayers = { path = "../../../modules/relayers", default-features = false }
# Substrate Dependencies
## Substrate Primitive Dependencies
sp-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-block-builder = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-core = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-consensus-aura = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-inherents = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-io = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-offchain = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-session = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-std = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-transaction-pool = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-version = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
## Substrate FRAME Dependencies
frame-executive = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
frame-benchmarking = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false, optional = true }
frame-support = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
frame-system = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
frame-system-benchmarking = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false, optional = true }
frame-system-rpc-runtime-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
## Substrate Pallet Dependencies
pallet-aura = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
pallet-balances = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
pallet-sudo = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
pallet-timestamp = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
pallet-transaction-payment = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
pallet-transaction-payment-rpc-runtime-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
# Cumulus Dependencies
cumulus-pallet-aura-ext = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
cumulus-pallet-parachain-system = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
cumulus-pallet-dmp-queue = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
cumulus-pallet-xcm = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
cumulus-pallet-xcmp-queue = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
cumulus-primitives-core = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
cumulus-primitives-timestamp = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
parachain-info = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
# Polkadot Dependencies
polkadot-parachain-primitives = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
xcm = { package = "staging-xcm", git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
xcm-builder = { package = "staging-xcm-builder", git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
xcm-executor = { package = "staging-xcm-executor", git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
pallet-xcm = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
[dev-dependencies]
bridge-runtime-common = { path = "../../runtime-common", features = ["integrity-test"] }
static_assertions = "1.1"
[features]
default = [ 'std' ]
runtime-benchmarks = [
'bridge-runtime-common/runtime-benchmarks',
'frame-benchmarking',
'frame-support/runtime-benchmarks',
'frame-system-benchmarking/runtime-benchmarks',
'frame-system/runtime-benchmarks',
'pallet-balances/runtime-benchmarks',
'pallet-bridge-grandpa/runtime-benchmarks',
'pallet-bridge-messages/runtime-benchmarks',
'pallet-bridge-relayers/runtime-benchmarks',
'pallet-timestamp/runtime-benchmarks',
'pallet-xcm/runtime-benchmarks',
'sp-runtime/runtime-benchmarks',
'xcm-builder/runtime-benchmarks',
]
std = [
"bp-messages/std",
"bp-millau/std",
"bp-relayers/std",
"bp-rialto-parachain/std",
"bp-runtime/std",
"bridge-runtime-common/std",
"codec/std",
"cumulus-pallet-aura-ext/std",
"cumulus-pallet-parachain-system/std",
"cumulus-pallet-xcm/std",
"cumulus-pallet-xcmp-queue/std",
"cumulus-primitives-core/std",
"cumulus-primitives-timestamp/std",
"frame-executive/std",
"frame-support/std",
"frame-system-rpc-runtime-api/std",
"frame-system/std",
"pallet-aura/std",
"pallet-balances/std",
"pallet-bridge-grandpa/std",
"pallet-bridge-messages/std",
"pallet-bridge-relayers/std",
"pallet-sudo/std",
"pallet-timestamp/std",
"pallet-transaction-payment-rpc-runtime-api/std",
"pallet-transaction-payment/std",
"pallet-xcm/std",
"parachain-info/std",
"polkadot-parachain-primitives/std",
"scale-info/std",
"sp-api/std",
"sp-block-builder/std",
"sp-consensus-aura/std",
"sp-core/std",
"sp-inherents/std",
"sp-io/std",
"sp-offchain/std",
"sp-runtime/std",
"sp-session/std",
"sp-std/std",
"sp-transaction-pool/std",
"sp-version/std",
"xcm-builder/std",
"xcm-executor/std",
"xcm/std",
]
@@ -1,26 +0,0 @@
// 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 substrate_wasm_builder::WasmBuilder;
fn main() {
WasmBuilder::new()
.with_current_project()
.export_heap_base()
.import_memory()
.disable_runtime_version_section_check()
.build()
}
@@ -1,975 +0,0 @@
// 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/>.
//! The Rialto parachain runtime. This can be compiled with `#[no_std]`, ready for Wasm.
//!
//! Originally a copy of runtime from <https://github.com/substrate-developer-hub/substrate-parachain-template>.
#![cfg_attr(not(feature = "std"), no_std)]
// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.
#![recursion_limit = "256"]
// Make the WASM binary available.
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
use bridge_runtime_common::generate_bridge_reject_obsolete_headers_and_messages;
use codec::{Decode, Encode};
use cumulus_pallet_parachain_system::AnyRelayNumber;
use scale_info::TypeInfo;
use sp_api::impl_runtime_apis;
use sp_core::{crypto::KeyTypeId, OpaqueMetadata};
use sp_runtime::{
create_runtime_str, generic, impl_opaque_keys,
traits::{AccountIdLookup, Block as BlockT, DispatchInfoOf, SignedExtension},
transaction_validity::{TransactionSource, TransactionValidity, TransactionValidityError},
ApplyExtrinsicResult,
};
use sp_std::prelude::*;
#[cfg(feature = "std")]
use sp_version::NativeVersion;
use sp_version::RuntimeVersion;
// A few exports that help ease life for downstream crates.
use bp_runtime::HeaderId;
pub use frame_support::{
construct_runtime,
dispatch::DispatchClass,
match_types, parameter_types,
traits::{ConstBool, ConstU32, Everything, IsInVec, Nothing, Randomness},
weights::{
constants::{
BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_REF_TIME_PER_SECOND,
},
IdentityFee, Weight,
},
StorageValue,
};
pub use frame_system::{Call as SystemCall, EnsureRoot};
pub use pallet_balances::Call as BalancesCall;
pub use pallet_sudo::Call as SudoCall;
pub use pallet_timestamp::Call as TimestampCall;
pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;
#[cfg(any(feature = "std", test))]
pub use sp_runtime::BuildStorage;
pub use sp_runtime::{MultiAddress, Perbill, Permill};
pub use bp_rialto_parachain::{
AccountId, Balance, BlockLength, BlockNumber, BlockWeights, Hash, Hasher as Hashing, Header,
Nonce, Signature, MAXIMUM_BLOCK_WEIGHT,
};
pub use pallet_bridge_grandpa::Call as BridgeGrandpaCall;
pub use pallet_bridge_messages::Call as MessagesCall;
pub use pallet_xcm::Call as XcmCall;
// Polkadot & XCM imports
use bridge_runtime_common::CustomNetworkId;
use pallet_xcm::XcmPassthrough;
use polkadot_parachain_primitives::primitives::Sibling;
use xcm::latest::prelude::*;
use xcm_builder::{
AccountId32Aliases, CurrencyAdapter, EnsureXcmOrigin, FixedWeightBounds, IsConcrete,
NativeAsset, ParentAsSuperuser, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative,
SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32,
SovereignSignedViaLocation, TakeWeightCredit, UsingComponents,
};
use xcm_executor::{Config, XcmExecutor};
pub mod millau_messages;
// generate signed extension that rejects obsolete bridge transactions
generate_bridge_reject_obsolete_headers_and_messages! {
RuntimeCall, AccountId,
// Grandpa
BridgeMillauGrandpa,
// Messages
BridgeMillauMessages
}
/// Dummy signed extension that does nothing.
///
/// We're using it to have the same set of signed extensions on all parachains with bridge pallets
/// deployed (bridge hubs and rialto parachain).
#[derive(Encode, Decode, Debug, PartialEq, Eq, Clone, TypeInfo)]
pub struct DummyBridgeRefundMillauMessages;
impl SignedExtension for DummyBridgeRefundMillauMessages {
const IDENTIFIER: &'static str = "DummyBridgeRefundMillauMessages";
type AccountId = AccountId;
type Call = RuntimeCall;
type AdditionalSigned = ();
type Pre = ();
fn additional_signed(&self) -> Result<Self::AdditionalSigned, TransactionValidityError> {
Ok(())
}
fn pre_dispatch(
self,
_who: &Self::AccountId,
_call: &Self::Call,
_info: &DispatchInfoOf<Self::Call>,
_len: usize,
) -> Result<Self::Pre, TransactionValidityError> {
Ok(())
}
}
/// The address format for describing accounts.
pub type Address = MultiAddress<AccountId, ()>;
/// Block type as expected by this runtime.
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
/// A Block signed with a Justification
pub type SignedBlock = generic::SignedBlock<Block>;
/// BlockId type as expected by this runtime.
pub type BlockId = generic::BlockId<Block>;
/// The SignedExtension to the basic transaction logic.
pub type SignedExtra = (
frame_system::CheckNonZeroSender<Runtime>,
frame_system::CheckSpecVersion<Runtime>,
frame_system::CheckTxVersion<Runtime>,
frame_system::CheckGenesis<Runtime>,
frame_system::CheckEra<Runtime>,
frame_system::CheckNonce<Runtime>,
frame_system::CheckWeight<Runtime>,
pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
BridgeRejectObsoleteHeadersAndMessages,
DummyBridgeRefundMillauMessages,
);
/// Unchecked extrinsic type as expected by this runtime.
pub type UncheckedExtrinsic =
generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
/// Extrinsic type that has already been checked.
pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, RuntimeCall, SignedExtra>;
/// Executive: handles dispatch to the various modules.
pub type Executive = frame_executive::Executive<
Runtime,
Block,
frame_system::ChainContext<Runtime>,
Runtime,
AllPalletsWithSystem,
>;
impl_opaque_keys! {
pub struct SessionKeys {
pub aura: Aura,
}
}
/// This runtime version.
#[sp_version::runtime_version]
pub const VERSION: RuntimeVersion = RuntimeVersion {
spec_name: create_runtime_str!("template-parachain"),
impl_name: create_runtime_str!("template-parachain"),
authoring_version: 1,
spec_version: 1,
impl_version: 0,
apis: RUNTIME_API_VERSIONS,
transaction_version: 1,
state_version: 0,
};
/// This determines the average expected block time that we are targeting.
/// Blocks will be produced at a minimum duration defined by `SLOT_DURATION`.
/// `SLOT_DURATION` is picked up by `pallet_timestamp` which is in turn picked
/// up by `pallet_aura` to implement `fn slot_duration()`.
///
/// Change this to adjust the block time.
pub const MILLISECS_PER_BLOCK: u64 = 12000;
pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;
pub const EPOCH_DURATION_IN_BLOCKS: u32 = 10 * MINUTES;
// Time is measured by number of blocks.
pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);
pub const HOURS: BlockNumber = MINUTES * 60;
pub const DAYS: BlockNumber = HOURS * 24;
// Unit = the base number of indivisible units for balances
pub const UNIT: Balance = 1_000_000_000_000;
pub const MILLIUNIT: Balance = 1_000_000_000;
pub const MICROUNIT: Balance = 1_000_000;
// 1 in 4 blocks (on average, not counting collisions) will be primary babe blocks.
pub const PRIMARY_PROBABILITY: (u64, u64) = (1, 4);
/// The version information used to identify this runtime when compiled natively.
#[cfg(feature = "std")]
pub fn native_version() -> NativeVersion {
NativeVersion { runtime_version: VERSION, can_author_with: Default::default() }
}
parameter_types! {
pub const BlockHashCount: BlockNumber = 250;
pub const Version: RuntimeVersion = VERSION;
pub const SS58Prefix: u8 = 48;
}
// Configure FRAME pallets to include in runtime.
impl frame_system::Config for Runtime {
/// The identifier used to distinguish between accounts.
type AccountId = AccountId;
/// The aggregated dispatch type that is available for extrinsics.
type RuntimeCall = RuntimeCall;
/// The lookup mechanism to get account ID from whatever is passed in dispatchers.
type Lookup = AccountIdLookup<AccountId, ()>;
/// The index type for storing how many extrinsics an account has signed.
type Nonce = Nonce;
/// The type for hashing blocks and tries.
type Hash = Hash;
/// The hashing algorithm used.
type Hashing = Hashing;
/// The header type.
type Block = Block;
/// The ubiquitous event type.
type RuntimeEvent = RuntimeEvent;
/// The ubiquitous origin type.
type RuntimeOrigin = RuntimeOrigin;
/// Maximum number of block number to block hash mappings to keep (oldest pruned first).
type BlockHashCount = BlockHashCount;
/// Runtime version.
type Version = Version;
/// Converts a module to an index of this module in the runtime.
type PalletInfo = PalletInfo;
type AccountData = pallet_balances::AccountData<Balance>;
/// What to do if a new account is created.
type OnNewAccount = ();
/// What to do if an account is fully reaped from the system.
type OnKilledAccount = ();
/// The weight of database operations that the runtime can invoke.
type DbWeight = ();
/// The basic call filter to use in dispatchable.
type BaseCallFilter = Everything;
/// Weight information for the extrinsics of this pallet.
type SystemWeightInfo = ();
/// Block & extrinsics weights: base values and limits.
type BlockWeights = BlockWeights;
/// The maximum length of a block (in bytes).
type BlockLength = BlockLength;
/// This is used as an identifier of the chain. 42 is the generic substrate prefix.
type SS58Prefix = SS58Prefix;
/// The action to take on a Runtime Upgrade
type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;
type MaxConsumers = frame_support::traits::ConstU32<16>;
}
parameter_types! {
pub const MinimumPeriod: u64 = SLOT_DURATION / 2;
}
impl pallet_timestamp::Config for Runtime {
/// A timestamp: milliseconds since the Unix epoch.
type Moment = u64;
type OnTimestampSet = ();
type MinimumPeriod = MinimumPeriod;
type WeightInfo = ();
}
parameter_types! {
pub const ExistentialDeposit: u128 = MILLIUNIT;
pub const TransferFee: u128 = MILLIUNIT;
pub const CreationFee: u128 = MILLIUNIT;
pub const TransactionByteFee: u128 = MICROUNIT;
pub const OperationalFeeMultiplier: u8 = 5;
}
impl pallet_balances::Config for Runtime {
/// The type for recording an account's balance.
type Balance = Balance;
/// The ubiquitous event type.
type RuntimeEvent = RuntimeEvent;
type DustRemoval = ();
type ExistentialDeposit = ExistentialDeposit;
type AccountStore = System;
type WeightInfo = pallet_balances::weights::SubstrateWeight<Runtime>;
type MaxLocks = ConstU32<50>;
type MaxReserves = ConstU32<50>;
type ReserveIdentifier = [u8; 8];
type RuntimeHoldReason = RuntimeHoldReason;
type FreezeIdentifier = ();
type MaxHolds = ConstU32<0>;
type MaxFreezes = ConstU32<0>;
}
impl pallet_transaction_payment::Config for Runtime {
type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, ()>;
type OperationalFeeMultiplier = OperationalFeeMultiplier;
type WeightToFee = IdentityFee<Balance>;
type LengthToFee = IdentityFee<Balance>;
type FeeMultiplierUpdate = ();
type RuntimeEvent = RuntimeEvent;
}
impl pallet_sudo::Config for Runtime {
type RuntimeCall = RuntimeCall;
type RuntimeEvent = RuntimeEvent;
type WeightInfo = pallet_sudo::weights::SubstrateWeight<Runtime>;
}
parameter_types! {
pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
}
impl cumulus_pallet_parachain_system::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type OnSystemEvent = ();
type SelfParaId = parachain_info::Pallet<Runtime>;
type OutboundXcmpMessageSource = XcmpQueue;
type DmpMessageHandler = DmpQueue;
type ReservedDmpWeight = ReservedDmpWeight;
type XcmpMessageHandler = XcmpQueue;
type ReservedXcmpWeight = ReservedXcmpWeight;
type CheckAssociatedRelayNumber = AnyRelayNumber;
}
impl parachain_info::Config for Runtime {}
impl cumulus_pallet_aura_ext::Config for Runtime {}
parameter_types! {
pub const RelayLocation: MultiLocation = MultiLocation::parent();
pub const RelayNetwork: NetworkId = CustomNetworkId::Rialto.as_network_id();
pub RelayOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();
pub UniversalLocation: InteriorMultiLocation = ThisNetwork::get().into();
/// The Millau network ID.
pub const MillauNetwork: NetworkId = CustomNetworkId::Millau.as_network_id();
/// The RialtoParachain network ID.
pub const ThisNetwork: NetworkId = CustomNetworkId::RialtoParachain.as_network_id();
}
/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used
/// when determining ownership of accounts for asset transacting and when attempting to use XCM
/// `Transact` in order to determine the dispatch Origin.
pub type LocationToAccountId = (
// The parent (Relay-chain) origin converts to the default `AccountId`.
ParentIsPreset<AccountId>,
// Sibling parachain origins convert to AccountId via the `ParaId::into`.
SiblingParachainConvertsVia<Sibling, AccountId>,
// Straight up local `AccountId32` origins just alias directly to `AccountId`.
AccountId32Aliases<RelayNetwork, AccountId>,
);
/// Means for transacting assets on this chain.
pub type LocalAssetTransactor = CurrencyAdapter<
// Use this currency:
Balances,
// Use this currency when it is a fungible asset matching the given location or name:
IsConcrete<RelayLocation>,
// Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:
LocationToAccountId,
// Our chain's account ID type (we can't get away without mentioning it explicitly):
AccountId,
// We don't track any teleports.
(),
>;
/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,
/// ready for dispatching a transaction with XCM `Transact`. There is an `OriginKind` which can
/// biases the kind of local `Origin` it will become.
pub type XcmOriginToTransactDispatchOrigin = (
// Sovereign account converter; this attempts to derive an `AccountId` from the origin location
// using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for
// foreign chains who want to have a local sovereign account on this chain which they control.
SovereignSignedViaLocation<LocationToAccountId, RuntimeOrigin>,
// Native converter for Relay-chain (Parent) location; will convert to a `Relay` origin when
// recognised.
RelayChainAsNative<RelayOrigin, RuntimeOrigin>,
// Native converter for sibling Parachains; will convert to a `SiblingPara` origin when
// recognised.
SiblingParachainAsNative<cumulus_pallet_xcm::Origin, RuntimeOrigin>,
// Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a
// transaction from the Root origin.
ParentAsSuperuser<RuntimeOrigin>,
// Native signed account converter; this just converts an `AccountId32` origin into a normal
// `Origin::Signed` origin of the same 32-byte value.
SignedAccountId32AsNative<RelayNetwork, RuntimeOrigin>,
// Xcm origins can be represented natively under the Xcm pallet's Xcm origin.
XcmPassthrough<RuntimeOrigin>,
);
// TODO: until https://github.com/paritytech/parity-bridges-common/issues/1417 is fixed (in either way),
// the following constant must match the similar constant in the Millau runtime.
parameter_types! {
/// The amount of weight an XCM operation takes. We don't care much about those values as we're on testnet.
pub const UnitWeightCost: Weight = Weight::from_parts(1_000_000, 1024);
// One UNIT buys 1 second of weight.
pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), UNIT);
pub const MaxInstructions: u32 = 100;
pub const MaxAuthorities: u32 = 100_000;
pub MaxAssetsIntoHolding: u32 = 64;
}
match_types! {
pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {
MultiLocation { parents: 1, interior: Here } |
MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }
};
}
pub type Barrier = TakeWeightCredit;
/// Dispatches received XCM messages from other chain.
pub type OnRialtoParachainBlobDispatcher =
xcm_builder::BridgeBlobDispatcher<XcmRouter, UniversalLocation, ()>;
/// XCM weigher type.
pub type XcmWeigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;
pub struct XcmConfig;
impl Config for XcmConfig {
type RuntimeCall = RuntimeCall;
type XcmSender = ();
type AssetTransactor = LocalAssetTransactor;
type OriginConverter = XcmOriginToTransactDispatchOrigin;
type IsReserve = NativeAsset;
type IsTeleporter = NativeAsset; // <- should be enough to allow teleportation of UNIT
type UniversalLocation = UniversalLocation;
type Barrier = Barrier;
type Weigher = XcmWeigher;
type Trader = UsingComponents<IdentityFee<Balance>, RelayLocation, AccountId, Balances, ()>;
type ResponseHandler = PolkadotXcm;
type AssetTrap = PolkadotXcm;
type AssetClaims = PolkadotXcm;
type SubscriptionService = PolkadotXcm;
type PalletInstancesInfo = ();
type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
type AssetLocker = ();
type AssetExchanger = ();
type FeeManager = ();
type MessageExporter = millau_messages::ToMillauBlobExporter;
type UniversalAliases = Nothing;
type CallDispatcher = RuntimeCall;
type SafeCallFilter = Everything;
type Aliasers = Nothing;
}
/// No local origins on this chain are allowed to dispatch XCM sends/executions.
pub type LocalOriginToLocation = SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>;
/// The XCM router. We are not sending messages to sibling/parent/child chains here.
pub type XcmRouter = ();
#[cfg(feature = "runtime-benchmarks")]
parameter_types! {
pub ReachableDest: Option<MultiLocation> = None;
}
impl pallet_xcm::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type SendXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
type XcmRouter = XcmRouter;
type ExecuteXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
type XcmExecuteFilter = Everything;
type XcmExecutor = XcmExecutor<XcmConfig>;
type XcmTeleportFilter = Everything;
type XcmReserveTransferFilter = Everything;
type Weigher = XcmWeigher;
type RuntimeOrigin = RuntimeOrigin;
type RuntimeCall = RuntimeCall;
const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
type Currency = Balances;
type CurrencyMatcher = ();
type TrustedLockers = ();
type SovereignAccountOf = ();
type MaxLockers = frame_support::traits::ConstU32<8>;
type UniversalLocation = UniversalLocation;
type WeightInfo = pallet_xcm::TestWeightInfo;
#[cfg(feature = "runtime-benchmarks")]
type ReachableDest = ReachableDest;
type AdminOrigin = frame_system::EnsureRoot<AccountId>;
type MaxRemoteLockConsumers = ConstU32<0>;
type RemoteLockConsumerIdentifier = ();
}
impl cumulus_pallet_xcm::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type XcmExecutor = XcmExecutor<XcmConfig>;
}
impl cumulus_pallet_xcmp_queue::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type XcmExecutor = XcmExecutor<XcmConfig>;
type ChannelInfo = ParachainSystem;
type VersionWrapper = ();
type ExecuteOverweightOrigin = EnsureRoot<AccountId>;
type ControllerOrigin = EnsureRoot<AccountId>;
type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;
type WeightInfo = ();
type PriceForSiblingDelivery = ();
}
impl cumulus_pallet_dmp_queue::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type XcmExecutor = XcmExecutor<XcmConfig>;
type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;
}
impl pallet_aura::Config for Runtime {
type AuthorityId = AuraId;
type DisabledValidators = ();
type MaxAuthorities = MaxAuthorities;
type AllowMultipleBlocksPerSlot = ConstBool<false>;
}
impl pallet_bridge_relayers::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Reward = Balance;
type PaymentProcedure =
bp_relayers::PayRewardFromAccount<pallet_balances::Pallet<Runtime>, AccountId>;
type StakeAndSlash = ();
type WeightInfo = ();
}
pub type MillauGrandpaInstance = ();
impl pallet_bridge_grandpa::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type BridgedChain = bp_millau::Millau;
type MaxFreeMandatoryHeadersPerBlock = ConstU32<4>;
type HeadersToKeep = ConstU32<{ bp_millau::DAYS as u32 }>;
type WeightInfo = pallet_bridge_grandpa::weights::BridgeWeight<Runtime>;
}
parameter_types! {
pub const MaxMessagesToPruneAtOnce: bp_messages::MessageNonce = 8;
pub const MaxUnrewardedRelayerEntriesAtInboundLane: bp_messages::MessageNonce =
bp_millau::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX;
pub const MaxUnconfirmedMessagesAtInboundLane: bp_messages::MessageNonce =
bp_millau::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX;
pub const RootAccountForPayments: Option<AccountId> = None;
pub const BridgedChainId: bp_runtime::ChainId = bp_runtime::MILLAU_CHAIN_ID;
pub ActiveOutboundLanes: &'static [bp_messages::LaneId] = &[millau_messages::XCM_LANE];
}
/// Instance of the messages pallet used to relay messages to/from Millau chain.
pub type WithMillauMessagesInstance = ();
impl pallet_bridge_messages::Config<WithMillauMessagesInstance> for Runtime {
type RuntimeEvent = RuntimeEvent;
type WeightInfo = pallet_bridge_messages::weights::BridgeWeight<Runtime>;
type ActiveOutboundLanes = ActiveOutboundLanes;
type MaxUnrewardedRelayerEntriesAtInboundLane = MaxUnrewardedRelayerEntriesAtInboundLane;
type MaxUnconfirmedMessagesAtInboundLane = MaxUnconfirmedMessagesAtInboundLane;
type MaximalOutboundPayloadSize = crate::millau_messages::ToMillauMaximalOutboundPayloadSize;
type OutboundPayload = crate::millau_messages::ToMillauMessagePayload;
type InboundPayload = crate::millau_messages::FromMillauMessagePayload;
type InboundRelayer = bp_millau::AccountId;
type DeliveryPayments = ();
type TargetHeaderChain = crate::millau_messages::MillauAsTargetHeaderChain;
type LaneMessageVerifier = crate::millau_messages::ToMillauMessageVerifier;
type DeliveryConfirmationPayments = pallet_bridge_relayers::DeliveryConfirmationPaymentsAdapter<
Runtime,
WithMillauMessagesInstance,
frame_support::traits::ConstU128<100_000>,
>;
type OnMessagesDelivered = ();
type SourceHeaderChain = crate::millau_messages::MillauAsSourceHeaderChain;
type MessageDispatch = crate::millau_messages::FromMillauMessageDispatch;
type BridgedChainId = BridgedChainId;
}
// Create the runtime by composing the FRAME pallets that were previously configured.
construct_runtime!(
pub enum Runtime {
System: frame_system::{Pallet, Call, Storage, Config<T>, Event<T>},
Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent},
Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>},
TransactionPayment: pallet_transaction_payment::{Pallet, Storage, Event<T>},
ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Storage, Inherent, Event<T>} = 20,
ParachainInfo: parachain_info::{Pallet, Storage, Config<T>} = 21,
Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,
Aura: pallet_aura::{Pallet, Config<T>},
AuraExt: cumulus_pallet_aura_ext::{Pallet, Config<T>},
// XCM helpers.
XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,
PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,
CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,
DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,
// Millau bridge modules.
BridgeRelayers: pallet_bridge_relayers::{Pallet, Call, Storage, Event<T>},
BridgeMillauGrandpa: pallet_bridge_grandpa::{Pallet, Call, Storage, Event<T>},
BridgeMillauMessages: pallet_bridge_messages::{Pallet, Call, Storage, Event<T>, Config<T>},
}
);
impl_runtime_apis! {
impl sp_api::Core<Block> for Runtime {
fn version() -> RuntimeVersion {
VERSION
}
fn execute_block(block: Block) {
Executive::execute_block(block)
}
fn initialize_block(header: &<Block as BlockT>::Header) {
Executive::initialize_block(header)
}
}
impl sp_api::Metadata<Block> for Runtime {
fn metadata() -> OpaqueMetadata {
OpaqueMetadata::new(Runtime::metadata().into())
}
fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
Runtime::metadata_at_version(version)
}
fn metadata_versions() -> sp_std::vec::Vec<u32> {
Runtime::metadata_versions()
}
}
impl sp_block_builder::BlockBuilder<Block> for Runtime {
fn apply_extrinsic(
extrinsic: <Block as BlockT>::Extrinsic,
) -> ApplyExtrinsicResult {
Executive::apply_extrinsic(extrinsic)
}
fn finalize_block() -> <Block as BlockT>::Header {
Executive::finalize_block()
}
fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
data.create_extrinsics()
}
fn check_inherents(
block: Block,
data: sp_inherents::InherentData,
) -> sp_inherents::CheckInherentsResult {
data.check_extrinsics(&block)
}
}
impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
fn validate_transaction(
source: TransactionSource,
tx: <Block as BlockT>::Extrinsic,
block_hash: <Block as BlockT>::Hash,
) -> TransactionValidity {
Executive::validate_transaction(source, tx, block_hash)
}
}
impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
fn offchain_worker(header: &<Block as BlockT>::Header) {
Executive::offchain_worker(header)
}
}
impl sp_session::SessionKeys<Block> for Runtime {
fn decode_session_keys(
encoded: Vec<u8>,
) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
SessionKeys::decode_into_raw_public_keys(&encoded)
}
fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
SessionKeys::generate(seed)
}
}
impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {
fn slot_duration() -> sp_consensus_aura::SlotDuration {
sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())
}
fn authorities() -> Vec<AuraId> {
Aura::authorities().to_vec()
}
}
impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {
fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {
ParachainSystem::collect_collation_info(header)
}
}
impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
fn account_nonce(account: AccountId) -> Nonce {
System::account_nonce(account)
}
}
impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {
fn query_info(
uxt: <Block as BlockT>::Extrinsic,
len: u32,
) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
TransactionPayment::query_info(uxt, len)
}
fn query_fee_details(
uxt: <Block as BlockT>::Extrinsic,
len: u32,
) -> pallet_transaction_payment::FeeDetails<Balance> {
TransactionPayment::query_fee_details(uxt, len)
}
fn query_weight_to_fee(weight: Weight) -> Balance {
TransactionPayment::weight_to_fee(weight)
}
fn query_length_to_fee(length: u32) -> Balance {
TransactionPayment::length_to_fee(length)
}
}
impl bp_millau::MillauFinalityApi<Block> for Runtime {
fn best_finalized() -> Option<HeaderId<bp_millau::Hash, bp_millau::BlockNumber>> {
BridgeMillauGrandpa::best_finalized()
}
fn synced_headers_grandpa_info(
) -> Vec<bp_header_chain::StoredHeaderGrandpaInfo<bp_millau::Header>> {
BridgeMillauGrandpa::synced_headers_grandpa_info()
}
}
impl bp_millau::ToMillauOutboundLaneApi<Block> for Runtime {
fn message_details(
lane: bp_messages::LaneId,
begin: bp_messages::MessageNonce,
end: bp_messages::MessageNonce,
) -> Vec<bp_messages::OutboundMessageDetails> {
bridge_runtime_common::messages_api::outbound_message_details::<
Runtime,
WithMillauMessagesInstance,
>(lane, begin, end)
}
}
impl bp_millau::FromMillauInboundLaneApi<Block> for Runtime {
fn message_details(
lane: bp_messages::LaneId,
messages: Vec<(bp_messages::MessagePayload, bp_messages::OutboundMessageDetails)>,
) -> Vec<bp_messages::InboundMessageDetails> {
bridge_runtime_common::messages_api::inbound_message_details::<
Runtime,
WithMillauMessagesInstance,
>(lane, messages)
}
}
#[cfg(feature = "runtime-benchmarks")]
impl frame_benchmarking::Benchmark<Block> for Runtime {
fn benchmark_metadata(_extra: bool) -> (
Vec<frame_benchmarking::BenchmarkList>,
Vec<frame_support::traits::StorageInfo>,
) {
todo!("TODO: fix or remove")
}
fn dispatch_benchmark(
config: frame_benchmarking::BenchmarkConfig
) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {
use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark};
use frame_support::traits::TrackedStorageKey;
use frame_system_benchmarking::Pallet as SystemBench;
impl frame_system_benchmarking::Config for Runtime {}
let whitelist: Vec<TrackedStorageKey> = vec![
// Block Number
hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),
// Total Issuance
hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),
// Execution Phase
hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),
// Event Count
hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),
// System Events
hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),
];
let mut batches = Vec::<BenchmarkBatch>::new();
let params = (&config, &whitelist);
add_benchmark!(params, batches, frame_system, SystemBench::<Runtime>);
add_benchmark!(params, batches, pallet_balances, Balances);
add_benchmark!(params, batches, pallet_timestamp, Timestamp);
Ok(batches)
}
}
}
struct CheckInherents;
impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {
fn check_inherents(
block: &Block,
relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,
) -> sp_inherents::CheckInherentsResult {
let relay_chain_slot = relay_state_proof
.read_slot()
.expect("Could not read the relay chain slot from the proof");
let inherent_data =
cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(
relay_chain_slot,
sp_std::time::Duration::from_secs(6),
)
.create_inherent_data()
.expect("Could not create the timestamp inherent data");
inherent_data.check_extrinsics(block)
}
}
cumulus_pallet_parachain_system::register_validate_block!(
Runtime = Runtime,
BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,
CheckInherents = CheckInherents,
);
#[cfg(test)]
mod tests {
use super::*;
use crate::millau_messages::{FromMillauMessageDispatch, XCM_LANE};
use bp_messages::{
target_chain::{DispatchMessage, DispatchMessageData, MessageDispatch},
LaneId, MessageKey,
};
use bridge_runtime_common::messages_xcm_extension::XcmBlobMessageDispatchResult;
use codec::Encode;
use pallet_bridge_messages::OutboundLanes;
use sp_runtime::{generic::Era, traits::Zero};
use xcm_executor::XcmExecutor;
fn new_test_ext() -> sp_io::TestExternalities {
sp_io::TestExternalities::new(
frame_system::GenesisConfig::<Runtime>::default().build_storage().unwrap(),
)
}
fn prepare_outbound_xcm_message(destination: NetworkId) -> Xcm<RuntimeCall> {
vec![ExportMessage {
network: destination,
destination: destination.into(),
xcm: vec![Instruction::Trap(42)].into(),
}]
.into()
}
#[test]
fn xcm_messages_to_millau_are_sent_using_bridge_exporter() {
new_test_ext().execute_with(|| {
// ensure that the there are no messages queued
assert_eq!(
OutboundLanes::<Runtime, WithMillauMessagesInstance>::get(XCM_LANE)
.latest_generated_nonce,
0,
);
// export message instruction "sends" message to Rialto
XcmExecutor::<XcmConfig>::execute_xcm_in_credit(
Here,
prepare_outbound_xcm_message(MillauNetwork::get()),
Default::default(),
Weight::MAX,
Weight::MAX,
)
.ensure_complete()
.expect("runtime configuration must be correct");
// ensure that the message has been queued
assert_eq!(
OutboundLanes::<Runtime, WithMillauMessagesInstance>::get(XCM_LANE)
.latest_generated_nonce,
1,
);
})
}
fn prepare_inbound_bridge_message() -> DispatchMessage<Vec<u8>> {
let xcm = xcm::VersionedXcm::<RuntimeCall>::V3(vec![Instruction::Trap(42)].into());
let location =
xcm::VersionedInteriorMultiLocation::V3(X1(GlobalConsensus(ThisNetwork::get())));
// this is the `BridgeMessage` from polkadot xcm builder, but it has no constructor
// or public fields, so just tuple
let bridge_message = (location, xcm).encode();
DispatchMessage {
key: MessageKey { lane_id: LaneId([0, 0, 0, 0]), nonce: 1 },
data: DispatchMessageData { payload: Ok(bridge_message) },
}
}
#[test]
fn xcm_messages_from_millau_are_dispatched() {
new_test_ext().execute_with(|| {
let incoming_message = prepare_inbound_bridge_message();
// we care only about handing message to the XCM dispatcher, so we don't care about its
// actual dispatch
let dispatch_result = FromMillauMessageDispatch::dispatch(incoming_message);
assert!(matches!(
dispatch_result.dispatch_level_result,
XcmBlobMessageDispatchResult::NotDispatched(_),
));
});
}
#[test]
fn ensure_signed_extension_definition_is_correct() {
use bp_polkadot_core::SuffixedCommonSignedExtensionExt;
sp_io::TestExternalities::default().execute_with(|| {
frame_system::BlockHash::<Runtime>::insert(BlockNumber::zero(), Hash::default());
let payload: SignedExtra = (
frame_system::CheckNonZeroSender::new(),
frame_system::CheckSpecVersion::new(),
frame_system::CheckTxVersion::new(),
frame_system::CheckGenesis::new(),
frame_system::CheckEra::from(Era::Immortal),
frame_system::CheckNonce::from(10),
frame_system::CheckWeight::new(),
pallet_transaction_payment::ChargeTransactionPayment::from(10),
BridgeRejectObsoleteHeadersAndMessages,
DummyBridgeRefundMillauMessages,
);
let indirect_payload = bp_rialto_parachain::SignedExtension::from_params(
VERSION.spec_version,
VERSION.transaction_version,
bp_runtime::TransactionEra::Immortal,
System::block_hash(BlockNumber::zero()),
10,
10,
(((), ()), ((), ())),
);
assert_eq!(payload.encode(), indirect_payload.encode());
assert_eq!(
payload.additional_signed().unwrap().encode(),
indirect_payload.additional_signed().unwrap().encode()
)
});
}
}
@@ -1,206 +0,0 @@
// 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/>.
//! Everything required to serve Millau <-> RialtoParachain messages.
// TODO: this is almost exact copy of `millau_messages.rs` from Rialto runtime.
// Should be extracted to a separate crate and reused here.
use crate::{MillauGrandpaInstance, Runtime, RuntimeOrigin, WithMillauMessagesInstance};
use bp_messages::LaneId;
use bridge_runtime_common::{
messages::{
self, source::TargetHeaderChainAdapter, target::SourceHeaderChainAdapter, MessageBridge,
},
messages_xcm_extension::{SenderAndLane, XcmBlobHauler, XcmBlobHaulerAdapter},
};
use frame_support::{parameter_types, weights::Weight};
use sp_runtime::RuntimeDebug;
use xcm::latest::prelude::*;
use xcm_builder::HaulBlobExporter;
/// Default lane that is used to send messages to Millau.
pub const XCM_LANE: LaneId = LaneId([0, 0, 0, 0]);
/// Weight of 2 XCM instructions is for simple `Trap(42)` program, coming through bridge
/// (it is prepended with `UniversalOrigin` instruction). It is used just for simplest manual
/// tests, confirming that we don't break encoding somewhere between.
pub const BASE_XCM_WEIGHT_TWICE: Weight = crate::UnitWeightCost::get().saturating_mul(2);
parameter_types! {
/// Weight credit for our test messages.
///
/// 2 XCM instructions is for simple `Trap(42)` program, coming through bridge
/// (it is prepended with `UniversalOrigin` instruction).
pub const WeightCredit: Weight = BASE_XCM_WEIGHT_TWICE;
/// Lane used by the with-Millau bridge.
pub MullauSenderAndLane: SenderAndLane = SenderAndLane::new(Here.into(), XCM_LANE);
/// Dummy message used in configuration.
pub DummyXcmMessage: Xcm<()> = Xcm::new();
}
/// Message payload for RialtoParachain -> Millau messages.
pub type ToMillauMessagePayload = messages::source::FromThisChainMessagePayload;
/// Message verifier for RialtoParachain -> Millau messages.
pub type ToMillauMessageVerifier =
messages::source::FromThisChainMessageVerifier<WithMillauMessageBridge>;
/// Message payload for Millau -> RialtoParachain messages.
pub type FromMillauMessagePayload = messages::target::FromBridgedChainMessagePayload;
/// Call-dispatch based message dispatch for Millau -> RialtoParachain messages.
pub type FromMillauMessageDispatch =
bridge_runtime_common::messages_xcm_extension::XcmBlobMessageDispatch<
crate::OnRialtoParachainBlobDispatcher,
(),
(),
>;
/// Messages proof for Millau -> RialtoParachain messages.
pub type FromMillauMessagesProof = messages::target::FromBridgedChainMessagesProof<bp_millau::Hash>;
/// Messages delivery proof for RialtoParachain -> Millau messages.
pub type ToMillauMessagesDeliveryProof =
messages::source::FromBridgedChainMessagesDeliveryProof<bp_millau::Hash>;
/// Maximal outbound payload size of Rialto -> Millau messages.
pub type ToMillauMaximalOutboundPayloadSize =
messages::source::FromThisChainMaximalOutboundPayloadSize<WithMillauMessageBridge>;
/// Millau <-> RialtoParachain message bridge.
#[derive(RuntimeDebug, Clone, Copy)]
pub struct WithMillauMessageBridge;
impl MessageBridge for WithMillauMessageBridge {
const BRIDGED_MESSAGES_PALLET_NAME: &'static str =
bp_rialto_parachain::WITH_RIALTO_PARACHAIN_MESSAGES_PALLET_NAME;
type ThisChain = RialtoParachain;
type BridgedChain = Millau;
type BridgedHeaderChain =
pallet_bridge_grandpa::GrandpaChainHeaders<Runtime, MillauGrandpaInstance>;
}
/// RialtoParachain chain from message lane point of view.
#[derive(RuntimeDebug, Clone, Copy)]
pub struct RialtoParachain;
impl messages::UnderlyingChainProvider for RialtoParachain {
type Chain = bp_rialto_parachain::RialtoParachain;
}
impl messages::ThisChainWithMessages for RialtoParachain {
type RuntimeOrigin = RuntimeOrigin;
}
/// Millau chain from message lane point of view.
#[derive(RuntimeDebug, Clone, Copy)]
pub struct Millau;
/// Millau as source header chain.
pub type MillauAsSourceHeaderChain = SourceHeaderChainAdapter<WithMillauMessageBridge>;
/// Millau as target header chain.
pub type MillauAsTargetHeaderChain = TargetHeaderChainAdapter<WithMillauMessageBridge>;
impl messages::UnderlyingChainProvider for Millau {
type Chain = bp_millau::Millau;
}
impl messages::BridgedChainWithMessages for Millau {}
/// Export XCM messages to be relayed to Millau.
pub type ToMillauBlobExporter =
HaulBlobExporter<XcmBlobHaulerAdapter<ToMillauXcmBlobHauler>, crate::MillauNetwork, ()>;
/// To-Millau XCM hauler.
pub struct ToMillauXcmBlobHauler;
impl XcmBlobHauler for ToMillauXcmBlobHauler {
type Runtime = Runtime;
type MessagesInstance = WithMillauMessagesInstance;
type SenderAndLane = MullauSenderAndLane;
type ToSourceChainSender = crate::XcmRouter;
type CongestedMessage = DummyXcmMessage;
type UncongestedMessage = DummyXcmMessage;
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{MillauGrandpaInstance, Runtime, WithMillauMessagesInstance};
use bridge_runtime_common::{
assert_complete_bridge_types,
integrity::{
assert_complete_bridge_constants, check_message_lane_weights,
AssertBridgeMessagesPalletConstants, AssertBridgePalletNames, AssertChainConstants,
AssertCompleteBridgeConstants,
},
};
#[test]
fn ensure_millau_message_lane_weights_are_correct() {
check_message_lane_weights::<
bp_rialto_parachain::RialtoParachain,
Runtime,
WithMillauMessagesInstance,
>(
bp_millau::EXTRA_STORAGE_PROOF_SIZE,
bp_rialto_parachain::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX,
bp_rialto_parachain::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX,
false,
);
}
#[test]
fn ensure_bridge_integrity() {
assert_complete_bridge_types!(
runtime: Runtime,
with_bridged_chain_grandpa_instance: MillauGrandpaInstance,
with_bridged_chain_messages_instance: WithMillauMessagesInstance,
bridge: WithMillauMessageBridge,
this_chain: bp_rialto_parachain::RialtoParachain,
bridged_chain: bp_millau::Millau,
);
assert_complete_bridge_constants::<
Runtime,
MillauGrandpaInstance,
WithMillauMessagesInstance,
WithMillauMessageBridge,
>(AssertCompleteBridgeConstants {
this_chain_constants: AssertChainConstants {
block_length: bp_rialto_parachain::BlockLength::get(),
block_weights: bp_rialto_parachain::BlockWeights::get(),
},
messages_pallet_constants: AssertBridgeMessagesPalletConstants {
max_unrewarded_relayers_in_bridged_confirmation_tx:
bp_millau::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX,
max_unconfirmed_messages_in_bridged_confirmation_tx:
bp_millau::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX,
bridged_chain_id: bp_runtime::MILLAU_CHAIN_ID,
},
pallet_names: AssertBridgePalletNames {
with_this_chain_messages_pallet_name:
bp_rialto_parachain::WITH_RIALTO_PARACHAIN_MESSAGES_PALLET_NAME,
with_bridged_chain_grandpa_pallet_name: bp_millau::WITH_MILLAU_GRANDPA_PALLET_NAME,
with_bridged_chain_messages_pallet_name:
bp_millau::WITH_MILLAU_MESSAGES_PALLET_NAME,
},
});
}
}
-61
View File
@@ -1,61 +0,0 @@
[[bin]]
name = "rialto-bridge-node-execute-worker"
path = "src/workers/execute-worker.rs"
[[bin]]
name = "rialto-bridge-node-prepare-worker"
path = "src/workers/prepare-worker.rs"
[package]
name = "rialto-bridge-node"
description = "Substrate node compatible with Rialto runtime"
version = "0.1.0"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2021"
build = "build.rs"
repository = "https://github.com/paritytech/parity-bridges-common/"
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
[dependencies]
clap = { version = "4.4.8", features = ["derive"] }
serde_json = "1.0.108"
# Bridge dependencies
rialto-runtime = { path = "../runtime" }
# Substrate Dependencies
sp-consensus-beefy = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
frame-benchmarking = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
frame-benchmarking-cli = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
frame-support = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
node-inspect = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sc-cli = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master"}
sc-executor = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sc-service = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sp-authority-discovery = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sp-consensus-babe = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sp-core = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sp-consensus-grandpa = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
# Polkadot Dependencies
polkadot-node-core-pvf = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
polkadot-node-core-pvf-common = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
polkadot-node-core-pvf-execute-worker = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
polkadot-node-core-pvf-prepare-worker = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
polkadot-primitives = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
polkadot-runtime-parachains = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
polkadot-service = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false, features = [ "full-node" ] }
[build-dependencies]
substrate-build-script-utils = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
frame-benchmarking-cli = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
[features]
default = []
runtime-benchmarks = [
"polkadot-service/runtime-benchmarks",
"rialto-runtime/runtime-benchmarks",
]
-23
View File
@@ -1,23 +0,0 @@
// 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 substrate_build_script_utils::{generate_cargo_keys, rerun_if_git_head_changed};
fn main() {
generate_cargo_keys();
rerun_if_git_head_changed();
}
-282
View File
@@ -1,282 +0,0 @@
// 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 polkadot_primitives::v6::{AssignmentId, ValidatorId};
use rialto_runtime::{
AccountId, BabeConfig, BalancesConfig, BeefyConfig, BridgeMillauMessagesConfig,
ConfigurationConfig, GrandpaConfig, RuntimeGenesisConfig, SessionConfig, SessionKeys,
Signature, SudoConfig, SystemConfig, WASM_BINARY,
};
use serde_json::json;
use sp_authority_discovery::AuthorityId as AuthorityDiscoveryId;
use sp_consensus_babe::AuthorityId as BabeId;
use sp_consensus_beefy::ecdsa_crypto::AuthorityId as BeefyId;
use sp_consensus_grandpa::AuthorityId as GrandpaId;
use sp_core::{sr25519, Pair, Public};
use sp_runtime::traits::{IdentifyAccount, Verify};
/// "Names" of the authorities accounts at local testnet.
const LOCAL_AUTHORITIES_ACCOUNTS: [&str; 5] = ["Alice", "Bob", "Charlie", "Dave", "Eve"];
/// "Names" of the authorities accounts at development testnet.
const DEV_AUTHORITIES_ACCOUNTS: [&str; 1] = [LOCAL_AUTHORITIES_ACCOUNTS[0]];
/// "Names" of all possible authorities accounts.
const ALL_AUTHORITIES_ACCOUNTS: [&str; 5] = LOCAL_AUTHORITIES_ACCOUNTS;
/// "Name" of the `sudo` account.
const SUDO_ACCOUNT: &str = "Sudo";
/// "Name" of the account, which owns the with-Millau messages pallet.
const MILLAU_MESSAGES_PALLET_OWNER: &str = "Millau.MessagesOwner";
/// Specialized `ChainSpec`. This is a specialization of the general Substrate ChainSpec type.
pub type ChainSpec =
sc_service::GenericChainSpec<RuntimeGenesisConfig, polkadot_service::chain_spec::Extensions>;
/// The chain specification option. This is expected to come in from the CLI and
/// is little more than one of a number of alternatives which can easily be converted
/// from a string (`--chain=...`) into a `ChainSpec`.
#[derive(Clone, Debug)]
pub enum Alternative {
/// Whatever the current runtime is, with just Alice as an auth.
Development,
/// Whatever the current runtime is, with simple Alice/Bob/Charlie/Dave/Eve auths.
LocalTestnet,
}
/// Helper function to generate a crypto pair from seed
pub fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public {
TPublic::Pair::from_string(&format!("//{seed}"), None)
.expect("static values are valid; qed")
.public()
}
type AccountPublic = <Signature as Verify>::Signer;
/// Helper function to generate an account ID from seed
pub fn get_account_id_from_seed<TPublic: Public>(seed: &str) -> AccountId
where
AccountPublic: From<<TPublic::Pair as Pair>::Public>,
{
AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account()
}
/// Helper function to generate authority keys.
pub fn get_authority_keys_from_seed(
s: &str,
) -> (AccountId, BabeId, BeefyId, GrandpaId, ValidatorId, AssignmentId, AuthorityDiscoveryId) {
(
get_account_id_from_seed::<sr25519::Public>(s),
get_from_seed::<BabeId>(s),
get_from_seed::<BeefyId>(s),
get_from_seed::<GrandpaId>(s),
get_from_seed::<ValidatorId>(s),
get_from_seed::<AssignmentId>(s),
get_from_seed::<AuthorityDiscoveryId>(s),
)
}
impl Alternative {
/// Get an actual chain config from one of the alternatives.
pub(crate) fn load(self) -> ChainSpec {
let properties = Some(
json!({
"tokenDecimals": 9,
"tokenSymbol": "RLT"
})
.as_object()
.expect("Map given; qed")
.clone(),
);
match self {
Alternative::Development => ChainSpec::from_genesis(
"Rialto Development",
"rialto_dev",
sc_service::ChainType::Development,
|| {
testnet_genesis(
DEV_AUTHORITIES_ACCOUNTS
.into_iter()
.map(get_authority_keys_from_seed)
.collect(),
get_account_id_from_seed::<sr25519::Public>(SUDO_ACCOUNT),
endowed_accounts(),
true,
)
},
vec![],
None,
None,
None,
properties,
Default::default(),
),
Alternative::LocalTestnet => ChainSpec::from_genesis(
"Rialto Local",
"rialto_local",
sc_service::ChainType::Local,
|| {
testnet_genesis(
LOCAL_AUTHORITIES_ACCOUNTS
.into_iter()
.map(get_authority_keys_from_seed)
.collect(),
get_account_id_from_seed::<sr25519::Public>(SUDO_ACCOUNT),
endowed_accounts(),
true,
)
},
vec![],
None,
None,
None,
properties,
Default::default(),
),
}
}
}
/// We're using the same set of endowed accounts on all Millau chains (dev/local) to make
/// sure that all accounts, required for bridge to be functional (e.g. relayers fund account,
/// accounts used by relayers in our test deployments, accounts used for demonstration
/// purposes), are all available on these chains.
fn endowed_accounts() -> Vec<AccountId> {
let all_authorities = ALL_AUTHORITIES_ACCOUNTS.iter().flat_map(|x| {
[
get_account_id_from_seed::<sr25519::Public>(x),
get_account_id_from_seed::<sr25519::Public>(&format!("{x}//stash")),
]
});
vec![
// Sudo account
get_account_id_from_seed::<sr25519::Public>(SUDO_ACCOUNT),
// Regular (unused) accounts
get_account_id_from_seed::<sr25519::Public>("Ferdie"),
get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"),
// Accounts, used by Rialto<>Millau bridge
get_account_id_from_seed::<sr25519::Public>(MILLAU_MESSAGES_PALLET_OWNER),
get_account_id_from_seed::<sr25519::Public>("Millau.HeadersAndMessagesRelay"),
get_account_id_from_seed::<sr25519::Public>("Millau.OutboundMessagesRelay.Lane00000001"),
get_account_id_from_seed::<sr25519::Public>("Millau.InboundMessagesRelay.Lane00000001"),
get_account_id_from_seed::<sr25519::Public>("Millau.MessagesSender"),
]
.into_iter()
.chain(all_authorities)
.collect()
}
fn session_keys(
babe: BabeId,
beefy: BeefyId,
grandpa: GrandpaId,
para_validator: ValidatorId,
para_assignment: AssignmentId,
authority_discovery: AuthorityDiscoveryId,
) -> SessionKeys {
SessionKeys { babe, beefy, grandpa, para_validator, para_assignment, authority_discovery }
}
fn testnet_genesis(
initial_authorities: Vec<(
AccountId,
BabeId,
BeefyId,
GrandpaId,
ValidatorId,
AssignmentId,
AuthorityDiscoveryId,
)>,
root_key: AccountId,
endowed_accounts: Vec<AccountId>,
_enable_println: bool,
) -> RuntimeGenesisConfig {
RuntimeGenesisConfig {
system: SystemConfig {
code: WASM_BINARY.expect("Rialto development WASM not available").to_vec(),
..Default::default()
},
balances: BalancesConfig {
balances: endowed_accounts.iter().cloned().map(|k| (k, 1 << 50)).collect(),
},
babe: BabeConfig {
authorities: Vec::new(),
epoch_config: Some(rialto_runtime::BABE_GENESIS_EPOCH_CONFIG),
..Default::default()
},
beefy: BeefyConfig::default(),
grandpa: GrandpaConfig { authorities: Vec::new(), ..Default::default() },
sudo: SudoConfig { key: Some(root_key) },
session: SessionConfig {
keys: initial_authorities
.iter()
.map(|x| {
(
x.0.clone(),
x.0.clone(),
session_keys(
x.1.clone(),
x.2.clone(),
x.3.clone(),
x.4.clone(),
x.5.clone(),
x.6.clone(),
),
)
})
.collect::<Vec<_>>(),
},
authority_discovery: Default::default(),
hrmp: Default::default(),
// this configuration is exact copy of configuration from Polkadot repo
// (see /node/service/src/chain_spec.rs:default_parachains_host_configuration)
configuration: ConfigurationConfig {
config: polkadot_runtime_parachains::configuration::HostConfiguration {
validation_upgrade_cooldown: 2u32,
validation_upgrade_delay: 2,
code_retention_period: 1200,
max_code_size: polkadot_primitives::v6::MAX_CODE_SIZE,
max_pov_size: polkadot_primitives::v6::MAX_POV_SIZE,
max_head_data_size: 32 * 1024,
group_rotation_frequency: 20,
max_upward_queue_count: 8,
max_upward_queue_size: 1024 * 1024,
max_downward_message_size: 1024 * 1024,
max_upward_message_size: 50 * 1024,
max_upward_message_num_per_candidate: 5,
hrmp_sender_deposit: 0,
hrmp_recipient_deposit: 0,
hrmp_channel_max_capacity: 8,
hrmp_channel_max_total_size: 8 * 1024,
hrmp_max_parachain_inbound_channels: 4,
hrmp_channel_max_message_size: 1024 * 1024,
hrmp_max_parachain_outbound_channels: 4,
hrmp_max_message_num_per_candidate: 5,
dispute_period: 6,
no_show_slots: 2,
n_delay_tranches: 25,
needed_approvals: 2,
relay_vrf_modulo_samples: 2,
zeroth_delay_tranche_width: 0,
minimum_validation_upgrade_delay: 5,
..Default::default()
},
},
paras: Default::default(),
bridge_millau_messages: BridgeMillauMessagesConfig {
owner: Some(get_account_id_from_seed::<sr25519::Public>(MILLAU_MESSAGES_PALLET_OWNER)),
..Default::default()
},
xcm_pallet: Default::default(),
}
}
-84
View File
@@ -1,84 +0,0 @@
// 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 clap::Parser;
use sc_cli::RunCmd;
#[derive(Debug, Parser)]
pub struct Cli {
#[structopt(subcommand)]
pub subcommand: Option<Subcommand>,
#[structopt(flatten)]
pub run: RunCmd,
}
/// Possible subcommands of the main binary.
#[derive(Debug, Parser)]
#[allow(clippy::large_enum_variant)]
pub enum Subcommand {
/// Key management CLI utilities
#[clap(subcommand)]
Key(sc_cli::KeySubcommand),
/// Verify a signature for a message, provided on `STDIN`, with a given (public or secret) key.
Verify(sc_cli::VerifyCmd),
/// Generate a seed that provides a vanity address.
Vanity(sc_cli::VanityCmd),
/// Sign a message, with a given (secret) key.
Sign(sc_cli::SignCmd),
/// Build a chain specification.
BuildSpec(sc_cli::BuildSpecCmd),
/// Validate blocks.
CheckBlock(sc_cli::CheckBlockCmd),
/// Export blocks.
ExportBlocks(sc_cli::ExportBlocksCmd),
/// Export the state of a given block into a chain spec.
ExportState(sc_cli::ExportStateCmd),
/// Import blocks.
ImportBlocks(sc_cli::ImportBlocksCmd),
/// Remove the whole chain.
PurgeChain(sc_cli::PurgeChainCmd),
/// Revert the chain to a previous state.
Revert(sc_cli::RevertCmd),
/// Inspect blocks or extrinsics.
Inspect(node_inspect::cli::InspectCmd),
/// Benchmark runtime pallets.
#[command(subcommand)]
Benchmark(frame_benchmarking_cli::BenchmarkCmd),
}
/// Validation worker command.
#[derive(Debug, Parser)]
pub struct ValidationWorkerCommand {
/// The path to the validation host's socket.
#[arg(long)]
pub socket_path: String,
/// Calling node implementation version
#[arg(long)]
pub node_impl_version: String,
}
-193
View File
@@ -1,193 +0,0 @@
// 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::cli::{Cli, Subcommand};
use frame_benchmarking_cli::BenchmarkCmd;
use rialto_runtime::{Block, RuntimeApi};
use sc_cli::SubstrateCli;
impl SubstrateCli for Cli {
fn impl_name() -> String {
"Rialto Bridge Node".into()
}
fn impl_version() -> String {
env!("CARGO_PKG_VERSION").into()
}
fn description() -> String {
"Rialto Bridge Node".into()
}
fn author() -> String {
"Parity Technologies".into()
}
fn support_url() -> String {
"https://github.com/paritytech/parity-bridges-common/".into()
}
fn copyright_start_year() -> i32 {
2019
}
fn executable_name() -> String {
"rialto-bridge-node".into()
}
fn load_spec(&self, id: &str) -> Result<Box<dyn sc_service::ChainSpec>, String> {
Ok(Box::new(
match id {
"" | "dev" => crate::chain_spec::Alternative::Development,
"local" => crate::chain_spec::Alternative::LocalTestnet,
_ => return Err(format!("Unsupported chain specification: {id}")),
}
.load(),
))
}
}
// Rialto native executor instance.
pub struct ExecutorDispatch;
impl sc_executor::NativeExecutionDispatch for ExecutorDispatch {
type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;
fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {
rialto_runtime::api::dispatch(method, data)
}
fn native_version() -> sc_executor::NativeVersion {
rialto_runtime::native_version()
}
}
/// Parse and run command line arguments
pub fn run() -> sc_cli::Result<()> {
let cli = Cli::from_args();
sp_core::crypto::set_default_ss58_version(sp_core::crypto::Ss58AddressFormat::custom(
rialto_runtime::SS58Prefix::get() as u16,
));
match &cli.subcommand {
Some(Subcommand::Benchmark(cmd)) => {
let runner = cli.create_runner(cmd)?;
match cmd {
BenchmarkCmd::Pallet(cmd) =>
if cfg!(feature = "runtime-benchmarks") {
runner.sync_run(|config| cmd.run::<Block, ()>(config))
} else {
println!(
"Benchmarking wasn't enabled when building the node. \
You can enable it with `--features runtime-benchmarks`."
);
Ok(())
},
_ => Err("Unsupported benchmarking subcommand".into()),
}
},
Some(Subcommand::Key(cmd)) => cmd.run(&cli),
Some(Subcommand::Sign(cmd)) => cmd.run(),
Some(Subcommand::Verify(cmd)) => cmd.run(),
Some(Subcommand::Vanity(cmd)) => cmd.run(),
Some(Subcommand::BuildSpec(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.sync_run(|config| cmd.run(config.chain_spec, config.network))
},
Some(Subcommand::CheckBlock(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.async_run(|mut config| {
let (client, _, import_queue, task_manager) =
polkadot_service::new_chain_ops(&mut config, None).map_err(service_error)?;
Ok((cmd.run(client, import_queue), task_manager))
})
},
Some(Subcommand::ExportBlocks(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.async_run(|mut config| {
let (client, _, _, task_manager) =
polkadot_service::new_chain_ops(&mut config, None).map_err(service_error)?;
Ok((cmd.run(client, config.database), task_manager))
})
},
Some(Subcommand::ExportState(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.async_run(|mut config| {
let (client, _, _, task_manager) =
polkadot_service::new_chain_ops(&mut config, None).map_err(service_error)?;
Ok((cmd.run(client, config.chain_spec), task_manager))
})
},
Some(Subcommand::ImportBlocks(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.async_run(|mut config| {
let (client, _, import_queue, task_manager) =
polkadot_service::new_chain_ops(&mut config, None).map_err(service_error)?;
Ok((cmd.run(client, import_queue), task_manager))
})
},
Some(Subcommand::PurgeChain(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.sync_run(|config| cmd.run(config.database))
},
Some(Subcommand::Revert(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.async_run(|mut config| {
let (client, backend, _, task_manager) =
polkadot_service::new_chain_ops(&mut config, None).map_err(service_error)?;
Ok((cmd.run(client, backend, None), task_manager))
})
},
Some(Subcommand::Inspect(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.sync_run(|config| cmd.run::<Block, RuntimeApi, ExecutorDispatch>(config))
},
None => {
let runner = cli.create_runner(&cli.run)?;
runner.run_node_until_exit(|config| async move {
polkadot_service::new_full(
config,
polkadot_service::NewFullParams {
is_parachain_node: polkadot_service::IsParachainNode::No,
grandpa_pause: None,
enable_beefy: true,
jaeger_agent: None,
telemetry_worker_handle: None,
node_version: None,
workers_path: None,
workers_names: Some((
"rialto-bridge-node-prepare-worker".to_string(),
"rialto-bridge-node-execute-worker".to_string(),
)),
overseer_gen: polkadot_service::overseer::RealOverseerGen,
overseer_message_channel_capacity_override: None,
malus_finality_delay: None,
hwbench: None,
},
)
.map(|full| full.task_manager)
.map_err(service_error)
})
},
}
}
// We don't want to change 'service.rs' too much to ease future updates => it'll keep using
// its own error enum like original polkadot service does.
fn service_error(err: polkadot_service::Error) -> sc_cli::Error {
sc_cli::Error::Application(Box::new(err))
}
-28
View File
@@ -1,28 +0,0 @@
// 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/>.
//! Rialto bridge node.
#![warn(missing_docs)]
mod chain_spec;
mod cli;
mod command;
/// Run the Rialto Node
fn main() -> sc_cli::Result<()> {
command::run()
}
@@ -1,23 +0,0 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Polkadot.
// Polkadot 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.
// Polkadot 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 Polkadot. If not, see <http://www.gnu.org/licenses/>.
//! Execute worker.
polkadot_node_core_pvf_common::decl_worker_main!(
"execute-worker",
polkadot_node_core_pvf_execute_worker::worker_entrypoint,
env!("SUBSTRATE_CLI_IMPL_VERSION")
);
@@ -1,23 +0,0 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Polkadot.
// Polkadot 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.
// Polkadot 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 Polkadot. If not, see <http://www.gnu.org/licenses/>.
//! Prepare worker.
polkadot_node_core_pvf_common::decl_worker_main!(
"prepare-worker",
polkadot_node_core_pvf_prepare_worker::worker_entrypoint,
env!("SUBSTRATE_CLI_IMPL_VERSION")
);
-153
View File
@@ -1,153 +0,0 @@
[package]
name = "rialto-runtime"
version = "0.1.0"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2021"
repository = "https://github.com/paritytech/parity-bridges-common/"
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"] }
scale-info = { version = "2.10.0", default-features = false, features = ["derive"] }
# Bridge dependencies
bp-header-chain = { path = "../../../primitives/header-chain", default-features = false }
bp-messages = { path = "../../../primitives/messages", default-features = false }
bp-millau = { path = "../../../primitives/chain-millau", default-features = false }
bp-relayers = { path = "../../../primitives/relayers", default-features = false }
bp-rialto = { path = "../../../primitives/chain-rialto", default-features = false }
bp-runtime = { path = "../../../primitives/runtime", default-features = false }
bridge-runtime-common = { path = "../../runtime-common", default-features = false }
pallet-bridge-beefy = { path = "../../../modules/beefy", default-features = false }
pallet-bridge-grandpa = { path = "../../../modules/grandpa", default-features = false }
pallet-bridge-messages = { path = "../../../modules/messages", default-features = false }
pallet-bridge-relayers = { path = "../../../modules/relayers", default-features = false }
pallet-shift-session-manager = { path = "../../../modules/shift-session-manager", default-features = false }
# Substrate Dependencies
sp-consensus-beefy = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false, optional = true }
frame-benchmarking = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false, optional = true }
frame-executive = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
frame-support = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
frame-system = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
frame-system-rpc-runtime-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
pallet-authority-discovery = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
pallet-authorship = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
pallet-babe = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
pallet-balances = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
pallet-beefy = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
pallet-beefy-mmr = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
pallet-grandpa = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
pallet-message-queue = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
pallet-mmr = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
pallet-offences = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
pallet-session = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false, features = ["historical"]}
pallet-sudo = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
pallet-timestamp = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
pallet-transaction-payment = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
pallet-transaction-payment-rpc-runtime-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-authority-discovery = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-block-builder = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-consensus-babe = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-core = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-inherents = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-io = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-offchain = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-session = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-std = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-transaction-pool = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-version = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
# Polkadot (parachain) Dependencies
pallet-xcm = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
polkadot-primitives = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
polkadot-runtime-common = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
polkadot-runtime-parachains = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
xcm = { package = "staging-xcm", git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
xcm-builder = { package = "staging-xcm-builder", git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
xcm-executor = { package = "staging-xcm-executor", git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
[dev-dependencies]
bridge-runtime-common = { path = "../../runtime-common", features = ["integrity-test"] }
env_logger = "0.10"
static_assertions = "1.1"
[build-dependencies]
substrate-wasm-builder = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
[features]
default = [ "std" ]
std = [
"bp-messages/std",
"bp-millau/std",
"bp-relayers/std",
"bp-rialto/std",
"bp-runtime/std",
"bridge-runtime-common/std",
"codec/std",
"frame-benchmarking/std",
"frame-executive/std",
"frame-support/std",
"frame-system-rpc-runtime-api/std",
"frame-system/std",
"pallet-authority-discovery/std",
"pallet-authorship/std",
"pallet-babe/std",
"pallet-balances/std",
"pallet-beefy-mmr/std",
"pallet-beefy/std",
"pallet-bridge-beefy/std",
"pallet-bridge-grandpa/std",
"pallet-bridge-messages/std",
"pallet-bridge-relayers/std",
"pallet-grandpa/std",
"pallet-message-queue/std",
"pallet-mmr/std",
"pallet-offences/std",
"pallet-session/std",
"pallet-shift-session-manager/std",
"pallet-sudo/std",
"pallet-timestamp/std",
"pallet-transaction-payment-rpc-runtime-api/std",
"pallet-transaction-payment/std",
"pallet-xcm/std",
"polkadot-primitives/std",
"polkadot-runtime-common/std",
"polkadot-runtime-parachains/std",
"scale-info/std",
"sp-api/std",
"sp-authority-discovery/std",
"sp-block-builder/std",
"sp-consensus-babe/std",
"sp-consensus-beefy/std",
"sp-core/std",
"sp-inherents/std",
"sp-io/std",
"sp-offchain/std",
"sp-runtime/std",
"sp-session/std",
"sp-std/std",
"sp-transaction-pool/std",
"sp-version/std",
"xcm-builder/std",
"xcm-executor/std",
"xcm/std",
]
runtime-benchmarks = [
"bridge-runtime-common/runtime-benchmarks",
"frame-benchmarking/runtime-benchmarks",
"frame-support/runtime-benchmarks",
"frame-system/runtime-benchmarks",
"pallet-bridge-grandpa/runtime-benchmarks",
"pallet-bridge-messages/runtime-benchmarks",
"pallet-bridge-relayers/runtime-benchmarks",
"pallet-message-queue/runtime-benchmarks",
"pallet-xcm/runtime-benchmarks",
"polkadot-runtime-common/runtime-benchmarks",
"sp-runtime/runtime-benchmarks",
"xcm-builder/runtime-benchmarks",
]
-26
View File
@@ -1,26 +0,0 @@
// 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 substrate_wasm_builder::WasmBuilder;
fn main() {
WasmBuilder::new()
.with_current_project()
.import_memory()
.export_heap_base()
.disable_runtime_version_section_check()
.build()
}
File diff suppressed because it is too large Load Diff
@@ -1,200 +0,0 @@
// 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/>.
//! Everything required to serve Millau <-> Rialto messages.
use crate::{MillauGrandpaInstance, Runtime, RuntimeOrigin, WithMillauMessagesInstance};
use bp_messages::LaneId;
use bridge_runtime_common::{
messages::{
self, source::TargetHeaderChainAdapter, target::SourceHeaderChainAdapter, MessageBridge,
},
messages_xcm_extension::{SenderAndLane, XcmBlobHauler, XcmBlobHaulerAdapter},
};
use frame_support::{parameter_types, weights::Weight};
use sp_runtime::RuntimeDebug;
use xcm::latest::prelude::*;
use xcm_builder::HaulBlobExporter;
/// Lane that is used for XCM messages exchange.
pub const XCM_LANE: LaneId = LaneId([0, 0, 0, 0]);
/// Weight of 2 XCM instructions is for simple `Trap(42)` program, coming through bridge
/// (it is prepended with `UniversalOrigin` instruction). It is used just for simplest manual
/// tests, confirming that we don't break encoding somewhere between.
pub const BASE_XCM_WEIGHT_TWICE: Weight = crate::xcm_config::BaseXcmWeight::get().saturating_mul(2);
parameter_types! {
/// Weight credit for our test messages.
///
/// 2 XCM instructions is for simple `Trap(42)` program, coming through bridge
/// (it is prepended with `UniversalOrigin` instruction).
pub const WeightCredit: Weight = BASE_XCM_WEIGHT_TWICE;
/// Lane used by the with-Millau bridge.
pub MullauSenderAndLane: SenderAndLane = SenderAndLane::new(Here.into(), XCM_LANE);
/// Dummy message used in configuration.
pub DummyXcmMessage: Xcm<()> = Xcm::new();
}
/// Message payload for Rialto -> Millau messages.
pub type ToMillauMessagePayload = messages::source::FromThisChainMessagePayload;
/// Message verifier for Rialto -> Millau messages.
pub type ToMillauMessageVerifier =
messages::source::FromThisChainMessageVerifier<WithMillauMessageBridge>;
/// Message payload for Millau -> Rialto messages.
pub type FromMillauMessagePayload = messages::target::FromBridgedChainMessagePayload;
/// Call-dispatch based message dispatch for Millau -> Rialto messages.
pub type FromMillauMessageDispatch =
bridge_runtime_common::messages_xcm_extension::XcmBlobMessageDispatch<
crate::xcm_config::OnRialtoBlobDispatcher,
(),
(),
>;
/// Messages proof for Millau -> Rialto messages.
pub type FromMillauMessagesProof = messages::target::FromBridgedChainMessagesProof<bp_millau::Hash>;
/// Messages delivery proof for Rialto -> Millau messages.
pub type ToMillauMessagesDeliveryProof =
messages::source::FromBridgedChainMessagesDeliveryProof<bp_millau::Hash>;
/// Maximal outbound payload size of Rialto -> Millau messages.
pub type ToMillauMaximalOutboundPayloadSize =
messages::source::FromThisChainMaximalOutboundPayloadSize<WithMillauMessageBridge>;
/// Millau <-> Rialto message bridge.
#[derive(RuntimeDebug, Clone, Copy)]
pub struct WithMillauMessageBridge;
impl MessageBridge for WithMillauMessageBridge {
const BRIDGED_MESSAGES_PALLET_NAME: &'static str = bp_rialto::WITH_RIALTO_MESSAGES_PALLET_NAME;
type ThisChain = Rialto;
type BridgedChain = Millau;
type BridgedHeaderChain =
pallet_bridge_grandpa::GrandpaChainHeaders<Runtime, MillauGrandpaInstance>;
}
/// Rialto chain from message lane point of view.
#[derive(RuntimeDebug, Clone, Copy)]
pub struct Rialto;
impl messages::UnderlyingChainProvider for Rialto {
type Chain = bp_rialto::Rialto;
}
impl messages::ThisChainWithMessages for Rialto {
type RuntimeOrigin = RuntimeOrigin;
}
/// Millau chain from message lane point of view.
#[derive(RuntimeDebug, Clone, Copy)]
pub struct Millau;
/// Millau as source header chain.
pub type MillauAsSourceHeaderChain = SourceHeaderChainAdapter<WithMillauMessageBridge>;
/// Millau as target header chain.
pub type MillauAsTargetHeaderChain = TargetHeaderChainAdapter<WithMillauMessageBridge>;
impl messages::UnderlyingChainProvider for Millau {
type Chain = bp_millau::Millau;
}
impl messages::BridgedChainWithMessages for Millau {}
/// Export XCM messages to be relayed to Millau.
pub type ToMillauBlobExporter = HaulBlobExporter<
XcmBlobHaulerAdapter<ToMillauXcmBlobHauler>,
crate::xcm_config::MillauNetwork,
(),
>;
/// To-Millau XCM hauler.
pub struct ToMillauXcmBlobHauler;
impl XcmBlobHauler for ToMillauXcmBlobHauler {
type Runtime = Runtime;
type MessagesInstance = WithMillauMessagesInstance;
type SenderAndLane = MullauSenderAndLane;
type ToSourceChainSender = crate::xcm_config::XcmRouter;
type CongestedMessage = DummyXcmMessage;
type UncongestedMessage = DummyXcmMessage;
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{MillauGrandpaInstance, Runtime, WithMillauMessagesInstance};
use bridge_runtime_common::{
assert_complete_bridge_types,
integrity::{
assert_complete_bridge_constants, check_message_lane_weights,
AssertBridgeMessagesPalletConstants, AssertBridgePalletNames, AssertChainConstants,
AssertCompleteBridgeConstants,
},
};
#[test]
fn ensure_millau_message_lane_weights_are_correct() {
check_message_lane_weights::<bp_rialto::Rialto, Runtime, WithMillauMessagesInstance>(
bp_millau::EXTRA_STORAGE_PROOF_SIZE,
bp_rialto::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX,
bp_rialto::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX,
false,
);
}
#[test]
fn ensure_bridge_integrity() {
assert_complete_bridge_types!(
runtime: Runtime,
with_bridged_chain_grandpa_instance: MillauGrandpaInstance,
with_bridged_chain_messages_instance: WithMillauMessagesInstance,
bridge: WithMillauMessageBridge,
this_chain: bp_rialto::Rialto,
bridged_chain: bp_millau::Millau,
);
assert_complete_bridge_constants::<
Runtime,
MillauGrandpaInstance,
WithMillauMessagesInstance,
WithMillauMessageBridge,
>(AssertCompleteBridgeConstants {
this_chain_constants: AssertChainConstants {
block_length: bp_rialto::BlockLength::get(),
block_weights: bp_rialto::BlockWeights::get(),
},
messages_pallet_constants: AssertBridgeMessagesPalletConstants {
max_unrewarded_relayers_in_bridged_confirmation_tx:
bp_millau::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX,
max_unconfirmed_messages_in_bridged_confirmation_tx:
bp_millau::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX,
bridged_chain_id: bp_runtime::MILLAU_CHAIN_ID,
},
pallet_names: AssertBridgePalletNames {
with_this_chain_messages_pallet_name: bp_rialto::WITH_RIALTO_MESSAGES_PALLET_NAME,
with_bridged_chain_grandpa_pallet_name: bp_millau::WITH_MILLAU_GRANDPA_PALLET_NAME,
with_bridged_chain_messages_pallet_name:
bp_millau::WITH_MILLAU_MESSAGES_PALLET_NAME,
},
});
}
}
@@ -1,274 +0,0 @@
// 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/>.
//! Parachains support in Rialto runtime.
use crate::{
xcm_config, AccountId, Babe, Balance, Balances, BlockNumber, ParaAssignmentProvider, Registrar,
Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, ShiftSessionManager, Slots,
UncheckedExtrinsic,
};
use frame_support::{
parameter_types,
traits::{KeyOwnerProofSystem, ProcessMessage, ProcessMessageError},
weights::{Weight, WeightMeter},
};
use frame_system::EnsureRoot;
use polkadot_primitives::v6::{ValidatorId, ValidatorIndex};
use polkadot_runtime_common::{paras_registrar, paras_sudo_wrapper, slots};
use polkadot_runtime_parachains::{
configuration as parachains_configuration, disputes as parachains_disputes,
disputes::slashing as parachains_slashing,
dmp as parachains_dmp, hrmp as parachains_hrmp, inclusion as parachains_inclusion,
inclusion::{AggregateMessageOrigin, UmpQueueId},
initializer as parachains_initializer, origin as parachains_origin, paras as parachains_paras,
paras_inherent as parachains_paras_inherent, scheduler as parachains_scheduler,
session_info as parachains_session_info, shared as parachains_shared,
};
use sp_core::crypto::KeyTypeId;
use sp_runtime::transaction_validity::TransactionPriority;
use xcm::latest::Junction;
impl<C> frame_system::offchain::SendTransactionTypes<C> for Runtime
where
RuntimeCall: From<C>,
{
type Extrinsic = UncheckedExtrinsic;
type OverarchingCall = RuntimeCall;
}
/// Special `RewardValidators` that does nothing ;)
pub struct RewardValidators;
impl polkadot_runtime_parachains::inclusion::RewardValidators for RewardValidators {
fn reward_backing(_: impl IntoIterator<Item = ValidatorIndex>) {}
fn reward_bitfields(_: impl IntoIterator<Item = ValidatorIndex>) {}
}
// all required parachain modules from `polkadot-runtime-parachains` crate
impl parachains_configuration::Config for Runtime {
type WeightInfo = parachains_configuration::TestWeightInfo;
}
impl parachains_dmp::Config for Runtime {}
impl parachains_hrmp::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RuntimeOrigin = RuntimeOrigin;
type ChannelManager = EnsureRoot<Self::AccountId>;
type Currency = Balances;
type WeightInfo = parachains_hrmp::TestWeightInfo;
}
impl parachains_inclusion::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RewardValidators = RewardValidators;
type DisputesHandler = ();
type MessageQueue = crate::MessageQueue;
type WeightInfo = ();
}
impl parachains_initializer::Config for Runtime {
type Randomness = pallet_babe::RandomnessFromOneEpochAgo<Runtime>;
type ForceOrigin = EnsureRoot<AccountId>;
type WeightInfo = ();
}
impl parachains_disputes::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RewardValidators = ();
type SlashingHandler = ();
type WeightInfo = parachains_disputes::TestWeightInfo;
}
impl parachains_slashing::Config for Runtime {
type KeyOwnerProofSystem = ();
type KeyOwnerProof =
<Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, ValidatorId)>>::Proof;
type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
KeyTypeId,
ValidatorId,
)>>::IdentificationTuple;
type HandleReports = ();
type WeightInfo = parachains_slashing::TestWeightInfo;
type BenchmarkingConfig = parachains_slashing::BenchConfig<200>;
}
impl parachains_origin::Config for Runtime {}
parameter_types! {
pub const ParasUnsignedPriority: TransactionPriority = TransactionPriority::max_value();
}
impl parachains_paras::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type WeightInfo = ParasWeightInfo;
type UnsignedPriority = ParasUnsignedPriority;
type QueueFootprinter = crate::ParaInclusion;
type NextSessionRotation = Babe;
type OnNewHead = Registrar;
}
/// Test weight for the `Paras` pallet.
///
/// We can't use `parachains_paras::TestWeightInfo` anymore, because it returns `Weight::MAX`
/// where we need some real-world weights. We'll use zero weights here, though to avoid
/// adding benchmarks to Rialto runtime.
pub struct ParasWeightInfo;
impl parachains_paras::WeightInfo for ParasWeightInfo {
fn force_set_current_code(_c: u32) -> Weight {
Weight::zero()
}
fn force_set_current_head(_s: u32) -> Weight {
Weight::zero()
}
fn force_set_most_recent_context() -> Weight {
Weight::zero()
}
fn force_schedule_code_upgrade(_c: u32) -> Weight {
Weight::zero()
}
fn force_note_new_head(_s: u32) -> Weight {
Weight::zero()
}
fn force_queue_action() -> Weight {
Weight::zero()
}
fn add_trusted_validation_code(_c: u32) -> Weight {
Weight::zero()
}
fn poke_unused_validation_code() -> Weight {
Weight::zero()
}
fn include_pvf_check_statement_finalize_upgrade_accept() -> Weight {
Weight::zero()
}
fn include_pvf_check_statement_finalize_upgrade_reject() -> Weight {
Weight::zero()
}
fn include_pvf_check_statement_finalize_onboarding_accept() -> Weight {
Weight::zero()
}
fn include_pvf_check_statement_finalize_onboarding_reject() -> Weight {
Weight::zero()
}
fn include_pvf_check_statement() -> Weight {
Weight::zero()
}
}
impl parachains_paras_inherent::Config for Runtime {
type WeightInfo = parachains_paras_inherent::TestWeightInfo;
}
impl polkadot_runtime_parachains::assigner_parachains::Config for Runtime {}
impl parachains_scheduler::Config for Runtime {
type AssignmentProvider = ParaAssignmentProvider;
}
impl parachains_session_info::Config for Runtime {
type ValidatorSet = ShiftSessionManager;
}
impl parachains_shared::Config for Runtime {}
parameter_types! {
/// Amount of weight that can be spent per block to service messages.
///
/// # WARNING
///
/// This is not a good value for para-chains since the `Scheduler`
/// already uses up to 80 percent block weight.
pub MessageQueueServiceWeight: Weight = crate::Perbill::from_percent(20) * bp_rialto::BlockWeights::get().max_block;
pub const MessageQueueHeapSize: u32 = 32 * 1024;
pub const MessageQueueMaxStale: u32 = 96;
}
/// Message processor to handle any messages that were enqueued into the `MessageQueue` pallet.
pub struct MessageProcessor;
impl ProcessMessage for MessageProcessor {
type Origin = AggregateMessageOrigin;
fn process_message(
message: &[u8],
origin: Self::Origin,
meter: &mut WeightMeter,
id: &mut [u8; 32],
) -> Result<bool, ProcessMessageError> {
let para = match origin {
AggregateMessageOrigin::Ump(UmpQueueId::Para(para)) => para,
};
xcm_builder::ProcessXcmMessage::<
Junction,
xcm_executor::XcmExecutor<xcm_config::XcmConfig>,
RuntimeCall,
>::process_message(message, Junction::Parachain(para.into()), meter, id)
}
}
impl pallet_message_queue::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Size = u32;
type HeapSize = MessageQueueHeapSize;
type MaxStale = MessageQueueMaxStale;
type ServiceWeight = MessageQueueServiceWeight;
#[cfg(not(feature = "runtime-benchmarks"))]
type MessageProcessor = MessageProcessor;
#[cfg(feature = "runtime-benchmarks")]
type MessageProcessor =
pallet_message_queue::mock_helpers::NoopMessageProcessor<AggregateMessageOrigin>;
type QueueChangeHandler = crate::ParaInclusion;
type WeightInfo = ();
type QueuePausedQuery = ();
}
// required onboarding pallets. We're not going to use auctions or crowdloans, so they're missing
parameter_types! {
pub const ParaDeposit: Balance = 0;
pub const DataDepositPerByte: Balance = 0;
}
impl paras_registrar::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RuntimeOrigin = RuntimeOrigin;
type Currency = Balances;
type OnSwap = Slots;
type ParaDeposit = ParaDeposit;
type DataDepositPerByte = DataDepositPerByte;
type WeightInfo = paras_registrar::TestWeightInfo;
}
parameter_types! {
pub const LeasePeriod: BlockNumber = 10 * bp_rialto::MINUTES;
}
impl slots::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Currency = Balances;
type Registrar = Registrar;
type LeasePeriod = LeasePeriod;
type WeightInfo = slots::TestWeightInfo;
type LeaseOffset = ();
type ForceOrigin = EnsureRoot<AccountId>;
}
impl paras_sudo_wrapper::Config for Runtime {}
@@ -1,280 +0,0 @@
// 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/>.
//! XCM configurations for the Rialto runtime.
use super::{
millau_messages::ToMillauBlobExporter, AccountId, AllPalletsWithSystem, Balances, Runtime,
RuntimeCall, RuntimeEvent, RuntimeOrigin, XcmPallet,
};
use bp_rialto::WeightToFee;
use bridge_runtime_common::CustomNetworkId;
use frame_support::{
parameter_types,
traits::{ConstU32, Everything, Nothing},
weights::Weight,
};
use frame_system::EnsureRoot;
use xcm::latest::prelude::*;
use xcm_builder::{
AccountId32Aliases, CurrencyAdapter as XcmCurrencyAdapter, IsConcrete, MintLocation,
SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,
UsingComponents,
};
parameter_types! {
/// The location of the `MLAU` token, from the context of this chain. Since this token is native to this
/// chain, we make it synonymous with it and thus it is the `Here` location, which means "equivalent to
/// the context".
pub const TokenLocation: MultiLocation = Here.into_location();
/// The Rialto network ID.
pub const ThisNetwork: NetworkId = CustomNetworkId::Rialto.as_network_id();
/// The Millau network ID.
pub const MillauNetwork: NetworkId = CustomNetworkId::Millau.as_network_id();
/// Our XCM location ancestry - i.e. our location within the Consensus Universe.
///
/// Since Polkadot is a top-level relay-chain with its own consensus, it's just our network ID.
pub UniversalLocation: InteriorMultiLocation = ThisNetwork::get().into();
/// The check account, which holds any native assets that have been teleported out and not back in (yet).
pub CheckAccount: (AccountId, MintLocation) = (XcmPallet::check_account(), MintLocation::Local);
}
/// The canonical means of converting a `MultiLocation` into an `AccountId`, used when we want to
/// determine the sovereign account controlled by a location.
pub type SovereignAccountOf = (
// We can directly alias an `AccountId32` into a local account.
AccountId32Aliases<ThisNetwork, AccountId>,
);
/// Our asset transactor. This is what allows us to interest with the runtime facilities from the
/// point of view of XCM-only concepts like `MultiLocation` and `MultiAsset`.
///
/// Ours is only aware of the Balances pallet, which is mapped to `TokenLocation`.
pub type LocalAssetTransactor = XcmCurrencyAdapter<
// Use this currency:
Balances,
// Use this currency when it is a fungible asset matching the given location or name:
IsConcrete<TokenLocation>,
// We can convert the MultiLocations with our converter above:
SovereignAccountOf,
// Our chain's account ID type (we can't get away without mentioning it explicitly):
AccountId,
// We track our teleports in/out to keep total issuance correct.
CheckAccount,
>;
/// The means that we convert the XCM message origin location into a local dispatch origin.
type LocalOriginConverter = (
// A `Signed` origin of the sovereign account that the original location controls.
SovereignSignedViaLocation<SovereignAccountOf, RuntimeOrigin>,
// The AccountId32 location type can be expressed natively as a `Signed` origin.
SignedAccountId32AsNative<ThisNetwork, RuntimeOrigin>,
);
parameter_types! {
/// The amount of weight an XCM operation takes. This is a safe overestimate.
pub const BaseXcmWeight: Weight = Weight::from_parts(1_000_000_000, 64 * 1024);
/// Maximum number of instructions in a single XCM fragment. A sanity check against weight
/// calculations getting too crazy.
pub const MaxInstructions: u32 = 100;
}
/// The XCM router. We are not sending messages to sibling/parent/child chains here.
pub type XcmRouter = ();
/// The barriers one of which must be passed for an XCM message to be executed.
pub type Barrier = (
// Weight that is paid for may be consumed.
TakeWeightCredit,
);
/// Dispatches received XCM messages from other chain.
pub type OnRialtoBlobDispatcher = xcm_builder::BridgeBlobDispatcher<
crate::xcm_config::XcmRouter,
crate::xcm_config::UniversalLocation,
(),
>;
/// Incoming XCM weigher type.
pub type XcmWeigher = xcm_builder::FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
pub struct XcmConfig;
impl xcm_executor::Config for XcmConfig {
type RuntimeCall = RuntimeCall;
type XcmSender = ();
type AssetTransactor = LocalAssetTransactor;
type OriginConverter = LocalOriginConverter;
type IsReserve = ();
type IsTeleporter = ();
type UniversalLocation = UniversalLocation;
type Barrier = Barrier;
type Weigher = XcmWeigher;
// The weight trader piggybacks on the existing transaction-fee conversion logic.
type Trader = UsingComponents<WeightToFee, TokenLocation, AccountId, Balances, ()>;
type ResponseHandler = XcmPallet;
type AssetTrap = XcmPallet;
type AssetLocker = ();
type AssetExchanger = ();
type AssetClaims = XcmPallet;
type SubscriptionService = XcmPallet;
type PalletInstancesInfo = AllPalletsWithSystem;
type MaxAssetsIntoHolding = ConstU32<64>;
type FeeManager = ();
type MessageExporter = ToMillauBlobExporter;
type UniversalAliases = Nothing;
type CallDispatcher = RuntimeCall;
type SafeCallFilter = Everything;
type Aliasers = Nothing;
}
/// Type to convert an `Origin` type value into a `MultiLocation` value which represents an interior
/// location of this chain.
pub type LocalOriginToLocation = (
// Usual Signed origin to be used in XCM as a corresponding AccountId32
SignedToAccountId32<RuntimeOrigin, AccountId, ThisNetwork>,
);
#[cfg(feature = "runtime-benchmarks")]
parameter_types! {
pub ReachableDest: Option<MultiLocation> = None;
}
impl pallet_xcm::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
// We don't allow any messages to be sent via the transaction yet. This is basically safe to
// enable, (safe the possibility of someone spamming the parachain if they're willing to pay
// the DOT to send from the Relay-chain). But it's useless until we bring in XCM v3 which will
// make `DescendOrigin` a bit more useful.
type SendXcmOrigin = xcm_builder::EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
type XcmRouter = XcmRouter;
// Anyone can execute XCM messages locally.
type ExecuteXcmOrigin = xcm_builder::EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
type XcmExecuteFilter = Everything;
type XcmExecutor = xcm_executor::XcmExecutor<XcmConfig>;
// Anyone is able to use teleportation regardless of who they are and what they want to
// teleport.
type XcmTeleportFilter = Everything;
// Anyone is able to use reserve transfers regardless of who they are and what they want to
// transfer.
type XcmReserveTransferFilter = Everything;
type Weigher = XcmWeigher;
type UniversalLocation = UniversalLocation;
type RuntimeOrigin = RuntimeOrigin;
type RuntimeCall = RuntimeCall;
const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
type Currency = Balances;
type CurrencyMatcher = ();
type TrustedLockers = ();
type SovereignAccountOf = SovereignAccountOf;
type MaxLockers = frame_support::traits::ConstU32<8>;
type WeightInfo = pallet_xcm::TestWeightInfo;
#[cfg(feature = "runtime-benchmarks")]
type ReachableDest = ReachableDest;
type AdminOrigin = EnsureRoot<AccountId>;
type MaxRemoteLockConsumers = ConstU32<0>;
type RemoteLockConsumerIdentifier = ();
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
millau_messages::{FromMillauMessageDispatch, XCM_LANE},
WithMillauMessagesInstance,
};
use bp_messages::{
target_chain::{DispatchMessage, DispatchMessageData, MessageDispatch},
LaneId, MessageKey,
};
use bridge_runtime_common::messages_xcm_extension::XcmBlobMessageDispatchResult;
use codec::Encode;
use pallet_bridge_messages::OutboundLanes;
use sp_runtime::BuildStorage;
use xcm_executor::XcmExecutor;
fn new_test_ext() -> sp_io::TestExternalities {
sp_io::TestExternalities::new(
frame_system::GenesisConfig::<Runtime>::default().build_storage().unwrap(),
)
}
fn prepare_outbound_xcm_message(destination: NetworkId) -> Xcm<RuntimeCall> {
vec![ExportMessage {
network: destination,
destination: destination.into(),
xcm: vec![Instruction::Trap(42)].into(),
}]
.into()
}
#[test]
fn xcm_messages_to_millau_are_sent_using_bridge_exporter() {
new_test_ext().execute_with(|| {
// ensure that the there are no messages queued
assert_eq!(
OutboundLanes::<Runtime, WithMillauMessagesInstance>::get(XCM_LANE)
.latest_generated_nonce,
0,
);
// export message instruction "sends" message to Rialto
XcmExecutor::<XcmConfig>::execute_xcm_in_credit(
Here,
prepare_outbound_xcm_message(MillauNetwork::get()),
Default::default(),
Weight::MAX,
Weight::MAX,
)
.ensure_complete()
.expect("runtime configuration must be correct");
// ensure that the message has been queued
assert_eq!(
OutboundLanes::<Runtime, WithMillauMessagesInstance>::get(XCM_LANE)
.latest_generated_nonce,
1,
);
})
}
fn prepare_inbound_bridge_message() -> DispatchMessage<Vec<u8>> {
let xcm = xcm::VersionedXcm::<RuntimeCall>::V3(vec![Instruction::Trap(42)].into());
let location =
xcm::VersionedInteriorMultiLocation::V3(X1(GlobalConsensus(ThisNetwork::get())));
// this is the `BridgeMessage` from polkadot xcm builder, but it has no constructor
// or public fields, so just tuple
let bridge_message = (location, xcm).encode();
DispatchMessage {
key: MessageKey { lane_id: LaneId([0, 0, 0, 0]), nonce: 1 },
data: DispatchMessageData { payload: Ok(bridge_message) },
}
}
#[test]
fn xcm_messages_from_millau_are_dispatched() {
let incoming_message = prepare_inbound_bridge_message();
// we care only about handing message to the XCM dispatcher, so we don't care about its
// actual dispatch
let dispatch_result = FromMillauMessageDispatch::dispatch(incoming_message);
assert!(matches!(
dispatch_result.dispatch_level_result,
XcmBlobMessageDispatchResult::NotDispatched(_),
));
}
}
+2 -39
View File
@@ -22,7 +22,6 @@ use crate::messages_call_ext::MessagesCallSubType;
use pallet_bridge_grandpa::CallSubType as GrandpaCallSubType;
use pallet_bridge_parachains::CallSubType as ParachainsCallSubtype;
use sp_runtime::transaction_validity::TransactionValidity;
use xcm::v3::NetworkId;
pub mod messages;
pub mod messages_api;
@@ -92,8 +91,8 @@ where
/// ```nocompile
/// generate_bridge_reject_obsolete_headers_and_messages!{
/// Call, AccountId
/// BridgeRialtoGrandpa, BridgeWestendGrandpa,
/// BridgeRialtoParachains
/// BridgeRococoGrandpa, BridgeRococoMessages,
/// BridgeRococoParachains
/// }
/// ```
///
@@ -147,42 +146,6 @@ macro_rules! generate_bridge_reject_obsolete_headers_and_messages {
};
}
/// A mapping over `NetworkId`.
/// Since `NetworkId` doesn't include `Millau`, `Rialto` and `RialtoParachain`, we create some
/// synthetic associations between these chains and `NetworkId` chains.
pub enum CustomNetworkId {
/// The Millau network ID, associated with Kusama.
Millau,
/// The Rialto network ID, associated with Polkadot.
Rialto,
/// The RialtoParachain network ID, associated with Westend.
RialtoParachain,
}
impl TryFrom<bp_runtime::ChainId> for CustomNetworkId {
type Error = ();
fn try_from(chain: bp_runtime::ChainId) -> Result<Self, Self::Error> {
Ok(match chain {
bp_runtime::MILLAU_CHAIN_ID => Self::Millau,
bp_runtime::RIALTO_CHAIN_ID => Self::Rialto,
bp_runtime::RIALTO_PARACHAIN_CHAIN_ID => Self::RialtoParachain,
_ => return Err(()),
})
}
}
impl CustomNetworkId {
/// Converts self to XCM' network id.
pub const fn as_network_id(&self) -> NetworkId {
match *self {
CustomNetworkId::Millau => NetworkId::Kusama,
CustomNetworkId::Rialto => NetworkId::Polkadot,
CustomNetworkId::RialtoParachain => NetworkId::Westend,
}
}
}
#[cfg(test)]
mod tests {
use crate::BridgeRuntimeFilterCall;
+1 -6
View File
@@ -14,12 +14,7 @@
// 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/>.
//! A mock runtime for testing different stuff in the crate. We've been using Millau
//! runtime for that before, but it has two drawbacks:
//!
//! - circular dependencies between this crate and Millau runtime;
//!
//! - we can't use (e.g. as git subtree or by copying) this crate in repo without Millau.
//! A mock runtime for testing different stuff in the crate.
#![cfg(test)]
@@ -27,6 +27,7 @@ use frame_support::traits::Get;
use sp_runtime::transaction_validity::TransactionPriority;
// reexport everything from `integrity_tests` module
#[allow(unused_imports)]
pub use integrity_tests::*;
/// Compute priority boost for message delivery transaction that delivers
+1 -1
View File
@@ -1,7 +1,7 @@
# High-Level Bridge Documentation
This document gives a brief, abstract description of main components that may be found in this repository. If you want
to see how we're using them to build Rococo <> Wococo (Kusama <> Polkadot) bridge, please refer to the [Polkadot <>
to see how we're using them to build Rococo <> Westend (Kusama <> Polkadot) bridge, please refer to the [Polkadot <>
Kusama Bridge](./polkadot-kusama-bridge-overview.md).
## Purpose
+31 -31
View File
@@ -23,7 +23,7 @@
//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024
// Executed Command:
// target/release/millau-bridge-node
// target/release/unknown-bridge-node
// benchmark
// pallet
// --chain=dev
@@ -58,39 +58,39 @@ pub trait WeightInfo {
/// Those weights are test only and must never be used in production.
pub struct BridgeWeight<T>(PhantomData<T>);
impl<T: frame_system::Config> WeightInfo for BridgeWeight<T> {
/// Storage: BridgeRialtoGrandpa PalletOperatingMode (r:1 w:0)
/// Storage: BridgeUnknownGrandpa PalletOperatingMode (r:1 w:0)
///
/// Proof: BridgeRialtoGrandpa PalletOperatingMode (max_values: Some(1), max_size: Some(1),
/// Proof: BridgeUnknownGrandpa PalletOperatingMode (max_values: Some(1), max_size: Some(1),
/// added: 496, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoGrandpa RequestCount (r:1 w:1)
/// Storage: BridgeUnknownGrandpa RequestCount (r:1 w:1)
///
/// Proof: BridgeRialtoGrandpa RequestCount (max_values: Some(1), max_size: Some(4), added: 499,
/// mode: MaxEncodedLen)
/// Proof: BridgeUnknownGrandpa RequestCount (max_values: Some(1), max_size: Some(4), added:
/// 499, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoGrandpa BestFinalized (r:1 w:1)
/// Storage: BridgeUnknownGrandpa BestFinalized (r:1 w:1)
///
/// Proof: BridgeRialtoGrandpa BestFinalized (max_values: Some(1), max_size: Some(36), added:
/// Proof: BridgeUnknownGrandpa BestFinalized (max_values: Some(1), max_size: Some(36), added:
/// 531, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoGrandpa CurrentAuthoritySet (r:1 w:0)
/// Storage: BridgeUnknownGrandpa CurrentAuthoritySet (r:1 w:0)
///
/// Proof: BridgeRialtoGrandpa CurrentAuthoritySet (max_values: Some(1), max_size: Some(209),
/// Proof: BridgeUnknownGrandpa CurrentAuthoritySet (max_values: Some(1), max_size: Some(209),
/// added: 704, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoGrandpa ImportedHashesPointer (r:1 w:1)
/// Storage: BridgeUnknownGrandpa ImportedHashesPointer (r:1 w:1)
///
/// Proof: BridgeRialtoGrandpa ImportedHashesPointer (max_values: Some(1), max_size: Some(4),
/// Proof: BridgeUnknownGrandpa ImportedHashesPointer (max_values: Some(1), max_size: Some(4),
/// added: 499, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoGrandpa ImportedHashes (r:1 w:1)
/// Storage: BridgeUnknownGrandpa ImportedHashes (r:1 w:1)
///
/// Proof: BridgeRialtoGrandpa ImportedHashes (max_values: Some(14400), max_size: Some(36),
/// Proof: BridgeUnknownGrandpa ImportedHashes (max_values: Some(14400), max_size: Some(36),
/// added: 2016, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoGrandpa ImportedHeaders (r:0 w:2)
/// Storage: BridgeUnknownGrandpa ImportedHeaders (r:0 w:2)
///
/// Proof: BridgeRialtoGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// Proof: BridgeUnknownGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// added: 2048, mode: MaxEncodedLen)
///
/// The range of component `p` is `[1, 4]`.
@@ -113,39 +113,39 @@ impl<T: frame_system::Config> WeightInfo for BridgeWeight<T> {
// For backwards compatibility and tests
impl WeightInfo for () {
/// Storage: BridgeRialtoGrandpa PalletOperatingMode (r:1 w:0)
/// Storage: BridgeUnknownGrandpa PalletOperatingMode (r:1 w:0)
///
/// Proof: BridgeRialtoGrandpa PalletOperatingMode (max_values: Some(1), max_size: Some(1),
/// Proof: BridgeUnknownGrandpa PalletOperatingMode (max_values: Some(1), max_size: Some(1),
/// added: 496, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoGrandpa RequestCount (r:1 w:1)
/// Storage: BridgeUnknownGrandpa RequestCount (r:1 w:1)
///
/// Proof: BridgeRialtoGrandpa RequestCount (max_values: Some(1), max_size: Some(4), added: 499,
/// mode: MaxEncodedLen)
/// Proof: BridgeUnknownGrandpa RequestCount (max_values: Some(1), max_size: Some(4), added:
/// 499, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoGrandpa BestFinalized (r:1 w:1)
/// Storage: BridgeUnknownGrandpa BestFinalized (r:1 w:1)
///
/// Proof: BridgeRialtoGrandpa BestFinalized (max_values: Some(1), max_size: Some(36), added:
/// Proof: BridgeUnknownGrandpa BestFinalized (max_values: Some(1), max_size: Some(36), added:
/// 531, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoGrandpa CurrentAuthoritySet (r:1 w:0)
/// Storage: BridgeUnknownGrandpa CurrentAuthoritySet (r:1 w:0)
///
/// Proof: BridgeRialtoGrandpa CurrentAuthoritySet (max_values: Some(1), max_size: Some(209),
/// Proof: BridgeUnknownGrandpa CurrentAuthoritySet (max_values: Some(1), max_size: Some(209),
/// added: 704, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoGrandpa ImportedHashesPointer (r:1 w:1)
/// Storage: BridgeUnknownGrandpa ImportedHashesPointer (r:1 w:1)
///
/// Proof: BridgeRialtoGrandpa ImportedHashesPointer (max_values: Some(1), max_size: Some(4),
/// Proof: BridgeUnknownGrandpa ImportedHashesPointer (max_values: Some(1), max_size: Some(4),
/// added: 499, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoGrandpa ImportedHashes (r:1 w:1)
/// Storage: BridgeUnknownGrandpa ImportedHashes (r:1 w:1)
///
/// Proof: BridgeRialtoGrandpa ImportedHashes (max_values: Some(14400), max_size: Some(36),
/// Proof: BridgeUnknownGrandpa ImportedHashes (max_values: Some(14400), max_size: Some(36),
/// added: 2016, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoGrandpa ImportedHeaders (r:0 w:2)
/// Storage: BridgeUnknownGrandpa ImportedHeaders (r:0 w:2)
///
/// Proof: BridgeRialtoGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// Proof: BridgeUnknownGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// added: 2048, mode: MaxEncodedLen)
///
/// The range of component `p` is `[1, 4]`.
+113 -113
View File
@@ -14,7 +14,7 @@
// 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/>.
//! Autogenerated weights for RialtoMessages
//! Autogenerated weights for pallet_bridge_messages
//!
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
//! DATE: 2023-03-23, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]`
@@ -23,13 +23,13 @@
//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024
// Executed Command:
// target/release/millau-bridge-node
// target/release/unknown-bridge-node
// benchmark
// pallet
// --chain=dev
// --steps=50
// --repeat=20
// --pallet=RialtoMessages
// --pallet=pallet_bridge_messages
// --extrinsic=*
// --execution=wasm
// --wasm-execution=Compiled
@@ -48,7 +48,7 @@ use frame_support::{
};
use sp_std::marker::PhantomData;
/// Weight functions needed for RialtoMessages.
/// Weight functions needed for pallet_bridge_messages.
pub trait WeightInfo {
fn receive_single_message_proof() -> Weight;
fn receive_two_messages_proof() -> Weight;
@@ -61,24 +61,24 @@ pub trait WeightInfo {
fn receive_single_message_proof_with_dispatch(i: u32) -> Weight;
}
/// Weights for `RialtoMessages` that are generated using one of the Bridge testnets.
/// Weights for `pallet_bridge_messages` that are generated using one of the Bridge testnets.
///
/// Those weights are test only and must never be used in production.
pub struct BridgeWeight<T>(PhantomData<T>);
impl<T: frame_system::Config> WeightInfo for BridgeWeight<T> {
/// Storage: BridgeRialtoMessages PalletOperatingMode (r:1 w:0)
/// Storage: BridgeUnknownMessages PalletOperatingMode (r:1 w:0)
///
/// Proof: BridgeRialtoMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2),
/// Proof: BridgeUnknownMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2),
/// added: 497, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoGrandpa ImportedHeaders (r:1 w:0)
/// Storage: BridgeUnknownGrandpa ImportedHeaders (r:1 w:0)
///
/// Proof: BridgeRialtoGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// Proof: BridgeUnknownGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// added: 2048, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoMessages InboundLanes (r:1 w:1)
/// Storage: BridgeUnknownMessages InboundLanes (r:1 w:1)
///
/// Proof: BridgeRialtoMessages InboundLanes (max_values: None, max_size: Some(49180), added:
/// Proof: BridgeUnknownMessages InboundLanes (max_values: None, max_size: Some(49180), added:
/// 51655, mode: MaxEncodedLen)
fn receive_single_message_proof() -> Weight {
// Proof Size summary in bytes:
@@ -89,19 +89,19 @@ impl<T: frame_system::Config> WeightInfo for BridgeWeight<T> {
.saturating_add(T::DbWeight::get().reads(3_u64))
.saturating_add(T::DbWeight::get().writes(1_u64))
}
/// Storage: BridgeRialtoMessages PalletOperatingMode (r:1 w:0)
/// Storage: BridgeUnknownMessages PalletOperatingMode (r:1 w:0)
///
/// Proof: BridgeRialtoMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2),
/// Proof: BridgeUnknownMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2),
/// added: 497, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoGrandpa ImportedHeaders (r:1 w:0)
/// Storage: BridgeUnknownGrandpa ImportedHeaders (r:1 w:0)
///
/// Proof: BridgeRialtoGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// Proof: BridgeUnknownGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// added: 2048, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoMessages InboundLanes (r:1 w:1)
/// Storage: BridgeUnknownMessages InboundLanes (r:1 w:1)
///
/// Proof: BridgeRialtoMessages InboundLanes (max_values: None, max_size: Some(49180), added:
/// Proof: BridgeUnknownMessages InboundLanes (max_values: None, max_size: Some(49180), added:
/// 51655, mode: MaxEncodedLen)
fn receive_two_messages_proof() -> Weight {
// Proof Size summary in bytes:
@@ -112,19 +112,19 @@ impl<T: frame_system::Config> WeightInfo for BridgeWeight<T> {
.saturating_add(T::DbWeight::get().reads(3_u64))
.saturating_add(T::DbWeight::get().writes(1_u64))
}
/// Storage: BridgeRialtoMessages PalletOperatingMode (r:1 w:0)
/// Storage: BridgeUnknownMessages PalletOperatingMode (r:1 w:0)
///
/// Proof: BridgeRialtoMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2),
/// Proof: BridgeUnknownMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2),
/// added: 497, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoGrandpa ImportedHeaders (r:1 w:0)
/// Storage: BridgeUnknownGrandpa ImportedHeaders (r:1 w:0)
///
/// Proof: BridgeRialtoGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// Proof: BridgeUnknownGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// added: 2048, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoMessages InboundLanes (r:1 w:1)
/// Storage: BridgeUnknownMessages InboundLanes (r:1 w:1)
///
/// Proof: BridgeRialtoMessages InboundLanes (max_values: None, max_size: Some(49180), added:
/// Proof: BridgeUnknownMessages InboundLanes (max_values: None, max_size: Some(49180), added:
/// 51655, mode: MaxEncodedLen)
fn receive_single_message_proof_with_outbound_lane_state() -> Weight {
// Proof Size summary in bytes:
@@ -135,19 +135,19 @@ impl<T: frame_system::Config> WeightInfo for BridgeWeight<T> {
.saturating_add(T::DbWeight::get().reads(3_u64))
.saturating_add(T::DbWeight::get().writes(1_u64))
}
/// Storage: BridgeRialtoMessages PalletOperatingMode (r:1 w:0)
/// Storage: BridgeUnknownMessages PalletOperatingMode (r:1 w:0)
///
/// Proof: BridgeRialtoMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2),
/// Proof: BridgeUnknownMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2),
/// added: 497, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoGrandpa ImportedHeaders (r:1 w:0)
/// Storage: BridgeUnknownGrandpa ImportedHeaders (r:1 w:0)
///
/// Proof: BridgeRialtoGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// Proof: BridgeUnknownGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// added: 2048, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoMessages InboundLanes (r:1 w:1)
/// Storage: BridgeUnknownMessages InboundLanes (r:1 w:1)
///
/// Proof: BridgeRialtoMessages InboundLanes (max_values: None, max_size: Some(49180), added:
/// Proof: BridgeUnknownMessages InboundLanes (max_values: None, max_size: Some(49180), added:
/// 51655, mode: MaxEncodedLen)
fn receive_single_message_proof_1_kb() -> Weight {
// Proof Size summary in bytes:
@@ -158,19 +158,19 @@ impl<T: frame_system::Config> WeightInfo for BridgeWeight<T> {
.saturating_add(T::DbWeight::get().reads(3_u64))
.saturating_add(T::DbWeight::get().writes(1_u64))
}
/// Storage: BridgeRialtoMessages PalletOperatingMode (r:1 w:0)
/// Storage: BridgeUnknownMessages PalletOperatingMode (r:1 w:0)
///
/// Proof: BridgeRialtoMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2),
/// Proof: BridgeUnknownMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2),
/// added: 497, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoGrandpa ImportedHeaders (r:1 w:0)
/// Storage: BridgeUnknownGrandpa ImportedHeaders (r:1 w:0)
///
/// Proof: BridgeRialtoGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// Proof: BridgeUnknownGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// added: 2048, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoMessages InboundLanes (r:1 w:1)
/// Storage: BridgeUnknownMessages InboundLanes (r:1 w:1)
///
/// Proof: BridgeRialtoMessages InboundLanes (max_values: None, max_size: Some(49180), added:
/// Proof: BridgeUnknownMessages InboundLanes (max_values: None, max_size: Some(49180), added:
/// 51655, mode: MaxEncodedLen)
fn receive_single_message_proof_16_kb() -> Weight {
// Proof Size summary in bytes:
@@ -181,19 +181,19 @@ impl<T: frame_system::Config> WeightInfo for BridgeWeight<T> {
.saturating_add(T::DbWeight::get().reads(3_u64))
.saturating_add(T::DbWeight::get().writes(1_u64))
}
/// Storage: BridgeRialtoMessages PalletOperatingMode (r:1 w:0)
/// Storage: BridgeUnknownMessages PalletOperatingMode (r:1 w:0)
///
/// Proof: BridgeRialtoMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2),
/// Proof: BridgeUnknownMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2),
/// added: 497, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoGrandpa ImportedHeaders (r:1 w:0)
/// Storage: BridgeUnknownGrandpa ImportedHeaders (r:1 w:0)
///
/// Proof: BridgeRialtoGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// Proof: BridgeUnknownGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// added: 2048, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoMessages OutboundLanes (r:1 w:1)
/// Storage: BridgeUnknownMessages OutboundLanes (r:1 w:1)
///
/// Proof: BridgeRialtoMessages OutboundLanes (max_values: Some(1), max_size: Some(44), added:
/// Proof: BridgeUnknownMessages OutboundLanes (max_values: Some(1), max_size: Some(44), added:
/// 539, mode: MaxEncodedLen)
///
/// Storage: BridgeRelayers RelayerRewards (r:1 w:1)
@@ -209,19 +209,19 @@ impl<T: frame_system::Config> WeightInfo for BridgeWeight<T> {
.saturating_add(T::DbWeight::get().reads(4_u64))
.saturating_add(T::DbWeight::get().writes(2_u64))
}
/// Storage: BridgeRialtoMessages PalletOperatingMode (r:1 w:0)
/// Storage: BridgeUnknownMessages PalletOperatingMode (r:1 w:0)
///
/// Proof: BridgeRialtoMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2),
/// Proof: BridgeUnknownMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2),
/// added: 497, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoGrandpa ImportedHeaders (r:1 w:0)
/// Storage: BridgeUnknownGrandpa ImportedHeaders (r:1 w:0)
///
/// Proof: BridgeRialtoGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// Proof: BridgeUnknownGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// added: 2048, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoMessages OutboundLanes (r:1 w:1)
/// Storage: BridgeUnknownMessages OutboundLanes (r:1 w:1)
///
/// Proof: BridgeRialtoMessages OutboundLanes (max_values: Some(1), max_size: Some(44), added:
/// Proof: BridgeUnknownMessages OutboundLanes (max_values: Some(1), max_size: Some(44), added:
/// 539, mode: MaxEncodedLen)
///
/// Storage: BridgeRelayers RelayerRewards (r:1 w:1)
@@ -237,19 +237,19 @@ impl<T: frame_system::Config> WeightInfo for BridgeWeight<T> {
.saturating_add(T::DbWeight::get().reads(4_u64))
.saturating_add(T::DbWeight::get().writes(2_u64))
}
/// Storage: BridgeRialtoMessages PalletOperatingMode (r:1 w:0)
/// Storage: BridgeUnknownMessages PalletOperatingMode (r:1 w:0)
///
/// Proof: BridgeRialtoMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2),
/// Proof: BridgeUnknownMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2),
/// added: 497, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoGrandpa ImportedHeaders (r:1 w:0)
/// Storage: BridgeUnknownGrandpa ImportedHeaders (r:1 w:0)
///
/// Proof: BridgeRialtoGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// Proof: BridgeUnknownGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// added: 2048, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoMessages OutboundLanes (r:1 w:1)
/// Storage: BridgeUnknownMessages OutboundLanes (r:1 w:1)
///
/// Proof: BridgeRialtoMessages OutboundLanes (max_values: Some(1), max_size: Some(44), added:
/// Proof: BridgeUnknownMessages OutboundLanes (max_values: Some(1), max_size: Some(44), added:
/// 539, mode: MaxEncodedLen)
///
/// Storage: BridgeRelayers RelayerRewards (r:2 w:2)
@@ -265,19 +265,19 @@ impl<T: frame_system::Config> WeightInfo for BridgeWeight<T> {
.saturating_add(T::DbWeight::get().reads(5_u64))
.saturating_add(T::DbWeight::get().writes(3_u64))
}
/// Storage: BridgeRialtoMessages PalletOperatingMode (r:1 w:0)
/// Storage: BridgeUnknownMessages PalletOperatingMode (r:1 w:0)
///
/// Proof: BridgeRialtoMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2),
/// Proof: BridgeUnknownMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2),
/// added: 497, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoGrandpa ImportedHeaders (r:1 w:0)
/// Storage: BridgeUnknownGrandpa ImportedHeaders (r:1 w:0)
///
/// Proof: BridgeRialtoGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// Proof: BridgeUnknownGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// added: 2048, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoMessages InboundLanes (r:1 w:1)
/// Storage: BridgeUnknownMessages InboundLanes (r:1 w:1)
///
/// Proof: BridgeRialtoMessages InboundLanes (max_values: None, max_size: Some(49180), added:
/// Proof: BridgeUnknownMessages InboundLanes (max_values: None, max_size: Some(49180), added:
/// 51655, mode: MaxEncodedLen)
///
/// The range of component `i` is `[128, 2048]`.
@@ -296,19 +296,19 @@ impl<T: frame_system::Config> WeightInfo for BridgeWeight<T> {
// For backwards compatibility and tests
impl WeightInfo for () {
/// Storage: BridgeRialtoMessages PalletOperatingMode (r:1 w:0)
/// Storage: BridgeUnknownMessages PalletOperatingMode (r:1 w:0)
///
/// Proof: BridgeRialtoMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2),
/// Proof: BridgeUnknownMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2),
/// added: 497, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoGrandpa ImportedHeaders (r:1 w:0)
/// Storage: BridgeUnknownGrandpa ImportedHeaders (r:1 w:0)
///
/// Proof: BridgeRialtoGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// Proof: BridgeUnknownGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// added: 2048, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoMessages InboundLanes (r:1 w:1)
/// Storage: BridgeUnknownMessages InboundLanes (r:1 w:1)
///
/// Proof: BridgeRialtoMessages InboundLanes (max_values: None, max_size: Some(49180), added:
/// Proof: BridgeUnknownMessages InboundLanes (max_values: None, max_size: Some(49180), added:
/// 51655, mode: MaxEncodedLen)
fn receive_single_message_proof() -> Weight {
// Proof Size summary in bytes:
@@ -319,19 +319,19 @@ impl WeightInfo for () {
.saturating_add(RocksDbWeight::get().reads(3_u64))
.saturating_add(RocksDbWeight::get().writes(1_u64))
}
/// Storage: BridgeRialtoMessages PalletOperatingMode (r:1 w:0)
/// Storage: BridgeUnknownMessages PalletOperatingMode (r:1 w:0)
///
/// Proof: BridgeRialtoMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2),
/// Proof: BridgeUnknownMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2),
/// added: 497, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoGrandpa ImportedHeaders (r:1 w:0)
/// Storage: BridgeUnknownGrandpa ImportedHeaders (r:1 w:0)
///
/// Proof: BridgeRialtoGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// Proof: BridgeUnknownGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// added: 2048, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoMessages InboundLanes (r:1 w:1)
/// Storage: BridgeUnknownMessages InboundLanes (r:1 w:1)
///
/// Proof: BridgeRialtoMessages InboundLanes (max_values: None, max_size: Some(49180), added:
/// Proof: BridgeUnknownMessages InboundLanes (max_values: None, max_size: Some(49180), added:
/// 51655, mode: MaxEncodedLen)
fn receive_two_messages_proof() -> Weight {
// Proof Size summary in bytes:
@@ -342,19 +342,19 @@ impl WeightInfo for () {
.saturating_add(RocksDbWeight::get().reads(3_u64))
.saturating_add(RocksDbWeight::get().writes(1_u64))
}
/// Storage: BridgeRialtoMessages PalletOperatingMode (r:1 w:0)
/// Storage: BridgeUnknownMessages PalletOperatingMode (r:1 w:0)
///
/// Proof: BridgeRialtoMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2),
/// Proof: BridgeUnknownMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2),
/// added: 497, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoGrandpa ImportedHeaders (r:1 w:0)
/// Storage: BridgeUnknownGrandpa ImportedHeaders (r:1 w:0)
///
/// Proof: BridgeRialtoGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// Proof: BridgeUnknownGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// added: 2048, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoMessages InboundLanes (r:1 w:1)
/// Storage: BridgeUnknownMessages InboundLanes (r:1 w:1)
///
/// Proof: BridgeRialtoMessages InboundLanes (max_values: None, max_size: Some(49180), added:
/// Proof: BridgeUnknownMessages InboundLanes (max_values: None, max_size: Some(49180), added:
/// 51655, mode: MaxEncodedLen)
fn receive_single_message_proof_with_outbound_lane_state() -> Weight {
// Proof Size summary in bytes:
@@ -365,19 +365,19 @@ impl WeightInfo for () {
.saturating_add(RocksDbWeight::get().reads(3_u64))
.saturating_add(RocksDbWeight::get().writes(1_u64))
}
/// Storage: BridgeRialtoMessages PalletOperatingMode (r:1 w:0)
/// Storage: BridgeUnknownMessages PalletOperatingMode (r:1 w:0)
///
/// Proof: BridgeRialtoMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2),
/// Proof: BridgeUnknownMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2),
/// added: 497, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoGrandpa ImportedHeaders (r:1 w:0)
/// Storage: BridgeUnknownGrandpa ImportedHeaders (r:1 w:0)
///
/// Proof: BridgeRialtoGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// Proof: BridgeUnknownGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// added: 2048, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoMessages InboundLanes (r:1 w:1)
/// Storage: BridgeUnknownMessages InboundLanes (r:1 w:1)
///
/// Proof: BridgeRialtoMessages InboundLanes (max_values: None, max_size: Some(49180), added:
/// Proof: BridgeUnknownMessages InboundLanes (max_values: None, max_size: Some(49180), added:
/// 51655, mode: MaxEncodedLen)
fn receive_single_message_proof_1_kb() -> Weight {
// Proof Size summary in bytes:
@@ -388,19 +388,19 @@ impl WeightInfo for () {
.saturating_add(RocksDbWeight::get().reads(3_u64))
.saturating_add(RocksDbWeight::get().writes(1_u64))
}
/// Storage: BridgeRialtoMessages PalletOperatingMode (r:1 w:0)
/// Storage: BridgeUnknownMessages PalletOperatingMode (r:1 w:0)
///
/// Proof: BridgeRialtoMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2),
/// Proof: BridgeUnknownMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2),
/// added: 497, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoGrandpa ImportedHeaders (r:1 w:0)
/// Storage: BridgeUnknownGrandpa ImportedHeaders (r:1 w:0)
///
/// Proof: BridgeRialtoGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// Proof: BridgeUnknownGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// added: 2048, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoMessages InboundLanes (r:1 w:1)
/// Storage: BridgeUnknownMessages InboundLanes (r:1 w:1)
///
/// Proof: BridgeRialtoMessages InboundLanes (max_values: None, max_size: Some(49180), added:
/// Proof: BridgeUnknownMessages InboundLanes (max_values: None, max_size: Some(49180), added:
/// 51655, mode: MaxEncodedLen)
fn receive_single_message_proof_16_kb() -> Weight {
// Proof Size summary in bytes:
@@ -411,19 +411,19 @@ impl WeightInfo for () {
.saturating_add(RocksDbWeight::get().reads(3_u64))
.saturating_add(RocksDbWeight::get().writes(1_u64))
}
/// Storage: BridgeRialtoMessages PalletOperatingMode (r:1 w:0)
/// Storage: BridgeUnknownMessages PalletOperatingMode (r:1 w:0)
///
/// Proof: BridgeRialtoMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2),
/// Proof: BridgeUnknownMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2),
/// added: 497, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoGrandpa ImportedHeaders (r:1 w:0)
/// Storage: BridgeUnknownGrandpa ImportedHeaders (r:1 w:0)
///
/// Proof: BridgeRialtoGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// Proof: BridgeUnknownGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// added: 2048, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoMessages OutboundLanes (r:1 w:1)
/// Storage: BridgeUnknownMessages OutboundLanes (r:1 w:1)
///
/// Proof: BridgeRialtoMessages OutboundLanes (max_values: Some(1), max_size: Some(44), added:
/// Proof: BridgeUnknownMessages OutboundLanes (max_values: Some(1), max_size: Some(44), added:
/// 539, mode: MaxEncodedLen)
///
/// Storage: BridgeRelayers RelayerRewards (r:1 w:1)
@@ -439,19 +439,19 @@ impl WeightInfo for () {
.saturating_add(RocksDbWeight::get().reads(4_u64))
.saturating_add(RocksDbWeight::get().writes(2_u64))
}
/// Storage: BridgeRialtoMessages PalletOperatingMode (r:1 w:0)
/// Storage: BridgeUnknownMessages PalletOperatingMode (r:1 w:0)
///
/// Proof: BridgeRialtoMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2),
/// Proof: BridgeUnknownMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2),
/// added: 497, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoGrandpa ImportedHeaders (r:1 w:0)
/// Storage: BridgeUnknownGrandpa ImportedHeaders (r:1 w:0)
///
/// Proof: BridgeRialtoGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// Proof: BridgeUnknownGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// added: 2048, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoMessages OutboundLanes (r:1 w:1)
/// Storage: BridgeUnknownMessages OutboundLanes (r:1 w:1)
///
/// Proof: BridgeRialtoMessages OutboundLanes (max_values: Some(1), max_size: Some(44), added:
/// Proof: BridgeUnknownMessages OutboundLanes (max_values: Some(1), max_size: Some(44), added:
/// 539, mode: MaxEncodedLen)
///
/// Storage: BridgeRelayers RelayerRewards (r:1 w:1)
@@ -467,19 +467,19 @@ impl WeightInfo for () {
.saturating_add(RocksDbWeight::get().reads(4_u64))
.saturating_add(RocksDbWeight::get().writes(2_u64))
}
/// Storage: BridgeRialtoMessages PalletOperatingMode (r:1 w:0)
/// Storage: BridgeUnknownMessages PalletOperatingMode (r:1 w:0)
///
/// Proof: BridgeRialtoMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2),
/// Proof: BridgeUnknownMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2),
/// added: 497, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoGrandpa ImportedHeaders (r:1 w:0)
/// Storage: BridgeUnknownGrandpa ImportedHeaders (r:1 w:0)
///
/// Proof: BridgeRialtoGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// Proof: BridgeUnknownGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// added: 2048, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoMessages OutboundLanes (r:1 w:1)
/// Storage: BridgeUnknownMessages OutboundLanes (r:1 w:1)
///
/// Proof: BridgeRialtoMessages OutboundLanes (max_values: Some(1), max_size: Some(44), added:
/// Proof: BridgeUnknownMessages OutboundLanes (max_values: Some(1), max_size: Some(44), added:
/// 539, mode: MaxEncodedLen)
///
/// Storage: BridgeRelayers RelayerRewards (r:2 w:2)
@@ -495,19 +495,19 @@ impl WeightInfo for () {
.saturating_add(RocksDbWeight::get().reads(5_u64))
.saturating_add(RocksDbWeight::get().writes(3_u64))
}
/// Storage: BridgeRialtoMessages PalletOperatingMode (r:1 w:0)
/// Storage: BridgeUnknownMessages PalletOperatingMode (r:1 w:0)
///
/// Proof: BridgeRialtoMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2),
/// Proof: BridgeUnknownMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2),
/// added: 497, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoGrandpa ImportedHeaders (r:1 w:0)
/// Storage: BridgeUnknownGrandpa ImportedHeaders (r:1 w:0)
///
/// Proof: BridgeRialtoGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// Proof: BridgeUnknownGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// added: 2048, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoMessages InboundLanes (r:1 w:1)
/// Storage: BridgeUnknownMessages InboundLanes (r:1 w:1)
///
/// Proof: BridgeRialtoMessages InboundLanes (max_values: None, max_size: Some(49180), added:
/// Proof: BridgeUnknownMessages InboundLanes (max_values: None, max_size: Some(49180), added:
/// 51655, mode: MaxEncodedLen)
///
/// The range of component `i` is `[128, 2048]`.
+61 -61
View File
@@ -23,7 +23,7 @@
//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024
// Executed Command:
// target/release/millau-bridge-node
// target/release/unknown-bridge-node
// benchmark
// pallet
// --chain=dev
@@ -60,29 +60,29 @@ pub trait WeightInfo {
/// Those weights are test only and must never be used in production.
pub struct BridgeWeight<T>(PhantomData<T>);
impl<T: frame_system::Config> WeightInfo for BridgeWeight<T> {
/// Storage: BridgeRialtoParachains PalletOperatingMode (r:1 w:0)
/// Storage: BridgeUnknownParachains PalletOperatingMode (r:1 w:0)
///
/// Proof: BridgeRialtoParachains PalletOperatingMode (max_values: Some(1), max_size: Some(1),
/// Proof: BridgeUnknownParachains PalletOperatingMode (max_values: Some(1), max_size: Some(1),
/// added: 496, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoGrandpa ImportedHeaders (r:1 w:0)
/// Storage: BridgeUnknownGrandpa ImportedHeaders (r:1 w:0)
///
/// Proof: BridgeRialtoGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// Proof: BridgeUnknownGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// added: 2048, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoParachains ParasInfo (r:1 w:1)
/// Storage: BridgeUnknownParachains ParasInfo (r:1 w:1)
///
/// Proof: BridgeRialtoParachains ParasInfo (max_values: Some(1), max_size: Some(60), added:
/// Proof: BridgeUnknownParachains ParasInfo (max_values: Some(1), max_size: Some(60), added:
/// 555, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoParachains ImportedParaHashes (r:1 w:1)
/// Storage: BridgeUnknownParachains ImportedParaHashes (r:1 w:1)
///
/// Proof: BridgeRialtoParachains ImportedParaHashes (max_values: Some(1024), max_size:
/// Proof: BridgeUnknownParachains ImportedParaHashes (max_values: Some(1024), max_size:
/// Some(64), added: 1549, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoParachains ImportedParaHeads (r:0 w:1)
/// Storage: BridgeUnknownParachains ImportedParaHeads (r:0 w:1)
///
/// Proof: BridgeRialtoParachains ImportedParaHeads (max_values: Some(1024), max_size:
/// Proof: BridgeUnknownParachains ImportedParaHeads (max_values: Some(1024), max_size:
/// Some(196), added: 1681, mode: MaxEncodedLen)
///
/// The range of component `p` is `[1, 2]`.
@@ -97,29 +97,29 @@ impl<T: frame_system::Config> WeightInfo for BridgeWeight<T> {
.saturating_add(T::DbWeight::get().reads(4_u64))
.saturating_add(T::DbWeight::get().writes(3_u64))
}
/// Storage: BridgeRialtoParachains PalletOperatingMode (r:1 w:0)
/// Storage: BridgeUnknownParachains PalletOperatingMode (r:1 w:0)
///
/// Proof: BridgeRialtoParachains PalletOperatingMode (max_values: Some(1), max_size: Some(1),
/// Proof: BridgeUnknownParachains PalletOperatingMode (max_values: Some(1), max_size: Some(1),
/// added: 496, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoGrandpa ImportedHeaders (r:1 w:0)
/// Storage: BridgeUnknownGrandpa ImportedHeaders (r:1 w:0)
///
/// Proof: BridgeRialtoGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// Proof: BridgeUnknownGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// added: 2048, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoParachains ParasInfo (r:1 w:1)
/// Storage: BridgeUnknownParachains ParasInfo (r:1 w:1)
///
/// Proof: BridgeRialtoParachains ParasInfo (max_values: Some(1), max_size: Some(60), added:
/// Proof: BridgeUnknownParachains ParasInfo (max_values: Some(1), max_size: Some(60), added:
/// 555, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoParachains ImportedParaHashes (r:1 w:1)
/// Storage: BridgeUnknownParachains ImportedParaHashes (r:1 w:1)
///
/// Proof: BridgeRialtoParachains ImportedParaHashes (max_values: Some(1024), max_size:
/// Proof: BridgeUnknownParachains ImportedParaHashes (max_values: Some(1024), max_size:
/// Some(64), added: 1549, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoParachains ImportedParaHeads (r:0 w:1)
/// Storage: BridgeUnknownParachains ImportedParaHeads (r:0 w:1)
///
/// Proof: BridgeRialtoParachains ImportedParaHeads (max_values: Some(1024), max_size:
/// Proof: BridgeUnknownParachains ImportedParaHeads (max_values: Some(1024), max_size:
/// Some(196), added: 1681, mode: MaxEncodedLen)
fn submit_parachain_heads_with_1kb_proof() -> Weight {
// Proof Size summary in bytes:
@@ -130,29 +130,29 @@ impl<T: frame_system::Config> WeightInfo for BridgeWeight<T> {
.saturating_add(T::DbWeight::get().reads(4_u64))
.saturating_add(T::DbWeight::get().writes(3_u64))
}
/// Storage: BridgeRialtoParachains PalletOperatingMode (r:1 w:0)
/// Storage: BridgeUnknownParachains PalletOperatingMode (r:1 w:0)
///
/// Proof: BridgeRialtoParachains PalletOperatingMode (max_values: Some(1), max_size: Some(1),
/// Proof: BridgeUnknownParachains PalletOperatingMode (max_values: Some(1), max_size: Some(1),
/// added: 496, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoGrandpa ImportedHeaders (r:1 w:0)
/// Storage: BridgeUnknownGrandpa ImportedHeaders (r:1 w:0)
///
/// Proof: BridgeRialtoGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// Proof: BridgeUnknownGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// added: 2048, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoParachains ParasInfo (r:1 w:1)
/// Storage: BridgeUnknownParachains ParasInfo (r:1 w:1)
///
/// Proof: BridgeRialtoParachains ParasInfo (max_values: Some(1), max_size: Some(60), added:
/// Proof: BridgeUnknownParachains ParasInfo (max_values: Some(1), max_size: Some(60), added:
/// 555, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoParachains ImportedParaHashes (r:1 w:1)
/// Storage: BridgeUnknownParachains ImportedParaHashes (r:1 w:1)
///
/// Proof: BridgeRialtoParachains ImportedParaHashes (max_values: Some(1024), max_size:
/// Proof: BridgeUnknownParachains ImportedParaHashes (max_values: Some(1024), max_size:
/// Some(64), added: 1549, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoParachains ImportedParaHeads (r:0 w:1)
/// Storage: BridgeUnknownParachains ImportedParaHeads (r:0 w:1)
///
/// Proof: BridgeRialtoParachains ImportedParaHeads (max_values: Some(1024), max_size:
/// Proof: BridgeUnknownParachains ImportedParaHeads (max_values: Some(1024), max_size:
/// Some(196), added: 1681, mode: MaxEncodedLen)
fn submit_parachain_heads_with_16kb_proof() -> Weight {
// Proof Size summary in bytes:
@@ -167,29 +167,29 @@ impl<T: frame_system::Config> WeightInfo for BridgeWeight<T> {
// For backwards compatibility and tests
impl WeightInfo for () {
/// Storage: BridgeRialtoParachains PalletOperatingMode (r:1 w:0)
/// Storage: BridgeUnknownParachains PalletOperatingMode (r:1 w:0)
///
/// Proof: BridgeRialtoParachains PalletOperatingMode (max_values: Some(1), max_size: Some(1),
/// Proof: BridgeUnknownParachains PalletOperatingMode (max_values: Some(1), max_size: Some(1),
/// added: 496, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoGrandpa ImportedHeaders (r:1 w:0)
/// Storage: BridgeUnknownGrandpa ImportedHeaders (r:1 w:0)
///
/// Proof: BridgeRialtoGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// Proof: BridgeUnknownGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// added: 2048, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoParachains ParasInfo (r:1 w:1)
/// Storage: BridgeUnknownParachains ParasInfo (r:1 w:1)
///
/// Proof: BridgeRialtoParachains ParasInfo (max_values: Some(1), max_size: Some(60), added:
/// Proof: BridgeUnknownParachains ParasInfo (max_values: Some(1), max_size: Some(60), added:
/// 555, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoParachains ImportedParaHashes (r:1 w:1)
/// Storage: BridgeUnknownParachains ImportedParaHashes (r:1 w:1)
///
/// Proof: BridgeRialtoParachains ImportedParaHashes (max_values: Some(1024), max_size:
/// Proof: BridgeUnknownParachains ImportedParaHashes (max_values: Some(1024), max_size:
/// Some(64), added: 1549, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoParachains ImportedParaHeads (r:0 w:1)
/// Storage: BridgeUnknownParachains ImportedParaHeads (r:0 w:1)
///
/// Proof: BridgeRialtoParachains ImportedParaHeads (max_values: Some(1024), max_size:
/// Proof: BridgeUnknownParachains ImportedParaHeads (max_values: Some(1024), max_size:
/// Some(196), added: 1681, mode: MaxEncodedLen)
///
/// The range of component `p` is `[1, 2]`.
@@ -204,29 +204,29 @@ impl WeightInfo for () {
.saturating_add(RocksDbWeight::get().reads(4_u64))
.saturating_add(RocksDbWeight::get().writes(3_u64))
}
/// Storage: BridgeRialtoParachains PalletOperatingMode (r:1 w:0)
/// Storage: BridgeUnknownParachains PalletOperatingMode (r:1 w:0)
///
/// Proof: BridgeRialtoParachains PalletOperatingMode (max_values: Some(1), max_size: Some(1),
/// Proof: BridgeUnknownParachains PalletOperatingMode (max_values: Some(1), max_size: Some(1),
/// added: 496, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoGrandpa ImportedHeaders (r:1 w:0)
/// Storage: BridgeUnknownGrandpa ImportedHeaders (r:1 w:0)
///
/// Proof: BridgeRialtoGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// Proof: BridgeUnknownGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// added: 2048, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoParachains ParasInfo (r:1 w:1)
/// Storage: BridgeUnknownParachains ParasInfo (r:1 w:1)
///
/// Proof: BridgeRialtoParachains ParasInfo (max_values: Some(1), max_size: Some(60), added:
/// Proof: BridgeUnknownParachains ParasInfo (max_values: Some(1), max_size: Some(60), added:
/// 555, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoParachains ImportedParaHashes (r:1 w:1)
/// Storage: BridgeUnknownParachains ImportedParaHashes (r:1 w:1)
///
/// Proof: BridgeRialtoParachains ImportedParaHashes (max_values: Some(1024), max_size:
/// Proof: BridgeUnknownParachains ImportedParaHashes (max_values: Some(1024), max_size:
/// Some(64), added: 1549, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoParachains ImportedParaHeads (r:0 w:1)
/// Storage: BridgeUnknownParachains ImportedParaHeads (r:0 w:1)
///
/// Proof: BridgeRialtoParachains ImportedParaHeads (max_values: Some(1024), max_size:
/// Proof: BridgeUnknownParachains ImportedParaHeads (max_values: Some(1024), max_size:
/// Some(196), added: 1681, mode: MaxEncodedLen)
fn submit_parachain_heads_with_1kb_proof() -> Weight {
// Proof Size summary in bytes:
@@ -237,29 +237,29 @@ impl WeightInfo for () {
.saturating_add(RocksDbWeight::get().reads(4_u64))
.saturating_add(RocksDbWeight::get().writes(3_u64))
}
/// Storage: BridgeRialtoParachains PalletOperatingMode (r:1 w:0)
/// Storage: BridgeUnknownParachains PalletOperatingMode (r:1 w:0)
///
/// Proof: BridgeRialtoParachains PalletOperatingMode (max_values: Some(1), max_size: Some(1),
/// Proof: BridgeUnknownParachains PalletOperatingMode (max_values: Some(1), max_size: Some(1),
/// added: 496, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoGrandpa ImportedHeaders (r:1 w:0)
/// Storage: BridgeUnknownGrandpa ImportedHeaders (r:1 w:0)
///
/// Proof: BridgeRialtoGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// Proof: BridgeUnknownGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
/// added: 2048, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoParachains ParasInfo (r:1 w:1)
/// Storage: BridgeUnknownParachains ParasInfo (r:1 w:1)
///
/// Proof: BridgeRialtoParachains ParasInfo (max_values: Some(1), max_size: Some(60), added:
/// Proof: BridgeUnknownParachains ParasInfo (max_values: Some(1), max_size: Some(60), added:
/// 555, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoParachains ImportedParaHashes (r:1 w:1)
/// Storage: BridgeUnknownParachains ImportedParaHashes (r:1 w:1)
///
/// Proof: BridgeRialtoParachains ImportedParaHashes (max_values: Some(1024), max_size:
/// Proof: BridgeUnknownParachains ImportedParaHashes (max_values: Some(1024), max_size:
/// Some(64), added: 1549, mode: MaxEncodedLen)
///
/// Storage: BridgeRialtoParachains ImportedParaHeads (r:0 w:1)
/// Storage: BridgeUnknownParachains ImportedParaHeads (r:0 w:1)
///
/// Proof: BridgeRialtoParachains ImportedParaHeads (max_values: Some(1024), max_size:
/// Proof: BridgeUnknownParachains ImportedParaHeads (max_values: Some(1024), max_size:
/// Some(196), added: 1681, mode: MaxEncodedLen)
fn submit_parachain_heads_with_16kb_proof() -> Weight {
// Proof Size summary in bytes:
@@ -31,7 +31,7 @@ use frame_support::weights::{RuntimeDbWeight, Weight};
pub const DEFAULT_PARACHAIN_HEAD_SIZE: u32 = 384;
/// Number of extra bytes (excluding size of storage value itself) of storage proof, built at
/// the Rialto chain.
/// some generic chain.
pub const EXTRA_STORAGE_PROOF_SIZE: u32 = 1024;
/// Extended weight info.
+1 -1
View File
@@ -23,7 +23,7 @@
//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024
// Executed Command:
// target/release/millau-bridge-node
// target/release/rip-bridge-node
// benchmark
// pallet
// --chain=dev
@@ -1,38 +0,0 @@
[package]
name = "pallet-shift-session-manager"
description = "A Substrate Runtime module that selects 2/3 of initial validators for every session"
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 }
scale-info = { version = "2.10.0", default-features = false, features = ["derive"] }
# Substrate Dependencies
frame-support = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
frame-system = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
pallet-session = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-staking = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-std = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
[dev-dependencies]
sp-core = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sp-io = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sp-state-machine = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
[features]
default = [ "std" ]
std = [
"codec/std",
"frame-support/std",
"frame-system/std",
"pallet-session/std",
"scale-info/std",
"sp-staking/std",
"sp-std/std",
]
try-runtime = [ "frame-support/try-runtime", "frame-system/try-runtime" ]
@@ -1,10 +0,0 @@
# Shift Session Manager Pallet
**THIS PALLET IS NOT INTENDED TO BE USED IN PRODUCTION**
The pallet does not provide any calls or runtime storage entries. It only provides implementation of the
`pallet_session::SessionManager`. This implementation, starting from session `3` selects two thirds of initial
validators and changes the set on every session. We are using it at our testnets ([Rialto](../../bin/rialto/) and
[Millau](../../bin/millau/)) to be sure that the set changes every session. On well-known production chains
(like Kusama and Polkadot) the alternative is the set of [nPoS](https://research.web3.foundation/en/latest/polkadot/NPoS/index.html)
pallets, which selects validators, based on their nominations.
@@ -1,259 +0,0 @@
// 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/>.
//! Substrate session manager that selects 2/3 validators from initial set,
//! starting from session 2.
#![cfg_attr(not(feature = "std"), no_std)]
use frame_support::traits::{ValidatorSet, ValidatorSetWithIdentification};
use sp_std::prelude::*;
pub use pallet::*;
#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*;
#[pallet::config]
#[pallet::disable_frame_system_supertrait_check]
pub trait Config: pallet_session::Config {}
#[pallet::pallet]
#[pallet::without_storage_info]
pub struct Pallet<T>(PhantomData<T>);
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {}
#[pallet::call]
impl<T: Config> Pallet<T> {}
/// Validators of first two sessions.
#[pallet::storage]
pub(super) type InitialValidators<T: Config> = StorageValue<_, Vec<T::ValidatorId>>;
}
impl<T: pallet_session::Config + Config> ValidatorSet<T::AccountId> for Pallet<T> {
type ValidatorId = T::ValidatorId;
type ValidatorIdOf = T::ValidatorIdOf;
fn session_index() -> sp_staking::SessionIndex {
pallet_session::Pallet::<T>::current_index()
}
fn validators() -> Vec<Self::ValidatorId> {
pallet_session::Pallet::<T>::validators()
}
}
impl<T: Config> ValidatorSetWithIdentification<T::AccountId> for Pallet<T> {
type Identification = ();
type IdentificationOf = ();
}
impl<T: Config> pallet_session::SessionManager<T::ValidatorId> for Pallet<T> {
fn end_session(_: sp_staking::SessionIndex) {}
fn start_session(_: sp_staking::SessionIndex) {}
fn new_session(session_index: sp_staking::SessionIndex) -> Option<Vec<T::ValidatorId>> {
// we don't want to add even more fields to genesis config => just return None
if session_index == 0 || session_index == 1 {
return None
}
// the idea that on first call (i.e. when session 1 ends) we're reading current
// set of validators from session module (they are initial validators) and save
// in our 'local storage'.
// then for every session we select (deterministically) 2/3 of these initial
// validators to serve validators of new session
let available_validators = InitialValidators::<T>::get().unwrap_or_else(|| {
let validators = <pallet_session::Pallet<T>>::validators();
InitialValidators::<T>::put(validators.clone());
validators
});
Some(Self::select_validators(session_index, &available_validators))
}
}
impl<T: Config> Pallet<T> {
/// Select validators for session.
fn select_validators(
session_index: sp_staking::SessionIndex,
available_validators: &[T::ValidatorId],
) -> Vec<T::ValidatorId> {
let available_validators_count = available_validators.len();
let count = sp_std::cmp::max(1, 2 * available_validators_count / 3);
let offset = session_index as usize % available_validators_count;
let end = offset + count;
let session_validators = match end.overflowing_sub(available_validators_count) {
(wrapped_end, false) if wrapped_end != 0 => available_validators[offset..]
.iter()
.chain(available_validators[..wrapped_end].iter())
.cloned()
.collect(),
_ => available_validators[offset..end].to_vec(),
};
session_validators
}
}
#[cfg(test)]
mod tests {
// From construct_runtime macro
#![allow(clippy::from_over_into)]
use super::*;
use frame_support::{
parameter_types,
sp_runtime::{
testing::UintAuthorityId,
traits::{BlakeTwo256, ConvertInto, IdentityLookup},
BuildStorage, Perbill, RuntimeAppPublic,
},
weights::Weight,
};
use sp_core::H256;
use sp_io::TestExternalities;
use sp_state_machine::BasicExternalities;
type AccountId = u64;
type Block = frame_system::mocking::MockBlock<TestRuntime>;
frame_support::construct_runtime! {
pub enum TestRuntime {
System: frame_system::{Pallet, Call, Config<T>, Storage, Event<T>},
Session: pallet_session::{Pallet},
}
}
parameter_types! {
pub const MaximumBlockWeight: Weight = Weight::from_parts(1024, 0);
pub const MaximumBlockLength: u32 = 2 * 1024;
pub const AvailableBlockRatio: Perbill = Perbill::one();
}
impl frame_system::Config for TestRuntime {
type RuntimeOrigin = RuntimeOrigin;
type Nonce = u64;
type RuntimeCall = RuntimeCall;
type Hash = H256;
type Hashing = BlakeTwo256;
type AccountId = AccountId;
type Lookup = IdentityLookup<Self::AccountId>;
type Block = Block;
type RuntimeEvent = ();
type BlockHashCount = frame_support::traits::ConstU64<250>;
type Version = ();
type PalletInfo = PalletInfo;
type AccountData = ();
type OnNewAccount = ();
type OnKilledAccount = ();
type BaseCallFilter = frame_support::traits::Everything;
type SystemWeightInfo = ();
type BlockWeights = ();
type BlockLength = ();
type DbWeight = ();
type SS58Prefix = ();
type OnSetCode = ();
type MaxConsumers = frame_support::traits::ConstU32<16>;
}
parameter_types! {
pub const Period: u64 = 1;
pub const Offset: u64 = 0;
}
impl pallet_session::Config for TestRuntime {
type RuntimeEvent = ();
type ValidatorId = <Self as frame_system::Config>::AccountId;
type ValidatorIdOf = ConvertInto;
type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>;
type NextSessionRotation = pallet_session::PeriodicSessions<Period, Offset>;
type SessionManager = ();
type SessionHandler = TestSessionHandler;
type Keys = UintAuthorityId;
type WeightInfo = ();
}
impl Config for TestRuntime {}
pub struct TestSessionHandler;
impl pallet_session::SessionHandler<AccountId> for TestSessionHandler {
const KEY_TYPE_IDS: &'static [sp_runtime::KeyTypeId] = &[UintAuthorityId::ID];
fn on_genesis_session<Ks: sp_runtime::traits::OpaqueKeys>(_validators: &[(AccountId, Ks)]) {
}
fn on_new_session<Ks: sp_runtime::traits::OpaqueKeys>(
_: bool,
_: &[(AccountId, Ks)],
_: &[(AccountId, Ks)],
) {
}
fn on_disabled(_: u32) {}
}
fn new_test_ext() -> TestExternalities {
let mut t = frame_system::GenesisConfig::<TestRuntime>::default().build_storage().unwrap();
let keys = vec![
(1, 1, UintAuthorityId(1)),
(2, 2, UintAuthorityId(2)),
(3, 3, UintAuthorityId(3)),
(4, 4, UintAuthorityId(4)),
(5, 5, UintAuthorityId(5)),
];
BasicExternalities::execute_with_storage(&mut t, || {
for (ref k, ..) in &keys {
frame_system::Pallet::<TestRuntime>::inc_providers(k);
}
});
pallet_session::GenesisConfig::<TestRuntime> { keys }
.assimilate_storage(&mut t)
.unwrap();
TestExternalities::new(t)
}
#[test]
fn shift_session_manager_works() {
new_test_ext().execute_with(|| {
let all_accs = vec![1, 2, 3, 4, 5];
// at least 1 validator is selected
assert_eq!(Pallet::<TestRuntime>::select_validators(0, &[1]), vec![1],);
// at session#0, shift is also 0
assert_eq!(Pallet::<TestRuntime>::select_validators(0, &all_accs), vec![1, 2, 3],);
// at session#1, shift is also 1
assert_eq!(Pallet::<TestRuntime>::select_validators(1, &all_accs), vec![2, 3, 4],);
// at session#3, we're wrapping
assert_eq!(Pallet::<TestRuntime>::select_validators(3, &all_accs), vec![4, 5, 1],);
// at session#5, we're starting from the beginning again
assert_eq!(Pallet::<TestRuntime>::select_validators(5, &all_accs), vec![1, 2, 3],);
});
}
}
@@ -23,7 +23,7 @@
//! EXECUTION: , WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024
// Executed Command:
// target/release/millau-bridge-node
// target/release/rip-bridge-node
// benchmark
// pallet
// --chain=dev
@@ -1,62 +0,0 @@
[package]
name = "bp-millau"
description = "Primitives of Millau 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]
# TODO: Consume `fixed-hash` from crates.io when the following fix is published:
# https://github.com/paritytech/parity-common/commit/d3a9327124a66e52ca1114bb8640c02c18c134b8
# Expected in a version > 0.8.0
fixed-hash = { git = "https://github.com/paritytech/parity-common", branch = "master", default-features = false }
hash256-std-hasher = { version = "0.15.2", default-features = false }
impl-codec = { version = "0.6", default-features = false }
impl-serde = { version = "0.4.0", default-features = false }
parity-util-mem = { version = "0.12.0", default-features = false, features = ["primitive-types"] }
scale-info = { version = "2.10.0", default-features = false, features = ["derive"] }
serde = { version = "1.0", default-features = false, features = ["alloc", "derive"] }
# Bridge Dependencies
bp-beefy = { path = "../beefy", default-features = false }
bp-header-chain = { path = "../header-chain", default-features = false }
bp-messages = { path = "../messages", default-features = false }
bp-runtime = { path = "../runtime", default-features = false }
# Substrate Based Dependencies
frame-support = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
frame-system = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-core = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-io = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-std = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-trie = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
[features]
default = [ "std" ]
std = [
"bp-beefy/std",
"bp-header-chain/std",
"bp-messages/std",
"bp-runtime/std",
"fixed-hash/std",
"frame-support/std",
"frame-system/std",
"hash256-std-hasher/std",
"impl-codec/std",
"impl-serde/std",
"parity-util-mem/std",
"scale-info/std",
"serde/std",
"sp-api/std",
"sp-core/std",
"sp-io/std",
"sp-runtime/std",
"sp-std/std",
"sp-trie/std",
]
-244
View File
@@ -1,244 +0,0 @@
// 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)]
mod millau_hash;
use bp_beefy::ChainWithBeefy;
use bp_header_chain::ChainWithGrandpa;
use bp_messages::MessageNonce;
use bp_runtime::{decl_bridge_finality_runtime_apis, decl_bridge_runtime_apis, Chain};
use frame_support::{
dispatch::DispatchClass,
weights::{constants::WEIGHT_REF_TIME_PER_SECOND, IdentityFee, Weight},
};
use frame_system::limits;
use scale_info::TypeInfo;
use serde::{Deserialize, Serialize};
use sp_core::{storage::StateVersion, Hasher as HasherT};
use sp_runtime::{
traits::{IdentifyAccount, Verify},
MultiSignature, MultiSigner, Perbill, RuntimeDebug,
};
use sp_std::prelude::*;
use sp_trie::{LayoutV0, LayoutV1, TrieConfiguration};
use sp_runtime::traits::Keccak256;
pub use millau_hash::MillauHash;
/// Number of extra bytes (excluding size of storage value itself) of storage proof, built at
/// Millau chain. This mostly depends on number of entries (and their density) in the storage trie.
/// Some reserve is reserved to account future chain growth.
pub const EXTRA_STORAGE_PROOF_SIZE: u32 = 1024;
/// Number of bytes, included in the signed Millau 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 = 103;
/// Maximum weight of single Millau block.
///
/// This represents 0.5 seconds of compute assuming a target block time of six seconds.
///
/// Max PoV size is set to max value, since it isn't important for relay/standalone chains.
pub const MAXIMUM_BLOCK_WEIGHT: Weight =
Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND.saturating_div(2), u64::MAX);
/// Represents the portion of a block that will be used by Normal extrinsics.
pub const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
/// Maximal number of unrewarded relayer entries in Millau confirmation transaction.
pub const MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX: MessageNonce = 128;
/// Maximal number of unconfirmed messages in Millau confirmation transaction.
pub const MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX: MessageNonce = 128;
/// The target length of a session (how often authorities change) on Millau measured in of number of
/// blocks.
///
/// Note that since this is a target sessions may change before/after this time depending on network
/// conditions.
pub const SESSION_LENGTH: BlockNumber = 5 * time_units::MINUTES;
/// Maximal number of GRANDPA authorities at Millau.
pub const MAX_AUTHORITIES_COUNT: u32 = 5;
/// Reasonable number of headers in the `votes_ancestries` on Millau chain.
///
/// See [`bp-header-chain::ChainWithGrandpa`] for more details.
pub const REASONABLE_HEADERS_IN_JUSTIFICATON_ANCESTRY: u32 = 8;
/// Approximate average header size in `votes_ancestries` field of justification on Millau chain.
///
/// See [`bp-header-chain::ChainWithGrandpa`] for more details.
pub const AVERAGE_HEADER_SIZE_IN_JUSTIFICATION: u32 = 256;
/// Approximate maximal header size on Millau chain.
///
/// We expect maximal header to have digest item with the new authorities set for every consensus
/// engine (GRANDPA, Babe, BEEFY, ...) - so we multiply it by 3. And also
/// `AVERAGE_HEADER_SIZE_IN_JUSTIFICATION` bytes for other stuff.
///
/// See [`bp-header-chain::ChainWithGrandpa`] for more details.
pub const MAX_HEADER_SIZE: u32 = MAX_AUTHORITIES_COUNT
.saturating_mul(3)
.saturating_add(AVERAGE_HEADER_SIZE_IN_JUSTIFICATION);
/// 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 Millau.
pub type BlockNumber = u64;
/// Hash type used in Millau.
pub type Hash = <BlakeTwoAndKeccak256 as HasherT>::Out;
/// Type of object that can produce hashes on Millau.
pub type Hasher = BlakeTwoAndKeccak256;
/// The header type used by Millau.
pub type Header = sp_runtime::generic::Header<BlockNumber, Hasher>;
/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.
pub type Signature = MultiSignature;
/// Some way of identifying an account on the chain. We intentionally make it equivalent
/// to the public key of our transaction signing scheme.
pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;
/// Public key of the chain account that may be used to verify signatures.
pub type AccountSigner = MultiSigner;
/// Balance of an account.
pub type Balance = u64;
/// Nonce of a transaction in the chain.
pub type Nonce = u32;
/// Weight-to-Fee type used by Millau.
pub type WeightToFee = IdentityFee<Balance>;
/// Millau chain.
#[derive(RuntimeDebug)]
pub struct Millau;
impl Chain for Millau {
type BlockNumber = BlockNumber;
type Hash = Hash;
type Hasher = Hasher;
type Header = Header;
type AccountId = AccountId;
type Balance = Balance;
type Nonce = Nonce;
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 ChainWithGrandpa for Millau {
const WITH_CHAIN_GRANDPA_PALLET_NAME: &'static str = WITH_MILLAU_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;
}
impl ChainWithBeefy for Millau {
type CommitmentHasher = Keccak256;
type MmrHashing = Keccak256;
type MmrHash = <Keccak256 as sp_runtime::traits::Hash>::Output;
type BeefyMmrLeafExtra = ();
type AuthorityId = bp_beefy::EcdsaValidatorId;
type AuthorityIdToMerkleLeaf = bp_beefy::BeefyEcdsaToEthereum;
}
/// Millau Hasher (Blake2-256 ++ Keccak-256) implementation.
#[derive(PartialEq, Eq, Clone, Copy, RuntimeDebug, TypeInfo, Serialize, Deserialize)]
pub struct BlakeTwoAndKeccak256;
impl sp_core::Hasher for BlakeTwoAndKeccak256 {
type Out = MillauHash;
type StdHasher = hash256_std_hasher::Hash256StdHasher;
const LENGTH: usize = 64;
fn hash(s: &[u8]) -> Self::Out {
let mut combined_hash = MillauHash::default();
combined_hash.as_mut()[..32].copy_from_slice(&sp_io::hashing::blake2_256(s));
combined_hash.as_mut()[32..].copy_from_slice(&sp_io::hashing::keccak_256(s));
combined_hash
}
}
impl sp_runtime::traits::Hash for BlakeTwoAndKeccak256 {
type Output = MillauHash;
fn trie_root(input: Vec<(Vec<u8>, Vec<u8>)>, state_version: StateVersion) -> Self::Output {
match state_version {
StateVersion::V0 => LayoutV0::<BlakeTwoAndKeccak256>::trie_root(input),
StateVersion::V1 => LayoutV1::<BlakeTwoAndKeccak256>::trie_root(input),
}
}
fn ordered_trie_root(input: Vec<Vec<u8>>, state_version: StateVersion) -> Self::Output {
match state_version {
StateVersion::V0 => LayoutV0::<BlakeTwoAndKeccak256>::ordered_trie_root(input),
StateVersion::V1 => LayoutV1::<BlakeTwoAndKeccak256>::ordered_trie_root(input),
}
}
}
frame_support::parameter_types! {
pub BlockLength: limits::BlockLength =
limits::BlockLength::max_with_normal_ratio(2 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
pub BlockWeights: limits::BlockWeights =
limits::BlockWeights::with_sensible_defaults(MAXIMUM_BLOCK_WEIGHT, NORMAL_DISPATCH_RATIO);
}
/// Name of the With-Millau GRANDPA pallet instance that is deployed at bridged chains.
pub const WITH_MILLAU_GRANDPA_PALLET_NAME: &str = "BridgeMillauGrandpa";
/// Name of the With-Millau messages pallet instance that is deployed at bridged chains.
pub const WITH_MILLAU_MESSAGES_PALLET_NAME: &str = "BridgeMillauMessages";
/// Name of the transaction payment pallet at the Millau runtime.
pub const TRANSACTION_PAYMENT_PALLET_NAME: &str = "TransactionPayment";
decl_bridge_runtime_apis!(millau, grandpa);
@@ -1,56 +0,0 @@
// 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 parity_util_mem::MallocSizeOf;
use scale_info::TypeInfo;
use sp_runtime::traits::CheckEqual;
// `sp_core::H512` can't be used, because it doesn't implement `CheckEqual`, which is required
// by `frame_system::Config::Hash`.
fixed_hash::construct_fixed_hash! {
/// Hash type used in Millau chain.
#[derive(MallocSizeOf, TypeInfo)]
pub struct MillauHash(64);
}
impl_serde::impl_fixed_hash_serde!(MillauHash, 64);
impl_codec::impl_fixed_hash_codec!(MillauHash, 64);
impl CheckEqual for MillauHash {
#[cfg(feature = "std")]
fn check_equal(&self, other: &Self) {
use sp_core::hexdisplay::HexDisplay;
if self != other {
println!(
"Hash: given={}, expected={}",
HexDisplay::from(self.as_fixed_bytes()),
HexDisplay::from(other.as_fixed_bytes()),
);
}
}
#[cfg(not(feature = "std"))]
fn check_equal(&self, other: &Self) {
use frame_support::Printable;
if self != other {
"Hash not equal".print();
self.as_bytes().print();
other.as_bytes().print();
}
}
}
@@ -1,39 +0,0 @@
[package]
name = "bp-rialto-parachain"
description = "Primitives of Rialto 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-messages = { path = "../messages", 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/polkadot-sdk", branch = "master", default-features = false }
frame-system = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-core = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-std = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
[features]
default = [ "std" ]
std = [
"bp-bridge-hub-cumulus/std",
"bp-messages/std",
"bp-runtime/std",
"frame-support/std",
"frame-system/std",
"sp-api/std",
"sp-core/std",
"sp-runtime/std",
"sp-std/std",
]
@@ -1,148 +0,0 @@
// 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)]
use bp_messages::MessageNonce;
use bp_runtime::{decl_bridge_runtime_apis, Chain, Parachain};
use frame_support::{
dispatch::DispatchClass,
weights::{constants::WEIGHT_REF_TIME_PER_SECOND, IdentityFee, Weight},
};
use frame_system::limits;
use sp_core::Hasher as HasherT;
use sp_runtime::{
traits::{BlakeTwo256, IdentifyAccount, Verify},
MultiSignature, MultiSigner, Perbill, RuntimeDebug,
};
/// Identifier of RialtoParachain in the Rialto relay chain.
///
/// This identifier is not something that is declared either by Rialto or RialtoParachain. This
/// is an identifier of registration. So in theory it may be changed. But since bridge is going
/// to be deployed after parachain registration AND since parachain de-registration is highly
/// likely impossible, it is fine to declare this constant here.
pub const RIALTO_PARACHAIN_ID: u32 = 2000;
/// Number of extra bytes (excluding size of storage value itself) of storage proof, built at
/// RialtoParachain chain. This mostly depends on number of entries (and their density) in the
/// storage trie. Some reserve is reserved to account future chain growth.
pub const EXTRA_STORAGE_PROOF_SIZE: u32 = 1024;
/// Can be computed by subtracting encoded call size from raw transaction size.
pub const TX_EXTRA_BYTES: u32 = 104;
/// Maximal weight of single RialtoParachain block.
///
/// This represents two seconds of compute assuming a target block time of six seconds.
///
/// Max PoV size is set to `5Mb` as all Cumulus-based parachains do.
pub const MAXIMUM_BLOCK_WEIGHT: Weight =
Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND.saturating_mul(2), 5 * 1024 * 1024);
/// Represents the portion of a block that will be used by Normal extrinsics.
pub const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
/// Maximal number of unrewarded relayer entries in Rialto confirmation transaction.
pub const MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX: MessageNonce = 1024;
/// Maximal number of unconfirmed messages in Rialto confirmation transaction.
pub const MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX: MessageNonce = 1024;
/// Block number type used in Rialto.
pub type BlockNumber = u32;
/// Hash type used in Rialto.
pub type Hash = <BlakeTwo256 as HasherT>::Out;
/// The type of object that can produce hashes on Rialto.
pub type Hasher = BlakeTwo256;
/// The header type used by Rialto.
pub type Header = sp_runtime::generic::Header<BlockNumber, Hasher>;
/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.
pub type Signature = MultiSignature;
/// Some way of identifying an account on the chain. We intentionally make it equivalent
/// to the public key of our transaction signing scheme.
pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;
/// Public key of the chain account that may be used to verify signatures.
pub type AccountSigner = MultiSigner;
/// Balance of an account.
pub type Balance = u128;
/// An instant or duration in time.
pub type Moment = u64;
/// Nonce of a transaction in the parachain.
pub type Nonce = u32;
/// Weight-to-Fee type used by Rialto parachain.
pub type WeightToFee = IdentityFee<Balance>;
/// Rialto parachain.
#[derive(RuntimeDebug)]
pub struct RialtoParachain;
impl Chain for RialtoParachain {
type BlockNumber = BlockNumber;
type Hash = Hash;
type Hasher = Hasher;
type Header = Header;
type AccountId = AccountId;
type Balance = Balance;
type Nonce = Nonce;
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 RialtoParachain {
const PARACHAIN_ID: u32 = RIALTO_PARACHAIN_ID;
}
// Technically this is incorrect, because rialto-parachain isn't a bridge hub, but we're
// trying to keep it close to the bridge hubs code (at least in this aspect).
pub use bp_bridge_hub_cumulus::SignedExtension;
frame_support::parameter_types! {
pub BlockLength: limits::BlockLength =
limits::BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
pub BlockWeights: limits::BlockWeights =
limits::BlockWeights::with_sensible_defaults(MAXIMUM_BLOCK_WEIGHT, NORMAL_DISPATCH_RATIO);
}
/// Name of the With-Rialto-Parachain messages pallet instance that is deployed at bridged chains.
pub const WITH_RIALTO_PARACHAIN_MESSAGES_PALLET_NAME: &str = "BridgeRialtoParachainMessages";
/// Name of the transaction payment pallet at the Rialto parachain runtime.
pub const TRANSACTION_PAYMENT_PALLET_NAME: &str = "TransactionPayment";
decl_bridge_runtime_apis!(rialto_parachain);
@@ -1,38 +0,0 @@
[package]
name = "bp-rialto"
description = "Primitives of Rialto 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-messages = { path = "../messages", default-features = false }
bp-runtime = { path = "../runtime", default-features = false }
# Substrate Based Dependencies
frame-support = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
frame-system = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-core = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-std = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
[features]
default = [ "std" ]
std = [
"bp-header-chain/std",
"bp-messages/std",
"bp-runtime/std",
"frame-support/std",
"frame-system/std",
"sp-api/std",
"sp-core/std",
"sp-runtime/std",
"sp-std/std",
]
-210
View File
@@ -1,210 +0,0 @@
// 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)]
use bp_header_chain::ChainWithGrandpa;
use bp_messages::MessageNonce;
use bp_runtime::{decl_bridge_finality_runtime_apis, decl_bridge_runtime_apis, Chain};
use frame_support::{
dispatch::DispatchClass,
weights::{constants::WEIGHT_REF_TIME_PER_SECOND, IdentityFee, Weight},
};
use frame_system::limits;
use sp_core::Hasher as HasherT;
use sp_runtime::{
traits::{BlakeTwo256, IdentifyAccount, Verify},
MultiSignature, MultiSigner, Perbill, RuntimeDebug,
};
/// Number of extra bytes (excluding size of storage value itself) of storage proof, built at
/// Rialto chain. This mostly depends on number of entries (and their density) in the storage trie.
/// Some reserve is reserved to account future chain growth.
pub const EXTRA_STORAGE_PROOF_SIZE: u32 = 1024;
/// Number of bytes, included in the signed Rialto 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 = 104;
/// Maximal weight of single Rialto block.
///
/// This represents two seconds of compute assuming a target block time of six seconds.
///
/// Max PoV size is set to max value, since it isn't important for relay/standalone chains.
pub const MAXIMUM_BLOCK_WEIGHT: Weight =
Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND.saturating_mul(2), u64::MAX);
/// Represents the portion of a block that will be used by Normal extrinsics.
pub const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
/// Maximal number of unrewarded relayer entries in Rialto confirmation transaction.
pub const MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX: MessageNonce = 1024;
/// Maximal number of unconfirmed messages in Rialto confirmation transaction.
pub const MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX: MessageNonce = 1024;
/// The target length of a session (how often authorities change) on Rialto measured in of number of
/// blocks.
///
/// Note that since this is a target sessions may change before/after this time depending on network
/// conditions.
pub const SESSION_LENGTH: BlockNumber = 4;
/// Maximal number of GRANDPA authorities at Rialto.
pub const MAX_AUTHORITIES_COUNT: u32 = 5;
/// Reasonable number of headers in the `votes_ancestries` on Rialto chain.
///
/// See [`bp-header-chain::ChainWithGrandpa`] for more details.
pub const REASONABLE_HEADERS_IN_JUSTIFICATON_ANCESTRY: u32 = 8;
/// Approximate average header size in `votes_ancestries` field of justification on Rialto chain.
///
/// See [`bp-header-chain::ChainWithGrandpa`] for more details.
pub const AVERAGE_HEADER_SIZE_IN_JUSTIFICATION: u32 = 256;
/// Approximate maximal header size on Rialto chain.
///
/// We expect maximal header to have digest item with the new authorities set for every consensus
/// engine (GRANDPA, Babe, BEEFY, ...) - so we multiply it by 3. And also
/// `AVERAGE_HEADER_SIZE_IN_JUSTIFICATION` bytes for other stuff.
///
/// See [`bp-header-chain::ChainWithGrandpa`] for more details.
pub const MAX_HEADER_SIZE: u32 = MAX_AUTHORITIES_COUNT
.saturating_mul(3)
.saturating_add(AVERAGE_HEADER_SIZE_IN_JUSTIFICATION);
/// Maximal size of encoded `bp_parachains::ParaStoredHeaderData` structure among all Rialto
/// 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;
/// 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, SESSION_LENGTH};
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;
pub const EPOCH_DURATION_IN_SLOTS: BlockNumber = SESSION_LENGTH;
// 1 in 4 blocks (on average, not counting collisions) will be primary babe blocks.
pub const PRIMARY_PROBABILITY: (u64, u64) = (1, 4);
}
/// Block number type used in Rialto.
pub type BlockNumber = u32;
/// Hash type used in Rialto.
pub type Hash = <BlakeTwo256 as HasherT>::Out;
/// The type of object that can produce hashes on Rialto.
pub type Hasher = BlakeTwo256;
/// The header type used by Rialto.
pub type Header = sp_runtime::generic::Header<BlockNumber, Hasher>;
/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.
pub type Signature = MultiSignature;
/// Some way of identifying an account on the chain. We intentionally make it equivalent
/// to the public key of our transaction signing scheme.
pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;
/// Public key of the chain account that may be used to verify signatures.
pub type AccountSigner = MultiSigner;
/// Balance of an account.
pub type Balance = u128;
/// An instant or duration in time.
pub type Moment = u64;
/// Nonce of a transaction in the chain.
pub type Nonce = u32;
/// Weight-to-Fee type used by Rialto.
pub type WeightToFee = IdentityFee<Balance>;
/// Rialto chain.
#[derive(RuntimeDebug)]
pub struct Rialto;
impl Chain for Rialto {
type BlockNumber = BlockNumber;
type Hash = Hash;
type Hasher = Hasher;
type Header = Header;
type AccountId = AccountId;
type Balance = Balance;
type Nonce = Nonce;
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 ChainWithGrandpa for Rialto {
const WITH_CHAIN_GRANDPA_PALLET_NAME: &'static str = WITH_RIALTO_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;
}
frame_support::parameter_types! {
pub BlockLength: limits::BlockLength =
limits::BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
pub BlockWeights: limits::BlockWeights =
limits::BlockWeights::with_sensible_defaults(MAXIMUM_BLOCK_WEIGHT, NORMAL_DISPATCH_RATIO);
}
/// Name of the With-Rialto GRANDPA pallet instance that is deployed at bridged chains.
pub const WITH_RIALTO_GRANDPA_PALLET_NAME: &str = "BridgeRialtoGrandpa";
/// Name of the With-Rialto messages pallet instance that is deployed at bridged chains.
pub const WITH_RIALTO_MESSAGES_PALLET_NAME: &str = "BridgeRialtoMessages";
/// Name of the With-Rialto parachains bridge pallet instance that is deployed at bridged chains.
pub const WITH_RIALTO_BRIDGE_PARAS_PALLET_NAME: &str = "BridgeRialtoParachains";
/// Name of the parachain registrar pallet in the Rialto runtime.
pub const PARAS_REGISTRAR_PALLET_NAME: &str = "Registrar";
/// Name of the parachains pallet in the Rialto runtime.
pub const PARAS_PALLET_NAME: &str = "Paras";
decl_bridge_runtime_apis!(rialto, grandpa);
+3 -3
View File
@@ -280,7 +280,7 @@ pub type TransactionEraOf<C> = crate::TransactionEra<BlockNumberOf<C>, HashOf<C>
/// - constants that are stringified names of runtime API methods:
/// - `BEST_FINALIZED_<THIS_CHAIN>_HEADER_METHOD`
/// - `<THIS_CHAIN>_ACCEPTED_<CONSENSUS>_FINALITY_PROOFS_METHOD`
/// The name of the chain has to be specified in snake case (e.g. `rialto_parachain`).
/// The name of the chain has to be specified in snake case (e.g. `bridge_hub_polkadot`).
#[macro_export]
macro_rules! decl_bridge_finality_runtime_apis {
($chain: ident $(, $consensus: ident => $justification_type: ty)?) => {
@@ -332,7 +332,7 @@ macro_rules! decl_bridge_finality_runtime_apis {
/// - `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`).
/// The name of the chain has to be specified in snake case (e.g. `bridge_hub_polkadot`).
#[macro_export]
macro_rules! decl_bridge_messages_runtime_apis {
($chain: ident) => {
@@ -390,7 +390,7 @@ macro_rules! decl_bridge_messages_runtime_apis {
/// 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`).
/// The name of the chain has to be specified in snake case (e.g. `bridge_hub_polkadot`).
#[macro_export]
macro_rules! decl_bridge_runtime_apis {
($chain: ident $(, $consensus: ident)?) => {
-29
View File
@@ -61,15 +61,6 @@ 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";
@@ -277,18 +268,6 @@ pub fn storage_map_final_key<H: StorageHasher>(
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`.
@@ -574,14 +553,6 @@ where
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!(
-19
View File
@@ -25,19 +25,12 @@ strum = { version = "0.25.0", features = ["derive"] }
bp-header-chain = { path = "../../primitives/header-chain" }
bp-messages = { path = "../../primitives/messages" }
bp-parachains = { path = "../../primitives/parachains" }
bp-millau = { path = "../../primitives/chain-millau" }
bp-polkadot-bulletin = { path = "../../primitives/chain-polkadot-bulletin" }
bp-polkadot-core = { path = "../../primitives/polkadot-core" }
bp-rialto = { path = "../../primitives/chain-rialto" }
bp-rialto-parachain = { path = "../../primitives/chain-rialto-parachain" }
bp-runtime = { path = "../../primitives/runtime" }
bridge-runtime-common = { path = "../../bin/runtime-common" }
millau-runtime = { path = "../../bin/millau/runtime" }
pallet-bridge-parachains = { path = "../../modules/parachains" }
parachains-relay = { path = "../parachains" }
relay-millau-client = { path = "../client-millau" }
relay-rialto-client = { path = "../client-rialto" }
relay-rialto-parachain-client = { path = "../client-rialto-parachain" }
relay-bridge-hub-kusama-client = { path = "../client-bridge-hub-kusama" }
relay-bridge-hub-polkadot-client = { path = "../client-bridge-hub-polkadot" }
relay-bridge-hub-rococo-client = { path = "../client-bridge-hub-rococo" }
@@ -51,10 +44,6 @@ relay-substrate-client = { path = "../client-substrate" }
relay-utils = { path = "../utils" }
relay-westend-client = { path = "../client-westend" }
relay-wococo-client = { path = "../client-wococo" }
rialto-runtime = { path = "../../bin/rialto/runtime" }
# we are not using this runtime to craft call or transactions, but we still need it
# to prepare large XCM messages
rialto-parachain-runtime = { path = "../../bin/rialto-parachain/runtime" }
substrate-relay-helper = { path = "../lib-substrate-relay" }
# Substrate Dependencies
@@ -63,14 +52,6 @@ frame-support = { git = "https://github.com/paritytech/polkadot-sdk", branch = "
sp-core = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
# Polkadot Dependencies
polkadot-parachain-primitives = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
polkadot-primitives = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
polkadot-runtime-common = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
polkadot-runtime-parachains = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
xcm = { package = "staging-xcm", git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
xcm-executor = { package = "staging-xcm-executor", git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
[dev-dependencies]
bp-test-utils = { path = "../../primitives/test-utils" }
hex-literal = "0.4"
@@ -18,8 +18,5 @@
pub mod kusama_polkadot;
pub mod polkadot_bulletin;
pub mod rialto_millau;
pub mod rialto_parachain_millau;
pub mod rococo_westend;
pub mod rococo_wococo;
pub mod westend_millau;
@@ -1,74 +0,0 @@
// 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/>.
//! Millau-to-Rialto headers sync entrypoint.
use crate::cli::bridge::{
CliBridgeBase, MessagesCliBridge, RelayToRelayEquivocationDetectionCliBridge,
RelayToRelayHeadersCliBridge,
};
use substrate_relay_helper::{
equivocation::{
DirectReportGrandpaEquivocationCallBuilder, SubstrateEquivocationDetectionPipeline,
},
finality::{DirectSubmitGrandpaFinalityProofCallBuilder, SubstrateFinalitySyncPipeline},
finality_base::{engine::Grandpa as GrandpaFinalityEngine, SubstrateFinalityPipeline},
};
/// Description of Millau -> Rialto finalized headers bridge.
#[derive(Clone, Debug)]
pub struct MillauFinalityToRialto;
impl SubstrateFinalityPipeline for MillauFinalityToRialto {
type SourceChain = relay_millau_client::Millau;
type TargetChain = relay_rialto_client::Rialto;
type FinalityEngine = GrandpaFinalityEngine<Self::SourceChain>;
}
impl SubstrateFinalitySyncPipeline for MillauFinalityToRialto {
type SubmitFinalityProofCallBuilder = DirectSubmitGrandpaFinalityProofCallBuilder<
Self,
rialto_runtime::Runtime,
rialto_runtime::MillauGrandpaInstance,
>;
}
impl SubstrateEquivocationDetectionPipeline for MillauFinalityToRialto {
type ReportEquivocationCallBuilder =
DirectReportGrandpaEquivocationCallBuilder<Self, millau_runtime::Runtime>;
}
/// `Millau` to `Rialto` bridge definition.
pub struct MillauToRialtoCliBridge {}
impl CliBridgeBase for MillauToRialtoCliBridge {
type Source = relay_millau_client::Millau;
type Target = relay_rialto_client::Rialto;
}
impl RelayToRelayHeadersCliBridge for MillauToRialtoCliBridge {
type Finality = MillauFinalityToRialto;
}
impl RelayToRelayEquivocationDetectionCliBridge for MillauToRialtoCliBridge {
type Equivocation = MillauFinalityToRialto;
}
impl MessagesCliBridge for MillauToRialtoCliBridge {
type MessagesLane =
crate::bridges::rialto_millau::millau_messages_to_rialto::MillauMessagesToRialto;
}
@@ -1,47 +0,0 @@
// 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/>.
//! Millau-to-Rialto messages sync entrypoint.
use relay_millau_client::Millau;
use relay_rialto_client::Rialto;
use substrate_relay_helper::messages_lane::{
DirectReceiveMessagesDeliveryProofCallBuilder, DirectReceiveMessagesProofCallBuilder,
SubstrateMessageLane,
};
/// Description of Millau -> Rialto messages bridge.
#[derive(Clone, Debug)]
pub struct MillauMessagesToRialto;
impl SubstrateMessageLane for MillauMessagesToRialto {
type SourceChain = Millau;
type TargetChain = Rialto;
type ReceiveMessagesProofCallBuilder = DirectReceiveMessagesProofCallBuilder<
Self,
rialto_runtime::Runtime,
rialto_runtime::WithMillauMessagesInstance,
>;
type ReceiveMessagesDeliveryProofCallBuilder = DirectReceiveMessagesDeliveryProofCallBuilder<
Self,
millau_runtime::Runtime,
millau_runtime::WithRialtoMessagesInstance,
>;
type SourceBatchCallBuilder = ();
type TargetBatchCallBuilder = ();
}
@@ -1,22 +0,0 @@
// 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/>.
//! Declaration of all bridges between Rialto and Millau.
pub mod millau_headers_to_rialto;
pub mod millau_messages_to_rialto;
pub mod rialto_headers_to_millau;
pub mod rialto_messages_to_millau;
@@ -1,74 +0,0 @@
// 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/>.
//! Rialto-to-Millau headers sync entrypoint.
use crate::cli::bridge::{
CliBridgeBase, MessagesCliBridge, RelayToRelayEquivocationDetectionCliBridge,
RelayToRelayHeadersCliBridge,
};
use substrate_relay_helper::{
equivocation::{
DirectReportGrandpaEquivocationCallBuilder, SubstrateEquivocationDetectionPipeline,
},
finality::{DirectSubmitGrandpaFinalityProofCallBuilder, SubstrateFinalitySyncPipeline},
finality_base::{engine::Grandpa as GrandpaFinalityEngine, SubstrateFinalityPipeline},
};
/// Description of Millau -> Rialto finalized headers bridge.
#[derive(Clone, Debug)]
pub struct RialtoFinalityToMillau;
impl SubstrateFinalityPipeline for RialtoFinalityToMillau {
type SourceChain = relay_rialto_client::Rialto;
type TargetChain = relay_millau_client::Millau;
type FinalityEngine = GrandpaFinalityEngine<Self::SourceChain>;
}
impl SubstrateFinalitySyncPipeline for RialtoFinalityToMillau {
type SubmitFinalityProofCallBuilder = DirectSubmitGrandpaFinalityProofCallBuilder<
Self,
millau_runtime::Runtime,
millau_runtime::RialtoGrandpaInstance,
>;
}
impl SubstrateEquivocationDetectionPipeline for RialtoFinalityToMillau {
type ReportEquivocationCallBuilder =
DirectReportGrandpaEquivocationCallBuilder<Self, rialto_runtime::Runtime>;
}
/// `Rialto` to `Millau` bridge definition.
pub struct RialtoToMillauCliBridge {}
impl CliBridgeBase for RialtoToMillauCliBridge {
type Source = relay_rialto_client::Rialto;
type Target = relay_millau_client::Millau;
}
impl RelayToRelayHeadersCliBridge for RialtoToMillauCliBridge {
type Finality = RialtoFinalityToMillau;
}
impl RelayToRelayEquivocationDetectionCliBridge for RialtoToMillauCliBridge {
type Equivocation = RialtoFinalityToMillau;
}
impl MessagesCliBridge for RialtoToMillauCliBridge {
type MessagesLane =
crate::bridges::rialto_millau::rialto_messages_to_millau::RialtoMessagesToMillau;
}
@@ -1,47 +0,0 @@
// 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/>.
//! Rialto-to-Millau messages sync entrypoint.
use relay_millau_client::Millau;
use relay_rialto_client::Rialto;
use substrate_relay_helper::messages_lane::{
DirectReceiveMessagesDeliveryProofCallBuilder, DirectReceiveMessagesProofCallBuilder,
SubstrateMessageLane,
};
/// Description of Rialto -> Millau messages bridge.
#[derive(Clone, Debug)]
pub struct RialtoMessagesToMillau;
impl SubstrateMessageLane for RialtoMessagesToMillau {
type SourceChain = Rialto;
type TargetChain = Millau;
type ReceiveMessagesProofCallBuilder = DirectReceiveMessagesProofCallBuilder<
Self,
millau_runtime::Runtime,
millau_runtime::WithRialtoMessagesInstance,
>;
type ReceiveMessagesDeliveryProofCallBuilder = DirectReceiveMessagesDeliveryProofCallBuilder<
Self,
rialto_runtime::Runtime,
rialto_runtime::WithMillauMessagesInstance,
>;
type SourceBatchCallBuilder = ();
type TargetBatchCallBuilder = ();
}
@@ -1,95 +0,0 @@
// 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/>.
//! Millau-to-RialtoParachain headers sync entrypoint.
// 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/>.
//! Millau-to-RialtoParachain headers sync entrypoint.
use crate::cli::bridge::{
CliBridgeBase, MessagesCliBridge, RelayToRelayEquivocationDetectionCliBridge,
RelayToRelayHeadersCliBridge,
};
use substrate_relay_helper::{
equivocation::{
DirectReportGrandpaEquivocationCallBuilder, SubstrateEquivocationDetectionPipeline,
},
finality::SubstrateFinalitySyncPipeline,
finality_base::{engine::Grandpa as GrandpaFinalityEngine, SubstrateFinalityPipeline},
};
substrate_relay_helper::generate_submit_finality_proof_call_builder!(
MillauFinalityToRialtoParachain,
MillauFinalityToRialtoParachainCallBuilder,
relay_rialto_parachain_client::RuntimeCall::BridgeMillauGrandpa,
relay_rialto_parachain_client::BridgeGrandpaCall::submit_finality_proof
);
/// Description of Millau -> Rialto finalized headers bridge.
#[derive(Clone, Debug)]
pub struct MillauFinalityToRialtoParachain;
impl SubstrateFinalityPipeline for MillauFinalityToRialtoParachain {
type SourceChain = relay_millau_client::Millau;
type TargetChain = relay_rialto_parachain_client::RialtoParachain;
type FinalityEngine = GrandpaFinalityEngine<Self::SourceChain>;
}
impl SubstrateFinalitySyncPipeline for MillauFinalityToRialtoParachain {
type SubmitFinalityProofCallBuilder = MillauFinalityToRialtoParachainCallBuilder;
}
impl SubstrateEquivocationDetectionPipeline for MillauFinalityToRialtoParachain {
type ReportEquivocationCallBuilder =
DirectReportGrandpaEquivocationCallBuilder<Self, millau_runtime::Runtime>;
}
/// `Millau` to `RialtoParachain` bridge definition.
pub struct MillauToRialtoParachainCliBridge {}
impl CliBridgeBase for MillauToRialtoParachainCliBridge {
type Source = relay_millau_client::Millau;
type Target = relay_rialto_parachain_client::RialtoParachain;
}
impl RelayToRelayHeadersCliBridge for MillauToRialtoParachainCliBridge {
type Finality = MillauFinalityToRialtoParachain;
}
impl RelayToRelayEquivocationDetectionCliBridge for MillauToRialtoParachainCliBridge {
type Equivocation = MillauFinalityToRialtoParachain;
}
impl MessagesCliBridge for MillauToRialtoParachainCliBridge {
type MessagesLane =
crate::bridges::rialto_parachain_millau::millau_messages_to_rialto_parachain::MillauMessagesToRialtoParachain;
}
@@ -1,51 +0,0 @@
// 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/>.
//! Millau-to-RialtoParachain messages sync entrypoint.
use relay_millau_client::Millau;
use relay_rialto_parachain_client::RialtoParachain;
use substrate_relay_helper::{
messages_lane::{DirectReceiveMessagesDeliveryProofCallBuilder, SubstrateMessageLane},
UtilityPalletBatchCallBuilder,
};
substrate_relay_helper::generate_receive_message_proof_call_builder!(
MillauMessagesToRialtoParachain,
MillauMessagesToRialtoParachainReceiveMessagesProofCallBuilder,
relay_rialto_parachain_client::RuntimeCall::BridgeMillauMessages,
relay_rialto_parachain_client::BridgeMessagesCall::receive_messages_proof
);
/// Description of Millau -> RialtoParachain messages bridge.
#[derive(Clone, Debug)]
pub struct MillauMessagesToRialtoParachain;
impl SubstrateMessageLane for MillauMessagesToRialtoParachain {
type SourceChain = Millau;
type TargetChain = RialtoParachain;
type ReceiveMessagesProofCallBuilder =
MillauMessagesToRialtoParachainReceiveMessagesProofCallBuilder;
type ReceiveMessagesDeliveryProofCallBuilder = DirectReceiveMessagesDeliveryProofCallBuilder<
Self,
millau_runtime::Runtime,
millau_runtime::WithRialtoParachainMessagesInstance,
>;
type SourceBatchCallBuilder = UtilityPalletBatchCallBuilder<Millau>;
type TargetBatchCallBuilder = ();
}
@@ -1,22 +0,0 @@
// 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/>.
//! Declaration of all bridges between Rialto Parachain and Millau.
pub mod millau_headers_to_rialto_parachain;
pub mod millau_messages_to_rialto_parachain;
pub mod rialto_parachain_messages_to_millau;
pub mod rialto_parachains_to_millau;
@@ -1,51 +0,0 @@
// 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/>.
//! RialtoParachain-to-Millau messages sync entrypoint.
use relay_millau_client::Millau;
use relay_rialto_parachain_client::RialtoParachain;
use substrate_relay_helper::{
messages_lane::{DirectReceiveMessagesProofCallBuilder, SubstrateMessageLane},
UtilityPalletBatchCallBuilder,
};
substrate_relay_helper::generate_receive_message_delivery_proof_call_builder!(
RialtoParachainMessagesToMillau,
RialtoParachainMessagesToMillauReceiveMessagesDeliveryProofCallBuilder,
relay_rialto_parachain_client::RuntimeCall::BridgeMillauMessages,
relay_rialto_parachain_client::BridgeMessagesCall::receive_messages_delivery_proof
);
/// Description of RialtoParachain -> Millau messages bridge.
#[derive(Clone, Debug)]
pub struct RialtoParachainMessagesToMillau;
impl SubstrateMessageLane for RialtoParachainMessagesToMillau {
type SourceChain = RialtoParachain;
type TargetChain = Millau;
type ReceiveMessagesProofCallBuilder = DirectReceiveMessagesProofCallBuilder<
Self,
millau_runtime::Runtime,
millau_runtime::WithRialtoParachainMessagesInstance,
>;
type ReceiveMessagesDeliveryProofCallBuilder =
RialtoParachainMessagesToMillauReceiveMessagesDeliveryProofCallBuilder;
type SourceBatchCallBuilder = ();
type TargetBatchCallBuilder = UtilityPalletBatchCallBuilder<Millau>;
}
@@ -1,65 +0,0 @@
// 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/>.
//! Rialto-to-Millau parachains sync entrypoint.
use crate::cli::bridge::{CliBridgeBase, MessagesCliBridge, ParachainToRelayHeadersCliBridge};
use relay_millau_client::Millau;
use relay_rialto_client::Rialto;
use relay_rialto_parachain_client::RialtoParachain;
use substrate_relay_helper::parachains::{
DirectSubmitParachainHeadsCallBuilder, SubstrateParachainsPipeline,
};
/// Rialto-to-Millau parachains sync description.
#[derive(Clone, Debug)]
pub struct RialtoParachainsToMillau;
impl SubstrateParachainsPipeline for RialtoParachainsToMillau {
type SourceParachain = RialtoParachain;
type SourceRelayChain = Rialto;
type TargetChain = Millau;
type SubmitParachainHeadsCallBuilder = RialtoParachainsToMillauSubmitParachainHeadsCallBuilder;
}
/// `submit_parachain_heads` call builder for Rialto-to-Millau parachains sync pipeline.
pub type RialtoParachainsToMillauSubmitParachainHeadsCallBuilder =
DirectSubmitParachainHeadsCallBuilder<
RialtoParachainsToMillau,
millau_runtime::Runtime,
millau_runtime::WithRialtoParachainsInstance,
>;
/// `RialtoParachain` to `Millau` bridge definition.
pub struct RialtoParachainToMillauCliBridge {}
impl CliBridgeBase for RialtoParachainToMillauCliBridge {
type Source = RialtoParachain;
type Target = Millau;
}
impl ParachainToRelayHeadersCliBridge for RialtoParachainToMillauCliBridge {
type SourceRelay = Rialto;
type ParachainFinality = RialtoParachainsToMillau;
type RelayFinality =
crate::bridges::rialto_millau::rialto_headers_to_millau::RialtoFinalityToMillau;
}
impl MessagesCliBridge for RialtoParachainToMillauCliBridge {
type MessagesLane =
crate::bridges::rialto_parachain_millau::rialto_parachain_messages_to_millau::RialtoParachainMessagesToMillau;
}
@@ -1,20 +0,0 @@
// 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/>.
//! Declaration of all bridges between Westend and Millau.
pub mod westend_headers_to_millau;
pub mod westend_parachains_to_millau;
@@ -1,54 +0,0 @@
// 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/>.
//! Westend-to-Millau headers sync entrypoint.
use crate::cli::bridge::{CliBridgeBase, RelayToRelayHeadersCliBridge};
use substrate_relay_helper::{
finality::{DirectSubmitGrandpaFinalityProofCallBuilder, SubstrateFinalitySyncPipeline},
finality_base::{engine::Grandpa as GrandpaFinalityEngine, SubstrateFinalityPipeline},
};
/// Description of Westend -> Millau finalized headers bridge.
#[derive(Clone, Debug)]
pub struct WestendFinalityToMillau;
impl SubstrateFinalityPipeline for WestendFinalityToMillau {
type SourceChain = relay_westend_client::Westend;
type TargetChain = relay_millau_client::Millau;
type FinalityEngine = GrandpaFinalityEngine<Self::SourceChain>;
}
impl SubstrateFinalitySyncPipeline for WestendFinalityToMillau {
type SubmitFinalityProofCallBuilder = DirectSubmitGrandpaFinalityProofCallBuilder<
Self,
millau_runtime::Runtime,
millau_runtime::WestendGrandpaInstance,
>;
}
/// `Westend` to `Millau` bridge definition.
pub struct WestendToMillauCliBridge {}
impl CliBridgeBase for WestendToMillauCliBridge {
type Source = relay_westend_client::Westend;
type Target = relay_millau_client::Millau;
}
impl RelayToRelayHeadersCliBridge for WestendToMillauCliBridge {
type Finality = WestendFinalityToMillau;
}
@@ -1,90 +0,0 @@
// 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/>.
//! Westend-to-Millau parachains sync entrypoint.
use crate::cli::bridge::{CliBridgeBase, ParachainToRelayHeadersCliBridge};
use relay_millau_client::Millau;
use relay_westend_client::Westend;
use substrate_relay_helper::parachains::{
DirectSubmitParachainHeadsCallBuilder, SubstrateParachainsPipeline,
};
/// Westend-to-Millau parachains sync description.
#[derive(Clone, Debug)]
pub struct WestendParachainsToMillau;
impl SubstrateParachainsPipeline for WestendParachainsToMillau {
type SourceParachain = relay_asset_hub_westend_client::AssetHubWestend;
type SourceRelayChain = Westend;
type TargetChain = Millau;
type SubmitParachainHeadsCallBuilder = WestendParachainsToMillauSubmitParachainHeadsCallBuilder;
}
/// `submit_parachain_heads` call builder for Rialto-to-Millau parachains sync pipeline.
pub type WestendParachainsToMillauSubmitParachainHeadsCallBuilder =
DirectSubmitParachainHeadsCallBuilder<
WestendParachainsToMillau,
millau_runtime::Runtime,
millau_runtime::WithWestendParachainsInstance,
>;
/// `WestendParachain` to `Millau` bridge definition.
pub struct AssetHubWestendToMillauCliBridge {}
impl ParachainToRelayHeadersCliBridge for AssetHubWestendToMillauCliBridge {
type SourceRelay = Westend;
type ParachainFinality = WestendParachainsToMillau;
type RelayFinality =
crate::bridges::westend_millau::westend_headers_to_millau::WestendFinalityToMillau;
}
impl CliBridgeBase for AssetHubWestendToMillauCliBridge {
type Source = relay_asset_hub_westend_client::AssetHubWestend;
type Target = Millau;
}
/// TODO: Note: I know this does not belong here, but I don't want to add it to the
/// `chain-asset-hub-westend` or `chain-westend`, because we wont use it for production and I don't
/// want to bring this to the bridges subtree now. Anyway, we plan to retire millau/rialto, so this
/// hack will disappear with that.
pub mod relay_asset_hub_westend_client {
use bp_runtime::{ChainId, UnderlyingChainProvider};
use relay_substrate_client::Chain;
use std::time::Duration;
/// `AssetHubWestend` parachain definition
#[derive(Debug, Clone, Copy)]
pub struct AssetHubWestend;
impl UnderlyingChainProvider for AssetHubWestend {
type Chain = millau_runtime::bp_bridged_chain::AssetHubWestend;
}
// Westmint seems to use the same configuration as all Polkadot-like chains, so we'll use
// Westend primitives here.
impl Chain for AssetHubWestend {
const ID: ChainId = bp_runtime::ASSET_HUB_WESTEND_CHAIN_ID;
const NAME: &'static str = "Westmint";
const BEST_FINALIZED_HEADER_ID_METHOD: &'static str =
millau_runtime::bp_bridged_chain::BEST_FINALIZED_ASSETHUBWESTEND_HEADER_METHOD;
const AVERAGE_BLOCK_INTERVAL: Duration = Duration::from_secs(6);
type SignedBlock = bp_polkadot_core::SignedBlock;
type Call = ();
}
}
@@ -1,75 +0,0 @@
// 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/>.
//! Millau chain specification for CLI.
use crate::cli::{encode_message::CliEncodeMessage, CliChain};
use bp_runtime::EncodedOrDecodedCall;
use bridge_runtime_common::CustomNetworkId;
use relay_millau_client::Millau;
use relay_substrate_client::SimpleRuntimeVersion;
use xcm_executor::traits::ExportXcm;
impl CliEncodeMessage for Millau {
fn encode_wire_message(
target: xcm::v3::NetworkId,
at_target_xcm: xcm::v3::Xcm<()>,
) -> anyhow::Result<Vec<u8>> {
anyhow::ensure!(
[
CustomNetworkId::Rialto.as_network_id(),
CustomNetworkId::RialtoParachain.as_network_id()
]
.contains(&target),
anyhow::format_err!("Unsupported target chain: {:?}", target)
);
Ok(millau_runtime::xcm_config::ToRialtoOrRialtoParachainSwitchExporter::validate(
target,
0,
&mut Some(Self::dummy_universal_source()?),
&mut Some(target.into()),
&mut Some(at_target_xcm),
)
.map_err(|e| anyhow::format_err!("Failed to prepare outbound message: {:?}", e))?
.0
.1
.0)
}
fn encode_execute_xcm(
message: xcm::VersionedXcm<Self::Call>,
) -> anyhow::Result<EncodedOrDecodedCall<Self::Call>> {
Ok(millau_runtime::RuntimeCall::XcmPallet(millau_runtime::XcmCall::execute {
message: Box::new(message),
max_weight: Self::estimate_execute_xcm_weight(),
})
.into())
}
}
impl CliChain for Millau {
const RUNTIME_VERSION: Option<SimpleRuntimeVersion> =
Some(SimpleRuntimeVersion::from_runtime_version(&millau_runtime::VERSION));
}
/// TODO: Note: I know this does not belong here, but I don't want to add it to the
/// `chain-asset-hub-westend` or `chain-westend`, because we wont use it for production and I don't
/// want to bring this to the bridges subtree now. Anyway, we plan to retire millau/rialto, so this
/// hack will disappear with that.
impl CliChain for crate::bridges::westend_millau::westend_parachains_to_millau::relay_asset_hub_westend_client::AssetHubWestend {
const RUNTIME_VERSION: Option<SimpleRuntimeVersion> = None;
}
@@ -17,95 +17,8 @@
//! Chain-specific relayer configuration.
mod kusama;
mod millau;
mod polkadot;
mod polkadot_bulletin;
mod rialto;
mod rialto_parachain;
mod rococo;
mod westend;
mod wococo;
#[cfg(test)]
mod tests {
use crate::cli::encode_message;
use bp_messages::source_chain::TargetHeaderChain;
use bp_runtime::Chain as _;
use codec::Encode;
use relay_millau_client::Millau;
use relay_rialto_client::Rialto;
use relay_substrate_client::{ChainWithTransactions, SignParam, UnsignedTransaction};
#[test]
fn maximal_rialto_to_millau_message_size_is_computed_correctly() {
use rialto_runtime::millau_messages::MillauAsTargetHeaderChain;
let maximal_message_size = encode_message::compute_maximal_message_size(
bp_rialto::Rialto::max_extrinsic_size(),
bp_millau::Millau::max_extrinsic_size(),
);
let message = vec![42; maximal_message_size as _];
assert_eq!(MillauAsTargetHeaderChain::verify_message(&message), Ok(()));
let message = vec![42; (maximal_message_size + 1) as _];
assert!(MillauAsTargetHeaderChain::verify_message(&message).is_err());
}
#[test]
fn maximal_size_remark_to_rialto_is_generated_correctly() {
assert!(
bridge_runtime_common::messages::target::maximal_incoming_message_size(
bp_rialto::Rialto::max_extrinsic_size()
) > bp_millau::Millau::max_extrinsic_size(),
"We can't actually send maximal messages to Rialto from Millau, because Millau extrinsics can't be that large",
)
}
#[test]
fn rialto_tx_extra_bytes_constant_is_correct() {
let rialto_call = rialto_runtime::RuntimeCall::System(rialto_runtime::SystemCall::remark {
remark: vec![],
});
let rialto_tx = Rialto::sign_transaction(
SignParam {
spec_version: 1,
transaction_version: 1,
genesis_hash: Default::default(),
signer: sp_keyring::AccountKeyring::Alice.pair(),
},
UnsignedTransaction::new(rialto_call.clone().into(), 0),
)
.unwrap();
let extra_bytes_in_transaction = rialto_tx.encode().len() - rialto_call.encode().len();
assert!(
bp_rialto::TX_EXTRA_BYTES as usize >= extra_bytes_in_transaction,
"Hardcoded number of extra bytes in Rialto transaction {} is lower than actual value: {}",
bp_rialto::TX_EXTRA_BYTES,
extra_bytes_in_transaction,
);
}
#[test]
fn millau_tx_extra_bytes_constant_is_correct() {
let millau_call = millau_runtime::RuntimeCall::System(millau_runtime::SystemCall::remark {
remark: vec![],
});
let millau_tx = Millau::sign_transaction(
SignParam {
spec_version: 0,
transaction_version: 0,
genesis_hash: Default::default(),
signer: sp_keyring::AccountKeyring::Alice.pair(),
},
UnsignedTransaction::new(millau_call.clone().into(), 0),
)
.unwrap();
let extra_bytes_in_transaction = millau_tx.encode().len() - millau_call.encode().len();
assert!(
bp_millau::TX_EXTRA_BYTES as usize >= extra_bytes_in_transaction,
"Hardcoded number of extra bytes in Millau transaction {} is lower than actual value: {}",
bp_millau::TX_EXTRA_BYTES,
extra_bytes_in_transaction,
);
}
}
@@ -1,62 +0,0 @@
// 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/>.
//! Rialto chain specification for CLI.
use crate::cli::{encode_message::CliEncodeMessage, CliChain};
use bp_runtime::EncodedOrDecodedCall;
use bridge_runtime_common::CustomNetworkId;
use relay_rialto_client::Rialto;
use relay_substrate_client::SimpleRuntimeVersion;
use xcm_executor::traits::ExportXcm;
impl CliEncodeMessage for Rialto {
fn encode_wire_message(
target: xcm::v3::NetworkId,
at_target_xcm: xcm::v3::Xcm<()>,
) -> anyhow::Result<Vec<u8>> {
anyhow::ensure!(
target == CustomNetworkId::Millau.as_network_id(),
anyhow::format_err!("Unsupported target chain: {:?}", target)
);
Ok(rialto_runtime::millau_messages::ToMillauBlobExporter::validate(
target,
0,
&mut Some(Self::dummy_universal_source()?),
&mut Some(target.into()),
&mut Some(at_target_xcm),
)
.map_err(|e| anyhow::format_err!("Failed to prepare outbound message: {:?}", e))?
.0
.0)
}
fn encode_execute_xcm(
message: xcm::VersionedXcm<Self::Call>,
) -> anyhow::Result<EncodedOrDecodedCall<Self::Call>> {
Ok(rialto_runtime::RuntimeCall::XcmPallet(rialto_runtime::XcmCall::execute {
message: Box::new(message),
max_weight: Self::estimate_execute_xcm_weight(),
})
.into())
}
}
impl CliChain for Rialto {
const RUNTIME_VERSION: Option<SimpleRuntimeVersion> =
Some(SimpleRuntimeVersion::from_runtime_version(&rialto_runtime::VERSION));
}
@@ -1,65 +0,0 @@
// 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/>.
//! Rialto parachain specification for CLI.
use crate::cli::{encode_message::CliEncodeMessage, CliChain};
use bp_runtime::EncodedOrDecodedCall;
use bridge_runtime_common::CustomNetworkId;
use relay_rialto_parachain_client::RialtoParachain;
use relay_substrate_client::SimpleRuntimeVersion;
use xcm_executor::traits::ExportXcm;
impl CliEncodeMessage for RialtoParachain {
fn encode_wire_message(
target: xcm::v3::NetworkId,
at_target_xcm: xcm::v3::Xcm<()>,
) -> anyhow::Result<Vec<u8>> {
anyhow::ensure!(
target == CustomNetworkId::Millau.as_network_id(),
anyhow::format_err!("Unsupported target chain: {:?}", target)
);
Ok(rialto_parachain_runtime::millau_messages::ToMillauBlobExporter::validate(
target,
0,
&mut Some(Self::dummy_universal_source()?),
&mut Some(target.into()),
&mut Some(at_target_xcm),
)
.map_err(|e| anyhow::format_err!("Failed to prepare outbound message: {:?}", e))?
.0
.0)
}
fn encode_execute_xcm(
message: xcm::VersionedXcm<Self::Call>,
) -> anyhow::Result<EncodedOrDecodedCall<Self::Call>> {
type RuntimeCall = relay_rialto_parachain_client::RuntimeCall;
type XcmCall = relay_rialto_parachain_client::runtime_types::pallet_xcm::pallet::Call;
let xcm_call = XcmCall::execute {
message: Box::new(unsafe { std::mem::transmute(message) }),
max_weight: Self::estimate_execute_xcm_weight(),
};
Ok(RuntimeCall::PolkadotXcm(xcm_call).into())
}
}
impl CliChain for RialtoParachain {
const RUNTIME_VERSION: Option<SimpleRuntimeVersion> = None;
}
@@ -29,10 +29,6 @@ use substrate_relay_helper::{
#[strum(serialize_all = "kebab_case")]
/// Supported full bridges (headers + messages).
pub enum FullBridge {
MillauToRialto,
RialtoToMillau,
MillauToRialtoParachain,
RialtoParachainToMillau,
BridgeHubRococoToBridgeHubWococo,
BridgeHubWococoToBridgeHubRococo,
BridgeHubRococoToBridgeHubWestend,
@@ -129,29 +129,6 @@ macro_rules! declare_chain_connection_params_cli_schema {
};
}
/// Helper trait to override transaction parameters differently.
pub trait TransactionParamsProvider {
/// Returns `true` if transaction parameters are defined by this provider.
fn is_defined(&self) -> bool;
/// Returns transaction parameters.
fn transaction_params<Chain: ChainWithTransactions>(
&self,
) -> anyhow::Result<TransactionParams<AccountKeyPairOf<Chain>>>;
/// Returns transaction parameters, defined by `self` provider or, if they're not defined,
/// defined by `other` provider.
fn transaction_params_or<Chain: ChainWithTransactions, T: TransactionParamsProvider>(
&self,
other: &T,
) -> anyhow::Result<TransactionParams<AccountKeyPairOf<Chain>>> {
if self.is_defined() {
self.transaction_params::<Chain>()
} else {
other.transaction_params::<Chain>()
}
}
}
/// Create chain-specific set of signing parameters.
#[macro_export]
macro_rules! declare_chain_signing_params_cli_schema {
@@ -239,15 +216,12 @@ macro_rules! declare_chain_signing_params_cli_schema {
suri_password.as_deref()
).map_err(|e| anyhow::format_err!("{:?}", e))
}
}
#[allow(dead_code)]
impl TransactionParamsProvider for [<$chain SigningParams>] {
fn is_defined(&self) -> bool {
self.[<$chain_prefix _signer>].is_some() || self.[<$chain_prefix _signer_file>].is_some()
}
fn transaction_params<Chain: ChainWithTransactions>(&self) -> anyhow::Result<TransactionParams<AccountKeyPairOf<Chain>>> {
/// Return transaction parameters.
#[allow(dead_code)]
pub fn transaction_params<Chain: ChainWithTransactions>(
&self,
) -> anyhow::Result<TransactionParams<AccountKeyPairOf<Chain>>> {
Ok(TransactionParams {
mortality: self.transactions_mortality()?,
signer: self.to_keypair::<Chain>()?,
@@ -310,7 +284,7 @@ mod tests {
target_transactions_mortality: None,
}
.to_keypair::<relay_rialto_client::Rialto>()
.to_keypair::<relay_polkadot_client::Polkadot>()
.map(|p| p.public())
.map_err(drop),
Ok(alice.public()),
@@ -327,7 +301,7 @@ mod tests {
target_transactions_mortality: None,
}
.to_keypair::<relay_rialto_client::Rialto>()
.to_keypair::<relay_polkadot_client::Polkadot>()
.map(|p| p.public())
.map_err(drop),
Ok(bob.public()),
@@ -344,7 +318,7 @@ mod tests {
target_transactions_mortality: None,
}
.to_keypair::<relay_rialto_client::Rialto>()
.to_keypair::<relay_polkadot_client::Polkadot>()
.map(|p| p.public())
.map_err(drop),
Ok(bob_with_alice_password.public()),
@@ -361,7 +335,7 @@ mod tests {
target_transactions_mortality: None,
}
.to_keypair::<relay_rialto_client::Rialto>()
.to_keypair::<relay_polkadot_client::Polkadot>()
.map(|p| p.public())
.map_err(drop),
Ok(alice.public()),
@@ -20,11 +20,6 @@ use crate::{
kusama_headers_to_bridge_hub_polkadot::KusamaToBridgeHubPolkadotCliBridge,
polkadot_headers_to_bridge_hub_kusama::PolkadotToBridgeHubKusamaCliBridge,
},
rialto_millau::{
millau_headers_to_rialto::MillauToRialtoCliBridge,
rialto_headers_to_millau::RialtoToMillauCliBridge,
},
rialto_parachain_millau::millau_headers_to_rialto_parachain::MillauToRialtoParachainCliBridge,
rococo_wococo::{
rococo_headers_to_bridge_hub_wococo::RococoToBridgeHubWococoCliBridge,
wococo_headers_to_bridge_hub_rococo::WococoToBridgeHubRococoCliBridge,
@@ -58,9 +53,6 @@ pub struct DetectEquivocations {
#[strum(serialize_all = "kebab_case")]
/// Equivocations detection bridge.
pub enum DetectEquivocationsBridge {
MillauToRialto,
RialtoToMillau,
MillauToRialtoParachain,
RococoToBridgeHubWococo,
WococoToBridgeHubRococo,
KusamaToBridgeHubPolkadot,
@@ -90,9 +82,6 @@ where
}
}
impl EquivocationsDetector for MillauToRialtoCliBridge {}
impl EquivocationsDetector for RialtoToMillauCliBridge {}
impl EquivocationsDetector for MillauToRialtoParachainCliBridge {}
impl EquivocationsDetector for RococoToBridgeHubWococoCliBridge {}
impl EquivocationsDetector for WococoToBridgeHubRococoCliBridge {}
impl EquivocationsDetector for KusamaToBridgeHubPolkadotCliBridge {}
@@ -102,10 +91,6 @@ impl DetectEquivocations {
/// Run the command.
pub async fn run(self) -> anyhow::Result<()> {
match self.bridge {
DetectEquivocationsBridge::MillauToRialto => MillauToRialtoCliBridge::start(self),
DetectEquivocationsBridge::RialtoToMillau => RialtoToMillauCliBridge::start(self),
DetectEquivocationsBridge::MillauToRialtoParachain =>
MillauToRialtoParachainCliBridge::start(self),
DetectEquivocationsBridge::RococoToBridgeHubWococo =>
RococoToBridgeHubWococoCliBridge::start(self),
DetectEquivocationsBridge::WococoToBridgeHubRococo =>
@@ -1,189 +0,0 @@
// 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::cli::{ExplicitOrMaximal, HexBytes};
use bp_runtime::EncodedOrDecodedCall;
use bridge_runtime_common::CustomNetworkId;
use codec::Encode;
use frame_support::weights::Weight;
use relay_substrate_client::Chain;
use structopt::StructOpt;
use xcm::latest::prelude::*;
/// All possible messages that may be delivered to generic Substrate chain.
///
/// Note this enum may be used in the context of both Source (as part of `encode-call`)
/// and Target chain (as part of `encode-message/send-message`).
#[derive(StructOpt, Debug, PartialEq, Eq)]
pub enum Message {
/// Raw bytes for the message.
Raw {
/// Raw message bytes.
data: HexBytes,
},
/// Message with given size.
Sized {
/// Sized of the message.
size: ExplicitOrMaximal<u32>,
},
}
/// Raw, SCALE-encoded message payload used in expected deployment.
pub type RawMessage = Vec<u8>;
pub trait CliEncodeMessage: Chain {
/// Returns dummy `AccountId32` universal source given this network id.
fn dummy_universal_source() -> anyhow::Result<xcm::v3::Junctions> {
use xcm::v3::prelude::*;
let this_network = CustomNetworkId::try_from(Self::ID)
.map(|n| n.as_network_id())
.map_err(|_| anyhow::format_err!("Unsupported chain: {:?}", Self::ID))?;
Ok(X2(
GlobalConsensus(this_network),
AccountId32 { network: Some(this_network), id: [0u8; 32] },
))
}
/// Returns XCM blob that is passed to the `send_message` function of the messages pallet
/// and then is sent over the wire.
fn encode_wire_message(target: NetworkId, at_target_xcm: Xcm<()>) -> anyhow::Result<Vec<u8>>;
/// Encode an `execute` XCM call of the XCM pallet.
fn encode_execute_xcm(
message: xcm::VersionedXcm<Self::Call>,
) -> anyhow::Result<EncodedOrDecodedCall<Self::Call>>;
/// Estimate value of `max_weight` argument for the `execute` XCM call of the XCM pallet.
fn estimate_execute_xcm_weight() -> Weight {
// we are only executing XCM on our testnets and 1/100 of max extrinsic weight is ok
Self::max_extrinsic_weight() / 100
}
}
/// Encode message payload passed through CLI flags.
pub(crate) fn encode_message<Source: CliEncodeMessage, Target: Chain>(
message: &Message,
) -> anyhow::Result<RawMessage> {
Ok(match message {
Message::Raw { ref data } => data.0.clone(),
Message::Sized { ref size } => {
let destination = CustomNetworkId::try_from(Target::ID)
.map(|n| n.as_network_id())
.map_err(|_| anyhow::format_err!("Unsupported target chain: {:?}", Target::ID))?;
let expected_size = match *size {
ExplicitOrMaximal::Explicit(size) => size,
ExplicitOrMaximal::Maximal => compute_maximal_message_size(
Source::max_extrinsic_size(),
Target::max_extrinsic_size(),
),
} as usize;
let at_target_xcm = vec![ExpectPallet {
index: 0,
name: vec![42; expected_size],
module_name: vec![],
crate_major: 0,
min_crate_minor: 0,
}]
.into();
let at_target_xcm_size =
Source::encode_wire_message(destination, at_target_xcm)?.encoded_size();
let at_target_xcm_overhead = at_target_xcm_size.saturating_sub(expected_size);
let at_target_xcm = vec![ExpectPallet {
index: 0,
name: vec![42; expected_size.saturating_sub(at_target_xcm_overhead)],
module_name: vec![],
crate_major: 0,
min_crate_minor: 0,
}]
.into();
xcm::VersionedXcm::<()>::V3(
vec![ExportMessage {
network: destination,
destination: destination.into(),
xcm: at_target_xcm,
}]
.into(),
)
.encode()
},
})
}
/// Compute maximal message size, given max extrinsic size at source and target chains.
pub(crate) fn compute_maximal_message_size(
maximal_source_extrinsic_size: u32,
maximal_target_extrinsic_size: u32,
) -> u32 {
// assume that both signed extensions and other arguments fit 1KB
let service_tx_bytes_on_source_chain = 1024;
let maximal_source_extrinsic_size =
maximal_source_extrinsic_size - service_tx_bytes_on_source_chain;
let maximal_message_size =
bridge_runtime_common::messages::target::maximal_incoming_message_size(
maximal_target_extrinsic_size,
);
std::cmp::min(maximal_message_size, maximal_source_extrinsic_size)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cli::send_message::decode_xcm;
use bp_runtime::Chain;
use relay_millau_client::Millau;
use relay_rialto_client::Rialto;
fn approximate_message_size<Source: CliEncodeMessage>(xcm_msg_len: usize) -> usize {
xcm_msg_len + Source::dummy_universal_source().unwrap().encoded_size()
}
#[test]
fn encode_explicit_size_message_works() {
let msg = encode_message::<Rialto, Millau>(&Message::Sized {
size: ExplicitOrMaximal::Explicit(100),
})
.unwrap();
// since it isn't the returned XCM what is sent over the wire, we can only check if
// it is close to what we need
assert!(
(1f64 - (approximate_message_size::<Rialto>(msg.len()) as f64) / 100_f64).abs() < 0.1
);
// check that it decodes to valid xcm
let _ = decode_xcm::<()>(msg).unwrap();
}
#[test]
fn encode_maximal_size_message_works() {
let maximal_size = compute_maximal_message_size(
Rialto::max_extrinsic_size(),
Millau::max_extrinsic_size(),
);
let msg =
encode_message::<Rialto, Millau>(&Message::Sized { size: ExplicitOrMaximal::Maximal })
.unwrap();
// since it isn't the returned XCM what is sent over the wire, we can only check if
// it is close to what we need
assert!(
(1f64 - approximate_message_size::<Rialto>(msg.len()) as f64 / maximal_size as f64)
.abs() < 0.1
);
// check that it decodes to valid xcm
let _ = decode_xcm::<()>(msg).unwrap();
}
}
@@ -27,11 +27,6 @@ use crate::{
polkadot_bulletin_headers_to_bridge_hub_polkadot::PolkadotBulletinToBridgeHubPolkadotCliBridge,
polkadot_headers_to_polkadot_bulletin::PolkadotToPolkadotBulletinCliBridge,
},
rialto_millau::{
millau_headers_to_rialto::MillauToRialtoCliBridge,
rialto_headers_to_millau::RialtoToMillauCliBridge,
},
rialto_parachain_millau::millau_headers_to_rialto_parachain::MillauToRialtoParachainCliBridge,
rococo_westend::{
rococo_headers_to_bridge_hub_westend::RococoToBridgeHubWestendCliBridge,
westend_headers_to_bridge_hub_rococo::WestendToBridgeHubRococoCliBridge,
@@ -40,7 +35,6 @@ use crate::{
rococo_headers_to_bridge_hub_wococo::RococoToBridgeHubWococoCliBridge,
wococo_headers_to_bridge_hub_rococo::WococoToBridgeHubRococoCliBridge,
},
westend_millau::westend_headers_to_millau::WestendToMillauCliBridge,
},
cli::{bridge::CliBridgeBase, chain_schema::*},
};
@@ -72,10 +66,6 @@ pub struct InitBridge {
#[strum(serialize_all = "kebab_case")]
/// Bridge to initialize.
pub enum InitBridgeName {
MillauToRialto,
RialtoToMillau,
WestendToMillau,
MillauToRialtoParachain,
RococoToBridgeHubWococo,
WococoToBridgeHubRococo,
KusamaToBridgeHubPolkadot,
@@ -126,72 +116,6 @@ where
}
}
impl BridgeInitializer for MillauToRialtoCliBridge {
type Engine = GrandpaFinalityEngine<Self::Source>;
fn encode_init_bridge(
init_data: <Self::Engine as Engine<Self::Source>>::InitializationData,
) -> <Self::Target as Chain>::Call {
rialto_runtime::SudoCall::sudo {
call: Box::new(rialto_runtime::BridgeGrandpaCall::initialize { init_data }.into()),
}
.into()
}
}
impl BridgeInitializer for MillauToRialtoParachainCliBridge {
type Engine = GrandpaFinalityEngine<Self::Source>;
fn encode_init_bridge(
init_data: <Self::Engine as Engine<Self::Source>>::InitializationData,
) -> <Self::Target as Chain>::Call {
type RuntimeCall = relay_rialto_parachain_client::RuntimeCall;
type BridgeGrandpaCall = relay_rialto_parachain_client::BridgeGrandpaCall;
type SudoCall = relay_rialto_parachain_client::SudoCall;
let initialize_call =
RuntimeCall::BridgeMillauGrandpa(BridgeGrandpaCall::initialize { init_data });
RuntimeCall::Sudo(SudoCall::sudo { call: Box::new(initialize_call) })
}
}
impl BridgeInitializer for RialtoToMillauCliBridge {
type Engine = GrandpaFinalityEngine<Self::Source>;
fn encode_init_bridge(
init_data: <Self::Engine as Engine<Self::Source>>::InitializationData,
) -> <Self::Target as Chain>::Call {
let initialize_call = millau_runtime::BridgeGrandpaCall::<
millau_runtime::Runtime,
millau_runtime::RialtoGrandpaInstance,
>::initialize {
init_data,
};
millau_runtime::SudoCall::sudo { call: Box::new(initialize_call.into()) }.into()
}
}
impl BridgeInitializer for WestendToMillauCliBridge {
type Engine = GrandpaFinalityEngine<Self::Source>;
fn encode_init_bridge(
init_data: <Self::Engine as Engine<Self::Source>>::InitializationData,
) -> <Self::Target as Chain>::Call {
// at Westend -> Millau initialization we're not using sudo, because otherwise
// our deployments may fail, because we need to initialize both Rialto -> Millau
// and Westend -> Millau bridge. => since there's single possible sudo account,
// one of transaction may fail with duplicate nonce error
millau_runtime::BridgeGrandpaCall::<
millau_runtime::Runtime,
millau_runtime::WestendGrandpaInstance,
>::initialize {
init_data,
}
.into()
}
}
impl BridgeInitializer for RococoToBridgeHubWococoCliBridge {
type Engine = GrandpaFinalityEngine<Self::Source>;
@@ -305,11 +229,6 @@ impl InitBridge {
/// Run the command.
pub async fn run(self) -> anyhow::Result<()> {
match self.bridge {
InitBridgeName::MillauToRialto => MillauToRialtoCliBridge::init_bridge(self),
InitBridgeName::RialtoToMillau => RialtoToMillauCliBridge::init_bridge(self),
InitBridgeName::WestendToMillau => WestendToMillauCliBridge::init_bridge(self),
InitBridgeName::MillauToRialtoParachain =>
MillauToRialtoParachainCliBridge::init_bridge(self),
InitBridgeName::RococoToBridgeHubWococo =>
RococoToBridgeHubWococoCliBridge::init_bridge(self),
InitBridgeName::WococoToBridgeHubRococo =>
+1 -46
View File
@@ -16,8 +16,6 @@
//! Deal with CLI args of substrate-to-substrate relay.
use std::convert::TryInto;
use async_std::prelude::*;
use codec::{Decode, Encode};
use futures::{select, FutureExt};
@@ -31,18 +29,14 @@ use bp_messages::LaneId;
use relay_substrate_client::SimpleRuntimeVersion;
pub(crate) mod bridge;
pub(crate) mod encode_message;
pub(crate) mod send_message;
mod chain_schema;
mod detect_equivocations;
mod init_bridge;
mod register_parachain;
mod relay_headers;
mod relay_headers_and_messages;
mod relay_messages;
mod relay_parachains;
mod resubmit_transactions;
/// The target that will be used when publishing logs related to this pallet.
pub const LOG_TARGET: &str = "bridge";
@@ -77,16 +71,6 @@ pub enum Command {
///
/// Sends initialization transaction to bootstrap the bridge with current finalized block data.
InitBridge(init_bridge::InitBridge),
/// Send custom message over the bridge.
///
/// Allows interacting with the bridge by sending messages over `Messages` component.
/// The message is being sent to the source chain, delivered to the target chain and dispatched
/// there.
SendMessage(send_message::SendMessage),
/// Resubmit transactions with increased tip if they are stalled.
ResubmitTransactions(resubmit_transactions::ResubmitTransactions),
/// Register parachain.
RegisterParachain(register_parachain::RegisterParachain),
/// Relay parachain heads.
RelayParachains(relay_parachains::RelayParachains),
/// Detect and report equivocations.
@@ -121,9 +105,6 @@ impl Command {
Self::RelayMessages(arg) => arg.run().await?,
Self::RelayHeadersAndMessages(arg) => arg.run().await?,
Self::InitBridge(arg) => arg.run().await?,
Self::SendMessage(arg) => arg.run().await?,
Self::ResubmitTransactions(arg) => arg.run().await?,
Self::RegisterParachain(arg) => arg.run().await?,
Self::RelayParachains(arg) => arg.run().await?,
Self::DetectEquivocations(arg) => arg.run().await?,
}
@@ -169,33 +150,7 @@ arg_enum! {
}
}
/// Generic balance type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Balance(pub u128);
impl std::fmt::Display for Balance {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
use num_format::{Locale, ToFormattedString};
write!(fmt, "{}", self.0.to_formatted_string(&Locale::en))
}
}
impl std::str::FromStr for Balance {
type Err = <u128 as std::str::FromStr>::Err;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self(s.parse()?))
}
}
impl Balance {
/// Cast balance to `u64` type, panicking if it's too large.
pub fn cast(&self) -> u64 {
self.0.try_into().expect("Balance is too high for this chain.")
}
}
// Bridge-supported network definition.
/// Bridge-supported network definition.
///
/// Used to abstract away CLI commands.
pub trait CliChain: relay_substrate_client::Chain {
@@ -1,324 +0,0 @@
// 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::cli::{chain_schema::*, Balance};
use codec::Encode;
use frame_support::Twox64Concat;
use num_traits::Zero;
use polkadot_parachain_primitives::primitives::{
HeadData as ParaHeadData, Id as ParaId, ValidationCode as ParaValidationCode,
};
use polkadot_runtime_common::{
paras_registrar::Call as ParaRegistrarCall, slots::Call as ParaSlotsCall,
};
use polkadot_runtime_parachains::paras::ParaLifecycle;
use relay_substrate_client::{AccountIdOf, CallOf, Chain, Client, UnsignedTransaction};
use relay_utils::{TrackedTransactionStatus, TransactionTracker};
use rialto_runtime::SudoCall;
use sp_core::{
storage::{well_known_keys::CODE, StorageKey},
Pair,
};
use structopt::StructOpt;
use strum::{EnumString, EnumVariantNames, VariantNames};
/// Name of the `NextFreeParaId` value in the `polkadot_runtime_common::paras_registrar` pallet.
const NEXT_FREE_PARA_ID_STORAGE_NAME: &str = "NextFreeParaId";
/// Name of the `ParaLifecycles` map in the `polkadot_runtime_parachains::paras` pallet.
const PARAS_LIFECYCLES_STORAGE_NAME: &str = "ParaLifecycles";
/// Register parachain.
#[derive(StructOpt, Debug, PartialEq, Eq)]
pub struct RegisterParachain {
/// A parachain to register.
#[structopt(possible_values = Parachain::VARIANTS, case_insensitive = true)]
parachain: Parachain,
/// Parachain deposit.
#[structopt(long, default_value = "0")]
deposit: Balance,
/// Lease begin.
#[structopt(long, default_value = "0")]
lease_begin: u32,
/// Lease end.
#[structopt(long, default_value = "256")]
lease_end: u32,
#[structopt(flatten)]
relay_connection: RelaychainConnectionParams,
#[structopt(flatten)]
relay_sign: RelaychainSigningParams,
#[structopt(flatten)]
para_connection: ParachainConnectionParams,
}
/// Parachain to register.
#[derive(Debug, EnumString, EnumVariantNames, PartialEq, Eq)]
#[strum(serialize_all = "kebab_case")]
pub enum Parachain {
RialtoParachain,
}
macro_rules! select_bridge {
($bridge: expr, $generic: tt) => {
match $bridge {
Parachain::RialtoParachain => {
type Relaychain = relay_rialto_client::Rialto;
type Parachain = relay_rialto_parachain_client::RialtoParachain;
use bp_rialto::{PARAS_PALLET_NAME, PARAS_REGISTRAR_PALLET_NAME};
$generic
},
}
};
}
impl RegisterParachain {
/// Run the command.
pub async fn run(self) -> anyhow::Result<()> {
select_bridge!(self.parachain, {
let relay_client = self.relay_connection.into_client::<Relaychain>().await?;
let relay_sign = self.relay_sign.to_keypair::<Relaychain>()?;
let para_client = self.para_connection.into_client::<Parachain>().await?;
// hopefully we're the only actor that is registering parachain right now
// => read next parachain id
let para_id_key = bp_runtime::storage_value_final_key(
PARAS_REGISTRAR_PALLET_NAME.as_bytes(),
NEXT_FREE_PARA_ID_STORAGE_NAME.as_bytes(),
);
let para_id: ParaId = relay_client
.storage_value(StorageKey(para_id_key.to_vec()), None)
.await?
.unwrap_or(polkadot_primitives::v6::LOWEST_PUBLIC_ID)
.max(polkadot_primitives::v6::LOWEST_PUBLIC_ID);
log::info!(target: "bridge", "Going to reserve parachain id: {:?}", para_id);
// step 1: reserve a parachain id
let relay_sudo_account: AccountIdOf<Relaychain> = relay_sign.public().into();
let reserve_parachain_id_call: CallOf<Relaychain> =
ParaRegistrarCall::reserve {}.into();
let reserve_result = relay_client
.submit_and_watch_signed_extrinsic(&relay_sign, move |_, transaction_nonce| {
Ok(UnsignedTransaction::new(
reserve_parachain_id_call.into(),
transaction_nonce,
))
})
.await?
.wait()
.await;
if reserve_result == TrackedTransactionStatus::Lost {
return Err(anyhow::format_err!(
"Failed to finalize `reserve-parachain-id` transaction"
))
}
log::info!(target: "bridge", "Reserved parachain id: {:?}", para_id);
// step 2: register parathread
let para_genesis_header = para_client.header_by_number(Zero::zero()).await?;
let para_code = para_client
.raw_storage_value(StorageKey(CODE.to_vec()), Some(para_genesis_header.hash()))
.await?
.ok_or_else(|| {
anyhow::format_err!("Cannot fetch validation code of {}", Parachain::NAME)
})?
.0;
log::info!(
target: "bridge",
"Going to register parachain {:?}: genesis len = {} code len = {}",
para_id,
para_genesis_header.encode().len(),
para_code.len(),
);
let register_parathread_call: CallOf<Relaychain> = ParaRegistrarCall::register {
id: para_id,
genesis_head: ParaHeadData(para_genesis_header.encode()),
validation_code: ParaValidationCode(para_code),
}
.into();
let register_result = relay_client
.submit_and_watch_signed_extrinsic(&relay_sign, move |_, transaction_nonce| {
Ok(UnsignedTransaction::new(register_parathread_call.into(), transaction_nonce))
})
.await?
.wait()
.await;
if register_result == TrackedTransactionStatus::Lost {
return Err(anyhow::format_err!(
"Failed to finalize `register-parathread` transaction"
))
}
log::info!(target: "bridge", "Registered parachain: {:?}. Waiting for onboarding", para_id);
// wait until parathread is onboarded
let para_state_key = bp_runtime::storage_map_final_key::<Twox64Concat>(
PARAS_PALLET_NAME,
PARAS_LIFECYCLES_STORAGE_NAME,
&para_id.encode(),
);
wait_para_state(
&relay_client,
&para_state_key.0,
&[ParaLifecycle::Onboarding, ParaLifecycle::Parathread],
ParaLifecycle::Parathread,
)
.await?;
// step 3: force parachain leases
let lease_begin = self.lease_begin;
let lease_end = self.lease_end;
let para_deposit = self.deposit.cast().into();
log::info!(
target: "bridge",
"Going to force leases of parachain {:?}: [{}; {}]",
para_id,
lease_begin,
lease_end,
);
let force_lease_call: CallOf<Relaychain> = SudoCall::sudo {
call: Box::new(
ParaSlotsCall::force_lease {
para: para_id,
leaser: relay_sudo_account.clone(),
amount: para_deposit,
period_begin: lease_begin,
period_count: lease_end.saturating_sub(lease_begin).saturating_add(1),
}
.into(),
),
}
.into();
relay_client
.submit_signed_extrinsic(&relay_sign, move |_, transaction_nonce| {
Ok(UnsignedTransaction::new(force_lease_call.into(), transaction_nonce))
})
.await?;
log::info!(target: "bridge", "Registered parachain leases: {:?}. Waiting for onboarding", para_id);
// wait until parachain is onboarded
wait_para_state(
&relay_client,
&para_state_key.0,
&[
ParaLifecycle::Onboarding,
ParaLifecycle::UpgradingParathread,
ParaLifecycle::Parathread,
],
ParaLifecycle::Parachain,
)
.await?;
Ok(())
})
}
}
/// Wait until parachain state is changed.
async fn wait_para_state<Relaychain: Chain>(
relay_client: &Client<Relaychain>,
para_state_key: &[u8],
from_states: &[ParaLifecycle],
to_state: ParaLifecycle,
) -> anyhow::Result<()> {
loop {
let para_state: ParaLifecycle = relay_client
.storage_value(StorageKey(para_state_key.to_vec()), None)
.await?
.ok_or_else(|| {
anyhow::format_err!(
"Cannot fetch next free parachain lifecycle from the runtime storage of {}",
Relaychain::NAME,
)
})?;
if para_state == to_state {
log::info!(target: "bridge", "Parachain state is now: {:?}", to_state);
return Ok(())
}
if !from_states.contains(&para_state) {
return Err(anyhow::format_err!("Invalid parachain lifecycle: {:?}", para_state))
}
log::info!(target: "bridge", "Parachain state: {:?}. Waiting for {:?}", para_state, to_state);
async_std::task::sleep(Relaychain::AVERAGE_BLOCK_INTERVAL).await;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn register_rialto_parachain() {
let register_parachain = RegisterParachain::from_iter(vec![
"register-parachain",
"rialto-parachain",
"--parachain-host",
"127.0.0.1",
"--parachain-port",
"11949",
"--relaychain-host",
"127.0.0.1",
"--relaychain-port",
"9944",
"--relaychain-signer",
"//Alice",
"--deposit",
"42",
"--lease-begin",
"100",
"--lease-end",
"200",
]);
assert_eq!(
register_parachain,
RegisterParachain {
parachain: Parachain::RialtoParachain,
deposit: Balance(42),
lease_begin: 100,
lease_end: 200,
relay_connection: RelaychainConnectionParams {
relaychain_host: "127.0.0.1".into(),
relaychain_port: 9944,
relaychain_secure: false,
relaychain_runtime_version: RelaychainRuntimeVersionParams {
relaychain_version_mode: RuntimeVersionType::Bundle,
relaychain_spec_version: None,
relaychain_transaction_version: None,
}
},
relay_sign: RelaychainSigningParams {
relaychain_signer: Some("//Alice".into()),
relaychain_signer_password: None,
relaychain_signer_file: None,
relaychain_signer_password_file: None,
relaychain_transactions_mortality: None,
},
para_connection: ParachainConnectionParams {
parachain_host: "127.0.0.1".into(),
parachain_port: 11949,
parachain_secure: false,
parachain_runtime_version: ParachainRuntimeVersionParams {
parachain_version_mode: RuntimeVersionType::Bundle,
parachain_spec_version: None,
parachain_transaction_version: None,
}
},
}
);
}
}
@@ -27,16 +27,10 @@ use crate::bridges::{
polkadot_bulletin_headers_to_bridge_hub_polkadot::PolkadotBulletinToBridgeHubPolkadotCliBridge,
polkadot_headers_to_polkadot_bulletin::PolkadotToPolkadotBulletinCliBridge,
},
rialto_millau::{
millau_headers_to_rialto::MillauToRialtoCliBridge,
rialto_headers_to_millau::RialtoToMillauCliBridge,
},
rialto_parachain_millau::millau_headers_to_rialto_parachain::MillauToRialtoParachainCliBridge,
rococo_wococo::{
rococo_headers_to_bridge_hub_wococo::RococoToBridgeHubWococoCliBridge,
wococo_headers_to_bridge_hub_rococo::WococoToBridgeHubRococoCliBridge,
},
westend_millau::westend_headers_to_millau::WestendToMillauCliBridge,
};
use relay_utils::metrics::{GlobalMetrics, StandaloneMetric};
use substrate_relay_helper::finality::SubstrateFinalitySyncPipeline;
@@ -67,10 +61,6 @@ pub struct RelayHeaders {
#[strum(serialize_all = "kebab_case")]
/// Headers relay bridge.
pub enum RelayHeadersBridge {
MillauToRialto,
RialtoToMillau,
WestendToMillau,
MillauToRialtoParachain,
RococoToBridgeHubWococo,
WococoToBridgeHubRococo,
KusamaToBridgeHubPolkadot,
@@ -110,10 +100,6 @@ trait HeadersRelayer: RelayToRelayHeadersCliBridge {
}
}
impl HeadersRelayer for MillauToRialtoCliBridge {}
impl HeadersRelayer for RialtoToMillauCliBridge {}
impl HeadersRelayer for WestendToMillauCliBridge {}
impl HeadersRelayer for MillauToRialtoParachainCliBridge {}
impl HeadersRelayer for RococoToBridgeHubWococoCliBridge {}
impl HeadersRelayer for WococoToBridgeHubRococoCliBridge {}
impl HeadersRelayer for KusamaToBridgeHubPolkadotCliBridge {}
@@ -125,11 +111,6 @@ impl RelayHeaders {
/// Run the command.
pub async fn run(self) -> anyhow::Result<()> {
match self.bridge {
RelayHeadersBridge::MillauToRialto => MillauToRialtoCliBridge::relay_headers(self),
RelayHeadersBridge::RialtoToMillau => RialtoToMillauCliBridge::relay_headers(self),
RelayHeadersBridge::WestendToMillau => WestendToMillauCliBridge::relay_headers(self),
RelayHeadersBridge::MillauToRialtoParachain =>
MillauToRialtoParachainCliBridge::relay_headers(self),
RelayHeadersBridge::RococoToBridgeHubWococo =>
RococoToBridgeHubWococoCliBridge::relay_headers(self),
RelayHeadersBridge::WococoToBridgeHubRococo =>
@@ -36,7 +36,6 @@ use structopt::StructOpt;
use futures::{FutureExt, TryFutureExt};
use relay_to_parachain::*;
use relay_to_relay::*;
use crate::{
bridges::{
@@ -48,14 +47,6 @@ use crate::{
polkadot_bulletin_headers_to_bridge_hub_polkadot::PolkadotBulletinToBridgeHubPolkadotCliBridge,
polkadot_parachains_to_polkadot_bulletin::PolkadotToPolkadotBulletinCliBridge,
},
rialto_millau::{
millau_headers_to_rialto::MillauToRialtoCliBridge,
rialto_headers_to_millau::RialtoToMillauCliBridge,
},
rialto_parachain_millau::{
millau_headers_to_rialto_parachain::MillauToRialtoParachainCliBridge,
rialto_parachains_to_millau::RialtoParachainToMillauCliBridge,
},
rococo_westend::{
rococo_parachains_to_bridge_hub_westend::BridgeHubRococoToBridgeHubWestendCliBridge,
westend_parachains_to_bridge_hub_rococo::BridgeHubWestendToBridgeHubRococoCliBridge,
@@ -203,9 +194,6 @@ where
}
// All supported chains.
declare_chain_cli_schema!(Millau, millau);
declare_chain_cli_schema!(Rialto, rialto);
declare_chain_cli_schema!(RialtoParachain, rialto_parachain);
declare_chain_cli_schema!(Rococo, rococo);
declare_chain_cli_schema!(BridgeHubRococo, bridge_hub_rococo);
declare_chain_cli_schema!(Wococo, wococo);
@@ -217,53 +205,7 @@ declare_chain_cli_schema!(BridgeHubKusama, bridge_hub_kusama);
declare_chain_cli_schema!(Polkadot, polkadot);
declare_chain_cli_schema!(BridgeHubPolkadot, bridge_hub_polkadot);
declare_chain_cli_schema!(PolkadotBulletin, polkadot_bulletin);
// Means to override signers of different layer transactions.
declare_chain_cli_schema!(MillauHeadersToRialto, millau_headers_to_rialto);
declare_chain_cli_schema!(MillauHeadersToRialtoParachain, millau_headers_to_rialto_parachain);
declare_chain_cli_schema!(RialtoHeadersToMillau, rialto_headers_to_millau);
declare_chain_cli_schema!(RialtoParachainsToMillau, rialto_parachains_to_millau);
declare_chain_cli_schema!(RococoHeadersToBridgeHubWococo, rococo_headers_to_bridge_hub_wococo);
declare_chain_cli_schema!(
RococoParachainsToBridgeHubWococo,
rococo_parachains_to_bridge_hub_wococo
);
declare_chain_cli_schema!(WococoHeadersToBridgeHubRococo, wococo_headers_to_bridge_hub_rococo);
declare_chain_cli_schema!(
WococoParachainsToBridgeHubRococo,
wococo_parachains_to_bridge_hub_rococo
);
declare_chain_cli_schema!(RococoHeadersToBridgeHubWestend, rococo_headers_to_bridge_hub_westend);
declare_chain_cli_schema!(
RococoParachainsToBridgeHubWestend,
rococo_parachains_to_bridge_hub_westend
);
declare_chain_cli_schema!(WestendHeadersToBridgeHubRococo, westend_headers_to_bridge_hub_rococo);
declare_chain_cli_schema!(
WestendParachainsToBridgeHubRococo,
westend_parachains_to_bridge_hub_rococo
);
declare_chain_cli_schema!(KusamaHeadersToBridgeHubPolkadot, kusama_headers_to_bridge_hub_polkadot);
declare_chain_cli_schema!(
KusamaParachainsToBridgeHubPolkadot,
kusama_parachains_to_bridge_hub_polkadot
);
declare_chain_cli_schema!(PolkadotHeadersToBridgeHubKusama, polkadot_headers_to_bridge_hub_kusama);
declare_chain_cli_schema!(
PolkadotParachainsToBridgeHubKusama,
polkadot_parachains_to_bridge_hub_kusama
);
declare_chain_cli_schema!(
PolkadotBulletinHeadersToBridgeHubPolkadot,
polkadot_bulletin_headers_to_bridge_hub_polkadot
);
declare_chain_cli_schema!(PolkadotHeadersToPolkadotBulletin, polkadot_headers_to_polkadot_bulletin);
declare_chain_cli_schema!(
PolkadotParachainsToPolkadotBulletin,
polkadot_parachains_to_polkadot_bulletin
);
// All supported bridges.
declare_relay_to_relay_bridge_schema!(Millau, Rialto);
declare_relay_to_parachain_bridge_schema!(Millau, RialtoParachain, Rialto);
declare_parachain_to_parachain_bridge_schema!(BridgeHubRococo, Rococo, BridgeHubWococo, Wococo);
declare_parachain_to_parachain_bridge_schema!(BridgeHubRococo, Rococo, BridgeHubWestend, Westend);
declare_parachain_to_parachain_bridge_schema!(BridgeHubKusama, Kusama, BridgeHubPolkadot, Polkadot);
@@ -434,58 +376,6 @@ where
}
}
/// Millau <> Rialto complex relay.
pub struct MillauRialtoFull2WayBridge {
base: <Self as Full2WayBridge>::Base,
}
#[async_trait]
impl Full2WayBridge for MillauRialtoFull2WayBridge {
type Base = RelayToRelayBridge<Self::L2R, Self::R2L>;
type Left = relay_millau_client::Millau;
type Right = relay_rialto_client::Rialto;
type L2R = MillauToRialtoCliBridge;
type R2L = RialtoToMillauCliBridge;
fn new(base: Self::Base) -> anyhow::Result<Self> {
Ok(Self { base })
}
fn base(&self) -> &Self::Base {
&self.base
}
fn mut_base(&mut self) -> &mut Self::Base {
&mut self.base
}
}
/// Millau <> RialtoParachain complex relay.
pub struct MillauRialtoParachainFull2WayBridge {
base: <Self as Full2WayBridge>::Base,
}
#[async_trait]
impl Full2WayBridge for MillauRialtoParachainFull2WayBridge {
type Base = RelayToParachainBridge<Self::L2R, Self::R2L>;
type Left = relay_millau_client::Millau;
type Right = relay_rialto_parachain_client::RialtoParachain;
type L2R = MillauToRialtoParachainCliBridge;
type R2L = RialtoParachainToMillauCliBridge;
fn new(base: Self::Base) -> anyhow::Result<Self> {
Ok(Self { base })
}
fn base(&self) -> &Self::Base {
&self.base
}
fn mut_base(&mut self) -> &mut Self::Base {
&mut self.base
}
}
/// BridgeHubRococo <> BridgeHubWococo complex relay.
pub struct BridgeHubRococoBridgeHubWococoFull2WayBridge {
base: <Self as Full2WayBridge>::Base,
@@ -593,10 +483,6 @@ impl Full2WayBridge for PolkadotBulletinBridgeHubPolkadotFull2WayBridge {
/// Complex headers+messages relay.
#[derive(Debug, PartialEq, StructOpt)]
pub enum RelayHeadersAndMessages {
/// Millau <> Rialto relay.
MillauRialto(MillauRialtoHeadersAndMessages),
/// Millau <> RialtoParachain relay.
MillauRialtoParachain(MillauRialtoParachainHeadersAndMessages),
/// BridgeHubRococo <> BridgeHubWococo relay.
BridgeHubRococoBridgeHubWococo(BridgeHubRococoBridgeHubWococoHeadersAndMessages),
/// BridgeHubKusama <> BridgeHubPolkadot relay.
@@ -611,12 +497,6 @@ impl RelayHeadersAndMessages {
/// Run the command.
pub async fn run(self) -> anyhow::Result<()> {
match self {
RelayHeadersAndMessages::MillauRialto(params) =>
MillauRialtoFull2WayBridge::new(params.into_bridge().await?)?.run().await,
RelayHeadersAndMessages::MillauRialtoParachain(params) =>
MillauRialtoParachainFull2WayBridge::new(params.into_bridge().await?)?
.run()
.await,
RelayHeadersAndMessages::BridgeHubRococoBridgeHubWococo(params) =>
BridgeHubRococoBridgeHubWococoFull2WayBridge::new(params.into_bridge().await?)?
.run()
@@ -642,130 +522,34 @@ mod tests {
use super::*;
#[test]
fn should_parse_relay_to_relay_options() {
fn should_parse_parachain_to_parachain_options() {
// when
let res = RelayHeadersAndMessages::from_iter(vec![
"relay-headers-and-messages",
"millau-rialto",
"--millau-host",
"millau-node-alice",
"--millau-port",
"bridge-hub-kusama-bridge-hub-polkadot",
"--bridge-hub-kusama-host",
"bridge-hub-kusama-node-collator1",
"--bridge-hub-kusama-port",
"9944",
"--millau-signer",
"//Charlie",
"--millau-transactions-mortality",
"64",
"--rialto-host",
"rialto-node-alice",
"--rialto-port",
"9944",
"--rialto-signer",
"//Charlie",
"--rialto-transactions-mortality",
"64",
"--lane",
"00000000",
"--lane",
"73776170",
"--prometheus-host",
"0.0.0.0",
]);
// then
assert_eq!(
res,
RelayHeadersAndMessages::MillauRialto(MillauRialtoHeadersAndMessages {
shared: HeadersAndMessagesSharedParams {
lane: vec![
HexLaneId([0x00, 0x00, 0x00, 0x00]),
HexLaneId([0x73, 0x77, 0x61, 0x70])
],
only_mandatory_headers: false,
prometheus_params: PrometheusParams {
no_prometheus: false,
prometheus_host: "0.0.0.0".into(),
prometheus_port: 9616,
},
},
left: MillauConnectionParams {
millau_host: "millau-node-alice".into(),
millau_port: 9944,
millau_secure: false,
millau_runtime_version: MillauRuntimeVersionParams {
millau_version_mode: RuntimeVersionType::Bundle,
millau_spec_version: None,
millau_transaction_version: None,
},
},
left_sign: MillauSigningParams {
millau_signer: Some("//Charlie".into()),
millau_signer_password: None,
millau_signer_file: None,
millau_signer_password_file: None,
millau_transactions_mortality: Some(64),
},
left_headers_to_right_sign_override: MillauHeadersToRialtoSigningParams {
millau_headers_to_rialto_signer: None,
millau_headers_to_rialto_signer_password: None,
millau_headers_to_rialto_signer_file: None,
millau_headers_to_rialto_signer_password_file: None,
millau_headers_to_rialto_transactions_mortality: None,
},
right: RialtoConnectionParams {
rialto_host: "rialto-node-alice".into(),
rialto_port: 9944,
rialto_secure: false,
rialto_runtime_version: RialtoRuntimeVersionParams {
rialto_version_mode: RuntimeVersionType::Bundle,
rialto_spec_version: None,
rialto_transaction_version: None,
},
},
right_sign: RialtoSigningParams {
rialto_signer: Some("//Charlie".into()),
rialto_signer_password: None,
rialto_signer_file: None,
rialto_signer_password_file: None,
rialto_transactions_mortality: Some(64),
},
right_headers_to_left_sign_override: RialtoHeadersToMillauSigningParams {
rialto_headers_to_millau_signer: None,
rialto_headers_to_millau_signer_password: None,
rialto_headers_to_millau_signer_file: None,
rialto_headers_to_millau_signer_password_file: None,
rialto_headers_to_millau_transactions_mortality: None,
},
}),
);
}
#[test]
fn should_parse_relay_to_parachain_options() {
// when
let res = RelayHeadersAndMessages::from_iter(vec![
"relay-headers-and-messages",
"millau-rialto-parachain",
"--millau-host",
"millau-node-alice",
"--millau-port",
"9944",
"--millau-signer",
"--bridge-hub-kusama-signer",
"//Iden",
"--rialto-headers-to-millau-signer",
"//Ken",
"--millau-transactions-mortality",
"--bridge-hub-kusama-transactions-mortality",
"64",
"--rialto-parachain-host",
"rialto-parachain-collator-charlie",
"--rialto-parachain-port",
"--kusama-host",
"kusama-alice",
"--kusama-port",
"9944",
"--rialto-parachain-signer",
"--bridge-hub-polkadot-host",
"bridge-hub-polkadot-collator1",
"--bridge-hub-polkadot-port",
"9944",
"--bridge-hub-polkadot-signer",
"//George",
"--rialto-parachain-transactions-mortality",
"--bridge-hub-polkadot-transactions-mortality",
"64",
"--rialto-host",
"rialto-node-alice",
"--rialto-port",
"--polkadot-host",
"polkadot-alice",
"--polkadot-port",
"9944",
"--lane",
"00000000",
@@ -776,8 +560,8 @@ mod tests {
// then
assert_eq!(
res,
RelayHeadersAndMessages::MillauRialtoParachain(
MillauRialtoParachainHeadersAndMessages {
RelayHeadersAndMessages::BridgeHubKusamaBridgeHubPolkadot(
BridgeHubKusamaBridgeHubPolkadotHeadersAndMessages {
shared: HeadersAndMessagesSharedParams {
lane: vec![HexLaneId([0x00, 0x00, 0x00, 0x00])],
only_mandatory_headers: false,
@@ -787,70 +571,59 @@ mod tests {
prometheus_port: 9616,
},
},
left: MillauConnectionParams {
millau_host: "millau-node-alice".into(),
millau_port: 9944,
millau_secure: false,
millau_runtime_version: MillauRuntimeVersionParams {
millau_version_mode: RuntimeVersionType::Bundle,
millau_spec_version: None,
millau_transaction_version: None,
left_relay: KusamaConnectionParams {
kusama_host: "kusama-alice".into(),
kusama_port: 9944,
kusama_secure: false,
kusama_runtime_version: KusamaRuntimeVersionParams {
kusama_version_mode: RuntimeVersionType::Bundle,
kusama_spec_version: None,
kusama_transaction_version: None,
},
},
left_sign: MillauSigningParams {
millau_signer: Some("//Iden".into()),
millau_signer_password: None,
millau_signer_file: None,
millau_signer_password_file: None,
millau_transactions_mortality: Some(64),
},
left_headers_to_right_sign_override:
MillauHeadersToRialtoParachainSigningParams {
millau_headers_to_rialto_parachain_signer: None,
millau_headers_to_rialto_parachain_signer_password: None,
millau_headers_to_rialto_parachain_signer_file: None,
millau_headers_to_rialto_parachain_signer_password_file: None,
millau_headers_to_rialto_parachain_transactions_mortality: None,
},
right: RialtoParachainConnectionParams {
rialto_parachain_host: "rialto-parachain-collator-charlie".into(),
rialto_parachain_port: 9944,
rialto_parachain_secure: false,
rialto_parachain_runtime_version: RialtoParachainRuntimeVersionParams {
rialto_parachain_version_mode: RuntimeVersionType::Bundle,
rialto_parachain_spec_version: None,
rialto_parachain_transaction_version: None,
left: BridgeHubKusamaConnectionParams {
bridge_hub_kusama_host: "bridge-hub-kusama-node-collator1".into(),
bridge_hub_kusama_port: 9944,
bridge_hub_kusama_secure: false,
bridge_hub_kusama_runtime_version: BridgeHubKusamaRuntimeVersionParams {
bridge_hub_kusama_version_mode: RuntimeVersionType::Bundle,
bridge_hub_kusama_spec_version: None,
bridge_hub_kusama_transaction_version: None,
},
},
right_sign: RialtoParachainSigningParams {
rialto_parachain_signer: Some("//George".into()),
rialto_parachain_signer_password: None,
rialto_parachain_signer_file: None,
rialto_parachain_signer_password_file: None,
rialto_parachain_transactions_mortality: Some(64),
left_sign: BridgeHubKusamaSigningParams {
bridge_hub_kusama_signer: Some("//Iden".into()),
bridge_hub_kusama_signer_password: None,
bridge_hub_kusama_signer_file: None,
bridge_hub_kusama_signer_password_file: None,
bridge_hub_kusama_transactions_mortality: Some(64),
},
right_relay_headers_to_left_sign_override: RialtoHeadersToMillauSigningParams {
rialto_headers_to_millau_signer: Some("//Ken".into()),
rialto_headers_to_millau_signer_password: None,
rialto_headers_to_millau_signer_file: None,
rialto_headers_to_millau_signer_password_file: None,
rialto_headers_to_millau_transactions_mortality: None,
right: BridgeHubPolkadotConnectionParams {
bridge_hub_polkadot_host: "bridge-hub-polkadot-collator1".into(),
bridge_hub_polkadot_port: 9944,
bridge_hub_polkadot_secure: false,
bridge_hub_polkadot_runtime_version:
BridgeHubPolkadotRuntimeVersionParams {
bridge_hub_polkadot_version_mode: RuntimeVersionType::Bundle,
bridge_hub_polkadot_spec_version: None,
bridge_hub_polkadot_transaction_version: None,
},
},
right_parachains_to_left_sign_override: RialtoParachainsToMillauSigningParams {
rialto_parachains_to_millau_signer: None,
rialto_parachains_to_millau_signer_password: None,
rialto_parachains_to_millau_signer_file: None,
rialto_parachains_to_millau_signer_password_file: None,
rialto_parachains_to_millau_transactions_mortality: None,
right_sign: BridgeHubPolkadotSigningParams {
bridge_hub_polkadot_signer: Some("//George".into()),
bridge_hub_polkadot_signer_password: None,
bridge_hub_polkadot_signer_file: None,
bridge_hub_polkadot_signer_password_file: None,
bridge_hub_polkadot_transactions_mortality: Some(64),
},
right_relay: RialtoConnectionParams {
rialto_host: "rialto-node-alice".into(),
rialto_port: 9944,
rialto_secure: false,
rialto_runtime_version: RialtoRuntimeVersionParams {
rialto_version_mode: RuntimeVersionType::Bundle,
rialto_spec_version: None,
rialto_transaction_version: None,
right_relay: PolkadotConnectionParams {
polkadot_host: "polkadot-alice".into(),
polkadot_port: 9944,
polkadot_secure: false,
polkadot_runtime_version: PolkadotRuntimeVersionParams {
polkadot_version_mode: RuntimeVersionType::Bundle,
polkadot_spec_version: None,
polkadot_transaction_version: None,
},
},
}
@@ -33,7 +33,6 @@ use substrate_relay_helper::{
on_demand::{
headers::OnDemandHeadersRelay, parachains::OnDemandParachainsRelay, OnDemandRelay,
},
TaggedAccount, TransactionParams,
};
/// A base relay between two parachain from different consensus systems.
@@ -54,20 +53,6 @@ pub struct ParachainToParachainBridge<
pub left_relay: Client<<L2R as ParachainToRelayHeadersCliBridge>::SourceRelay>,
/// Client of the right relay chain.
pub right_relay: Client<<R2L as ParachainToRelayHeadersCliBridge>::SourceRelay>,
/// Override for right_relay->left headers signer.
pub right_headers_to_left_transaction_params:
TransactionParams<AccountKeyPairOf<<R2L as CliBridgeBase>::Target>>,
/// Override for right->left parachains signer.
pub right_parachains_to_left_transaction_params:
TransactionParams<AccountKeyPairOf<<R2L as CliBridgeBase>::Target>>,
/// Override for left_relay->right headers signer.
pub left_headers_to_right_transaction_params:
TransactionParams<AccountKeyPairOf<<L2R as CliBridgeBase>::Target>>,
/// Override for left->right parachains signer.
pub left_parachains_to_right_transaction_params:
TransactionParams<AccountKeyPairOf<<L2R as CliBridgeBase>::Target>>,
}
macro_rules! declare_parachain_to_parachain_bridge_schema {
@@ -86,12 +71,6 @@ macro_rules! declare_parachain_to_parachain_bridge_schema {
// default signer, which is always used to sign messages relay transactions on the left chain
#[structopt(flatten)]
left_sign: [<$left_parachain SigningParams>],
// override for right_relay->left-parachain headers signer
#[structopt(flatten)]
right_relay_headers_to_left_sign_override: [<$right_chain HeadersTo $left_parachain SigningParams>],
// override for right->left parachains signer
#[structopt(flatten)]
right_parachains_to_left_sign_override: [<$right_chain ParachainsTo $left_parachain SigningParams>],
#[structopt(flatten)]
left_relay: [<$left_chain ConnectionParams>],
@@ -101,12 +80,6 @@ macro_rules! declare_parachain_to_parachain_bridge_schema {
// default signer, which is always used to sign messages relay transactions on the right chain
#[structopt(flatten)]
right_sign: [<$right_parachain SigningParams>],
// override for left_relay->right-parachain headers signer
#[structopt(flatten)]
left_relay_headers_to_right_sign_override: [<$left_chain HeadersTo $right_parachain SigningParams>],
// override for left->right parachains signer
#[structopt(flatten)]
left_parachains_to_right_sign_override: [<$left_chain ParachainsTo $right_parachain SigningParams>],
#[structopt(flatten)]
right_relay: [<$right_chain ConnectionParams>],
@@ -143,18 +116,6 @@ macro_rules! declare_parachain_to_parachain_bridge_schema {
)?,
left_relay: self.left_relay.into_client::<LeftRelay>().await?,
right_relay: self.right_relay.into_client::<RightRelay>().await?,
right_headers_to_left_transaction_params: self
.right_relay_headers_to_left_sign_override
.transaction_params_or::<Left, _>(&self.left_sign)?,
left_headers_to_right_transaction_params: self
.left_relay_headers_to_right_sign_override
.transaction_params_or::<Right, _>(&self.right_sign)?,
right_parachains_to_left_transaction_params: self
.right_parachains_to_left_sign_override
.transaction_params_or::<Left, _>(&self.left_sign)?,
left_parachains_to_right_transaction_params: self
.left_parachains_to_right_sign_override
.transaction_params_or::<Right, _>(&self.right_sign)?,
})
}
}
@@ -199,23 +160,6 @@ where
Arc<dyn OnDemandRelay<Self::Left, Self::Right>>,
Arc<dyn OnDemandRelay<Self::Right, Self::Left>>,
)> {
self.common.left.accounts.push(TaggedAccount::Headers {
id: self.right_headers_to_left_transaction_params.signer.public().into(),
bridged_chain: RightRelay::NAME.to_string(),
});
self.common.left.accounts.push(TaggedAccount::Parachains {
id: self.right_parachains_to_left_transaction_params.signer.public().into(),
bridged_chain: RightRelay::NAME.to_string(),
});
self.common.right.accounts.push(TaggedAccount::Headers {
id: self.left_headers_to_right_transaction_params.signer.public().into(),
bridged_chain: Left::NAME.to_string(),
});
self.common.right.accounts.push(TaggedAccount::Parachains {
id: self.left_parachains_to_right_transaction_params.signer.public().into(),
bridged_chain: LeftRelay::NAME.to_string(),
});
<L2R as ParachainToRelayHeadersCliBridge>::RelayFinality::start_relay_guards(
&self.common.right.client,
self.common.right.client.can_start_version_guard(),
@@ -231,7 +175,7 @@ where
OnDemandHeadersRelay::<<L2R as ParachainToRelayHeadersCliBridge>::RelayFinality>::new(
self.left_relay.clone(),
self.common.right.client.clone(),
self.left_headers_to_right_transaction_params.clone(),
self.common.right.tx_params.clone(),
self.common.shared.only_mandatory_headers,
Some(self.common.metrics_params.clone()),
);
@@ -239,7 +183,7 @@ where
OnDemandHeadersRelay::<<R2L as ParachainToRelayHeadersCliBridge>::RelayFinality>::new(
self.right_relay.clone(),
self.common.left.client.clone(),
self.right_headers_to_left_transaction_params.clone(),
self.common.left.tx_params.clone(),
self.common.shared.only_mandatory_headers,
Some(self.common.metrics_params.clone()),
);
@@ -249,7 +193,7 @@ where
>::new(
self.left_relay.clone(),
self.common.right.client.clone(),
self.left_parachains_to_right_transaction_params.clone(),
self.common.right.tx_params.clone(),
Arc::new(left_relay_to_right_on_demand_headers),
);
let right_to_left_on_demand_parachains = OnDemandParachainsRelay::<
@@ -257,7 +201,7 @@ where
>::new(
self.right_relay.clone(),
self.common.left.client.clone(),
self.right_parachains_to_left_transaction_params.clone(),
self.common.left.tx_params.clone(),
Arc::new(right_relay_to_left_on_demand_headers),
);
@@ -36,7 +36,6 @@ use substrate_relay_helper::{
on_demand::{
headers::OnDemandHeadersRelay, parachains::OnDemandParachainsRelay, OnDemandRelay,
},
TaggedAccount, TransactionParams,
};
/// A base relay between standalone (relay) chain and a parachain from another consensus system.
@@ -54,17 +53,6 @@ pub struct RelayToParachainBridge<
Full2WayBridgeCommonParams<<R2L as CliBridgeBase>::Target, <L2R as CliBridgeBase>::Target>,
/// Client of the right relay chain.
pub right_relay: Client<<R2L as ParachainToRelayHeadersCliBridge>::SourceRelay>,
/// Override for right_relay->left headers signer.
pub right_headers_to_left_transaction_params:
TransactionParams<AccountKeyPairOf<<R2L as CliBridgeBase>::Target>>,
/// Override for right->left parachains signer.
pub right_parachains_to_left_transaction_params:
TransactionParams<AccountKeyPairOf<<R2L as CliBridgeBase>::Target>>,
/// Override for left->right headers signer.
pub left_headers_to_right_transaction_params:
TransactionParams<AccountKeyPairOf<<L2R as CliBridgeBase>::Target>>,
}
macro_rules! declare_relay_to_parachain_bridge_schema {
@@ -83,21 +71,12 @@ macro_rules! declare_relay_to_parachain_bridge_schema {
// default signer, which is always used to sign messages relay transactions on the left chain
#[structopt(flatten)]
left_sign: [<$left_chain SigningParams>],
// override for right_relay->left headers signer
#[structopt(flatten)]
right_relay_headers_to_left_sign_override: [<$right_chain HeadersTo $left_chain SigningParams>],
// override for right->left parachains signer
#[structopt(flatten)]
right_parachains_to_left_sign_override: [<$right_chain ParachainsTo $left_chain SigningParams>],
#[structopt(flatten)]
right: [<$right_parachain ConnectionParams>],
// default signer, which is always used to sign messages relay transactions on the right chain
#[structopt(flatten)]
right_sign: [<$right_parachain SigningParams>],
// override for left->right headers signer
#[structopt(flatten)]
left_headers_to_right_sign_override: [<$left_chain HeadersTo $right_parachain SigningParams>],
#[structopt(flatten)]
right_relay: [<$right_chain ConnectionParams>],
@@ -130,19 +109,6 @@ macro_rules! declare_relay_to_parachain_bridge_schema {
},
)?,
right_relay: self.right_relay.into_client::<RightRelay>().await?,
right_headers_to_left_transaction_params: self
.right_relay_headers_to_left_sign_override
.transaction_params_or::<Left, _>(
&self.left_sign,
)?,
right_parachains_to_left_transaction_params: self
.right_parachains_to_left_sign_override
.transaction_params_or::<Left, _>(
&self.left_sign,
)?,
left_headers_to_right_transaction_params: self
.left_headers_to_right_sign_override
.transaction_params_or::<Right, _>(&self.right_sign)?,
})
}
}
@@ -185,19 +151,6 @@ where
Arc<dyn OnDemandRelay<Self::Left, Self::Right>>,
Arc<dyn OnDemandRelay<Self::Right, Self::Left>>,
)> {
self.common.left.accounts.push(TaggedAccount::Headers {
id: self.right_headers_to_left_transaction_params.signer.public().into(),
bridged_chain: RightRelay::NAME.to_string(),
});
self.common.left.accounts.push(TaggedAccount::Parachains {
id: self.right_parachains_to_left_transaction_params.signer.public().into(),
bridged_chain: RightRelay::NAME.to_string(),
});
self.common.right.accounts.push(TaggedAccount::Headers {
id: self.left_headers_to_right_transaction_params.signer.public().into(),
bridged_chain: Left::NAME.to_string(),
});
<L2R as RelayToRelayHeadersCliBridge>::Finality::start_relay_guards(
&self.common.right.client,
self.common.right.client.can_start_version_guard(),
@@ -213,7 +166,7 @@ where
OnDemandHeadersRelay::<<L2R as RelayToRelayHeadersCliBridge>::Finality>::new(
self.common.left.client.clone(),
self.common.right.client.clone(),
self.left_headers_to_right_transaction_params.clone(),
self.common.right.tx_params.clone(),
self.common.shared.only_mandatory_headers,
None,
);
@@ -221,7 +174,7 @@ where
OnDemandHeadersRelay::<<R2L as ParachainToRelayHeadersCliBridge>::RelayFinality>::new(
self.right_relay.clone(),
self.common.left.client.clone(),
self.right_headers_to_left_transaction_params.clone(),
self.common.left.tx_params.clone(),
self.common.shared.only_mandatory_headers,
Some(self.common.metrics_params.clone()),
);
@@ -230,7 +183,7 @@ where
>::new(
self.right_relay.clone(),
self.common.left.client.clone(),
self.right_parachains_to_left_transaction_params.clone(),
self.common.left.tx_params.clone(),
Arc::new(right_relay_to_left_on_demand_headers),
);
@@ -14,6 +14,10 @@
// 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/>.
// we don't have any relay/standalone <> relay/standalone chain bridges, but we may need it in a
// future
#![allow(unused_macros)]
use async_trait::async_trait;
use std::sync::Arc;
@@ -27,7 +31,6 @@ use sp_core::Pair;
use substrate_relay_helper::{
finality::SubstrateFinalitySyncPipeline,
on_demand::{headers::OnDemandHeadersRelay, OnDemandRelay},
TaggedAccount, TransactionParams,
};
/// A base relay between two standalone (relay) chains.
@@ -40,12 +43,6 @@ pub struct RelayToRelayBridge<
/// Parameters that are shared by all bridge types.
pub common:
Full2WayBridgeCommonParams<<R2L as CliBridgeBase>::Target, <L2R as CliBridgeBase>::Target>,
/// Override for right->left headers signer.
pub right_to_left_transaction_params:
TransactionParams<AccountKeyPairOf<<R2L as CliBridgeBase>::Target>>,
/// Override for left->right headers signer.
pub left_to_right_transaction_params:
TransactionParams<AccountKeyPairOf<<L2R as CliBridgeBase>::Target>>,
}
macro_rules! declare_relay_to_relay_bridge_schema {
@@ -62,18 +59,12 @@ macro_rules! declare_relay_to_relay_bridge_schema {
// default signer, which is always used to sign messages relay transactions on the left chain
#[structopt(flatten)]
left_sign: [<$left_chain SigningParams>],
// override for right->left headers signer
#[structopt(flatten)]
right_headers_to_left_sign_override: [<$right_chain HeadersTo $left_chain SigningParams>],
#[structopt(flatten)]
right: [<$right_chain ConnectionParams>],
#[structopt(flatten)]
// default signer, which is always used to sign messages relay transactions on the right chain
right_sign: [<$right_chain SigningParams>],
// override for left->right headers signer
#[structopt(flatten)]
left_headers_to_right_sign_override: [<$left_chain HeadersTo $right_chain SigningParams>],
}
impl [<$left_chain $right_chain HeadersAndMessages>] {
@@ -99,12 +90,8 @@ macro_rules! declare_relay_to_relay_bridge_schema {
accounts: vec![],
},
)?,
right_to_left_transaction_params: self
.right_headers_to_left_sign_override
.transaction_params_or::<Left, _>(&self.left_sign)?,
left_to_right_transaction_params: self
.left_headers_to_right_sign_override
.transaction_params_or::<Right, _>(&self.right_sign)?,
right_to_left_transaction_params: self.left_sign.transaction_params::<Left>(),
left_to_right_transaction_params: self.right_sign.transaction_params::<Right>(),
})
}
}
@@ -145,15 +132,6 @@ where
Arc<dyn OnDemandRelay<Self::Left, Self::Right>>,
Arc<dyn OnDemandRelay<Self::Right, Self::Left>>,
)> {
self.common.right.accounts.push(TaggedAccount::Headers {
id: self.left_to_right_transaction_params.signer.public().into(),
bridged_chain: Self::Left::NAME.to_string(),
});
self.common.left.accounts.push(TaggedAccount::Headers {
id: self.right_to_left_transaction_params.signer.public().into(),
bridged_chain: Self::Right::NAME.to_string(),
});
<L2R as RelayToRelayHeadersCliBridge>::Finality::start_relay_guards(
&self.common.right.client,
self.common.right.client.can_start_version_guard(),
@@ -169,7 +147,7 @@ where
OnDemandHeadersRelay::<<L2R as RelayToRelayHeadersCliBridge>::Finality>::new(
self.common.left.client.clone(),
self.common.right.client.clone(),
self.left_to_right_transaction_params.clone(),
self.common.right.tx_params.clone(),
self.common.shared.only_mandatory_headers,
None,
);
@@ -177,7 +155,7 @@ where
OnDemandHeadersRelay::<<R2L as RelayToRelayHeadersCliBridge>::Finality>::new(
self.common.right.client.clone(),
self.common.left.client.clone(),
self.right_to_left_transaction_params.clone(),
self.common.left.tx_params.clone(),
self.common.shared.only_mandatory_headers,
None,
);
@@ -28,14 +28,6 @@ use crate::bridges::{
bridge_hub_polkadot_messages_to_polkadot_bulletin::BridgeHubPolkadotToPolkadotBulletinMessagesCliBridge,
polkadot_bulletin_messages_to_bridge_hub_polkadot::PolkadotBulletinToBridgeHubPolkadotMessagesCliBridge,
},
rialto_millau::{
millau_headers_to_rialto::MillauToRialtoCliBridge,
rialto_headers_to_millau::RialtoToMillauCliBridge,
},
rialto_parachain_millau::{
millau_headers_to_rialto_parachain::MillauToRialtoParachainCliBridge,
rialto_parachains_to_millau::RialtoParachainToMillauCliBridge,
},
rococo_westend::{
bridge_hub_rococo_messages_to_bridge_hub_westend::BridgeHubRococoToBridgeHubWestendMessagesCliBridge,
bridge_hub_westend_messages_to_bridge_hub_rococo::BridgeHubWestendToBridgeHubRococoMessagesCliBridge,
@@ -109,10 +101,6 @@ where
}
}
impl MessagesRelayer for MillauToRialtoCliBridge {}
impl MessagesRelayer for RialtoToMillauCliBridge {}
impl MessagesRelayer for MillauToRialtoParachainCliBridge {}
impl MessagesRelayer for RialtoParachainToMillauCliBridge {}
impl MessagesRelayer for BridgeHubRococoToBridgeHubWococoMessagesCliBridge {}
impl MessagesRelayer for BridgeHubWococoToBridgeHubRococoMessagesCliBridge {}
impl MessagesRelayer for BridgeHubRococoToBridgeHubWestendMessagesCliBridge {}
@@ -126,12 +114,6 @@ impl RelayMessages {
/// Run the command.
pub async fn run(self) -> anyhow::Result<()> {
match self.bridge {
FullBridge::MillauToRialto => MillauToRialtoCliBridge::relay_messages(self),
FullBridge::RialtoToMillau => RialtoToMillauCliBridge::relay_messages(self),
FullBridge::MillauToRialtoParachain =>
MillauToRialtoParachainCliBridge::relay_messages(self),
FullBridge::RialtoParachainToMillau =>
RialtoParachainToMillauCliBridge::relay_messages(self),
FullBridge::BridgeHubRococoToBridgeHubWococo =>
BridgeHubRococoToBridgeHubWococoMessagesCliBridge::relay_messages(self),
FullBridge::BridgeHubWococoToBridgeHubRococo =>
@@ -20,7 +20,6 @@ use crate::bridges::{
polkadot_parachains_to_bridge_hub_kusama::BridgeHubPolkadotToBridgeHubKusamaCliBridge,
},
polkadot_bulletin::polkadot_parachains_to_polkadot_bulletin::PolkadotToPolkadotBulletinCliBridge,
rialto_parachain_millau::rialto_parachains_to_millau::RialtoParachainToMillauCliBridge,
rococo_westend::{
rococo_parachains_to_bridge_hub_westend::BridgeHubRococoToBridgeHubWestendCliBridge,
westend_parachains_to_bridge_hub_rococo::BridgeHubWestendToBridgeHubRococoCliBridge,
@@ -29,7 +28,6 @@ use crate::bridges::{
rococo_parachains_to_bridge_hub_wococo::BridgeHubRococoToBridgeHubWococoCliBridge,
wococo_parachains_to_bridge_hub_rococo::BridgeHubWococoToBridgeHubRococoCliBridge,
},
westend_millau::westend_parachains_to_millau::AssetHubWestendToMillauCliBridge,
};
use async_std::sync::Mutex;
use async_trait::async_trait;
@@ -70,8 +68,6 @@ pub struct RelayParachains {
#[derive(Debug, EnumString, EnumVariantNames)]
#[strum(serialize_all = "kebab_case")]
pub enum RelayParachainsBridge {
RialtoToMillau,
WestendToMillau,
RococoToBridgeHubWococo,
WococoToBridgeHubRococo,
KusamaToBridgeHubPolkadot,
@@ -122,8 +118,6 @@ where
}
}
impl ParachainsRelayer for RialtoParachainToMillauCliBridge {}
impl ParachainsRelayer for AssetHubWestendToMillauCliBridge {}
impl ParachainsRelayer for BridgeHubRococoToBridgeHubWococoCliBridge {}
impl ParachainsRelayer for BridgeHubWococoToBridgeHubRococoCliBridge {}
impl ParachainsRelayer for BridgeHubRococoToBridgeHubWestendCliBridge {}
@@ -136,10 +130,6 @@ impl RelayParachains {
/// Run the command.
pub async fn run(self) -> anyhow::Result<()> {
match self.bridge {
RelayParachainsBridge::RialtoToMillau =>
RialtoParachainToMillauCliBridge::relay_parachains(self),
RelayParachainsBridge::WestendToMillau =>
AssetHubWestendToMillauCliBridge::relay_parachains(self),
RelayParachainsBridge::RococoToBridgeHubWococo =>
BridgeHubRococoToBridgeHubWococoCliBridge::relay_parachains(self),
RelayParachainsBridge::WococoToBridgeHubRococo =>
@@ -1,560 +0,0 @@
// 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::cli::{chain_schema::*, Balance};
use bp_runtime::HeaderIdProvider;
use codec::{Decode, Encode};
use num_traits::{One, Zero};
use relay_substrate_client::{
AccountKeyPairOf, BlockWithJustification, Chain, ChainWithTransactions, Client,
Error as SubstrateError, HeaderIdOf, HeaderOf, SignParam,
};
use relay_utils::FailedClient;
use sp_core::Bytes;
use sp_runtime::{
traits::{Hash, Header as HeaderT},
transaction_validity::TransactionPriority,
};
use structopt::StructOpt;
use strum::{EnumString, EnumVariantNames, VariantNames};
use substrate_relay_helper::TransactionParams;
/// Start resubmit transactions process.
#[derive(StructOpt)]
pub struct ResubmitTransactions {
/// A bridge instance to relay headers for.
#[structopt(possible_values = RelayChain::VARIANTS, case_insensitive = true)]
chain: RelayChain,
#[structopt(flatten)]
target: TargetConnectionParams,
#[structopt(flatten)]
target_sign: TargetSigningParams,
/// Number of blocks we see before considering queued transaction as stalled.
#[structopt(long, default_value = "5")]
stalled_blocks: u32,
/// Tip limit. We'll never submit transaction with larger tip.
#[structopt(long)]
tip_limit: Balance,
/// Tip increase step. We'll be checking updated transaction priority by increasing its tip by
/// this step.
#[structopt(long)]
tip_step: Balance,
/// Priority selection strategy.
#[structopt(subcommand)]
strategy: PrioritySelectionStrategy,
}
/// Chain, which transactions we're going to track && resubmit.
#[derive(Debug, EnumString, EnumVariantNames)]
#[strum(serialize_all = "kebab_case")]
pub enum RelayChain {
Millau,
}
/// Strategy to use for priority selection.
#[derive(StructOpt, Debug, PartialEq, Eq, Clone, Copy)]
pub enum PrioritySelectionStrategy {
/// Strategy selects tip that changes transaction priority to be better than priority of
/// the first transaction of previous block.
///
/// It only makes sense to use this strategy for Millau transactions. Millau has transactions
/// that are close to block limits, so if there are any other queued transactions, 'large'
/// transaction won't fit the block && will be postponed. To avoid this, we change its priority
/// to some large value, making it best transaction => it'll be 'mined' first.
MakeItBestTransaction,
/// Strategy selects tip that changes transaction priority to be better than priority of
/// selected queued transaction.
///
/// When we first see stalled transaction, we make it better than worst 1/4 of queued
/// transactions. If it is still stalled, we'll make it better than 1/3 of queued transactions,
/// ...
MakeItBetterThanQueuedTransaction,
}
macro_rules! select_bridge {
($bridge: expr, $generic: tt) => {
match $bridge {
RelayChain::Millau => {
type Target = relay_millau_client::Millau;
$generic
},
}
};
}
impl ResubmitTransactions {
/// Run the command.
pub async fn run(self) -> anyhow::Result<()> {
select_bridge!(self.chain, {
let relay_loop_name = format!("ResubmitTransactions{}", Target::NAME);
let client = self.target.into_client::<Target>().await?;
let transaction_params = TransactionParams {
signer: self.target_sign.to_keypair::<Target>()?,
mortality: self.target_sign.target_transactions_mortality,
};
relay_utils::relay_loop((), client)
.run(relay_loop_name, move |_, client, _| {
run_until_connection_lost(
client,
transaction_params.clone(),
Context {
strategy: self.strategy,
best_header: HeaderOf::<Target>::new(
Default::default(),
Default::default(),
Default::default(),
Default::default(),
Default::default(),
),
transaction: None,
resubmitted: 0,
stalled_for: Zero::zero(),
stalled_for_limit: self.stalled_blocks as _,
tip_step: self.tip_step.cast() as _,
tip_limit: self.tip_limit.cast() as _,
},
)
})
.await
.map_err(Into::into)
})
}
}
impl PrioritySelectionStrategy {
/// Select target priority.
async fn select_target_priority<C: ChainWithTransactions>(
&self,
client: &Client<C>,
context: &Context<C>,
) -> Result<Option<TransactionPriority>, SubstrateError> {
match *self {
PrioritySelectionStrategy::MakeItBestTransaction =>
read_previous_block_best_priority(client, context).await,
PrioritySelectionStrategy::MakeItBetterThanQueuedTransaction =>
select_priority_from_queue(client, context).await,
}
}
}
#[derive(Debug)]
struct Context<C: Chain> {
/// Priority selection strategy.
strategy: PrioritySelectionStrategy,
/// Best known block header.
best_header: C::Header,
/// Hash of the (potentially) stalled transaction.
transaction: Option<C::Hash>,
/// How many times we have resubmitted this `transaction`?
resubmitted: u32,
/// This transaction is in pool for `stalled_for` wakeup intervals.
stalled_for: C::BlockNumber,
/// When `stalled_for` reaching this limit, transaction is considered stalled.
stalled_for_limit: C::BlockNumber,
/// Tip step interval.
tip_step: C::Balance,
/// Maximal tip.
tip_limit: C::Balance,
}
impl<C: Chain> Context<C> {
/// Return true if transaction has stalled.
fn is_stalled(&self) -> bool {
self.stalled_for >= self.stalled_for_limit
}
/// Notice resubmitted transaction.
fn notice_resubmitted_transaction(mut self, transaction: C::Hash) -> Self {
self.transaction = Some(transaction);
self.stalled_for = Zero::zero();
self.resubmitted += 1;
self
}
/// Notice transaction from the transaction pool.
fn notice_transaction(mut self, transaction: C::Hash) -> Self {
if self.transaction == Some(transaction) {
self.stalled_for += One::one();
} else {
self.transaction = Some(transaction);
self.stalled_for = One::one();
self.resubmitted = 0;
}
self
}
}
/// Run resubmit transactions loop.
async fn run_until_connection_lost<C: ChainWithTransactions>(
client: Client<C>,
transaction_params: TransactionParams<AccountKeyPairOf<C>>,
mut context: Context<C>,
) -> Result<(), FailedClient> {
loop {
async_std::task::sleep(C::AVERAGE_BLOCK_INTERVAL).await;
let result = run_loop_iteration(client.clone(), transaction_params.clone(), context).await;
context = match result {
Ok(context) => context,
Err(error) => {
log::error!(
target: "bridge",
"Resubmit {} transactions loop has failed with error: {:?}",
C::NAME,
error,
);
return Err(FailedClient::Target)
},
};
}
}
/// Run single loop iteration.
async fn run_loop_iteration<C: ChainWithTransactions>(
client: Client<C>,
transaction_params: TransactionParams<AccountKeyPairOf<C>>,
mut context: Context<C>,
) -> Result<Context<C>, SubstrateError> {
// correct best header is required for all other actions
context.best_header = client.best_header().await?;
// check if there's queued transaction, signed by given author
let original_transaction =
match lookup_signer_transaction(&client, &transaction_params.signer).await? {
Some(original_transaction) => original_transaction,
None => {
log::trace!(target: "bridge", "No {} transactions from required signer in the txpool", C::NAME);
return Ok(context)
},
};
let original_transaction_hash = C::Hasher::hash(&original_transaction.encode());
let context = context.notice_transaction(original_transaction_hash);
// if transaction hasn't been mined for `stalled_blocks`, we'll need to resubmit it
if !context.is_stalled() {
log::trace!(
target: "bridge",
"{} transaction {:?} is not yet stalled ({:?}/{:?})",
C::NAME,
context.transaction,
context.stalled_for,
context.stalled_for_limit,
);
return Ok(context)
}
// select priority for updated transaction
let target_priority = match context.strategy.select_target_priority(&client, &context).await? {
Some(target_priority) => target_priority,
None => {
log::trace!(target: "bridge", "Failed to select target priority");
return Ok(context)
},
};
// update transaction tip
let (is_updated, updated_transaction) = update_transaction_tip(
&client,
&transaction_params,
context.best_header.id(),
original_transaction,
context.tip_step,
context.tip_limit,
target_priority,
)
.await?;
if !is_updated {
log::trace!(target: "bridge", "{} transaction tip can not be updated. Reached limit?", C::NAME);
return Ok(context)
}
let updated_transaction = updated_transaction.encode();
let updated_transaction_hash = C::Hasher::hash(&updated_transaction);
client.submit_unsigned_extrinsic(Bytes(updated_transaction)).await?;
log::info!(
target: "bridge",
"Replaced {} transaction {} with {} in txpool",
C::NAME,
original_transaction_hash,
updated_transaction_hash,
);
Ok(context.notice_resubmitted_transaction(updated_transaction_hash))
}
/// Search transaction pool for transaction, signed by given key pair.
async fn lookup_signer_transaction<C: ChainWithTransactions>(
client: &Client<C>,
key_pair: &AccountKeyPairOf<C>,
) -> Result<Option<C::SignedTransaction>, SubstrateError> {
let pending_transactions = client.pending_extrinsics().await?;
for pending_transaction in pending_transactions {
let pending_transaction = C::SignedTransaction::decode(&mut &pending_transaction.0[..])
.map_err(SubstrateError::ResponseParseFailed)?;
if !C::is_signed_by(key_pair, &pending_transaction) {
continue
}
return Ok(Some(pending_transaction))
}
Ok(None)
}
/// Read priority of best signed transaction of previous block.
async fn read_previous_block_best_priority<C: ChainWithTransactions>(
client: &Client<C>,
context: &Context<C>,
) -> Result<Option<TransactionPriority>, SubstrateError> {
let best_block = client.get_block(Some(context.best_header.hash())).await?;
let best_transaction = best_block
.extrinsics()
.iter()
.filter_map(|xt| C::SignedTransaction::decode(&mut &xt[..]).ok())
.find(|xt| C::is_signed(xt));
match best_transaction {
Some(best_transaction) => Ok(Some(
client
.validate_transaction(*context.best_header.parent_hash(), best_transaction)
.await??
.priority,
)),
None => Ok(None),
}
}
/// Select priority of some queued transaction.
async fn select_priority_from_queue<C: ChainWithTransactions>(
client: &Client<C>,
context: &Context<C>,
) -> Result<Option<TransactionPriority>, SubstrateError> {
// select transaction from the queue
let queued_transactions = client.pending_extrinsics().await?;
let selected_transaction = match select_transaction_from_queue(queued_transactions, context) {
Some(selected_transaction) => selected_transaction,
None => return Ok(None),
};
let selected_transaction = C::SignedTransaction::decode(&mut &selected_transaction[..])
.map_err(SubstrateError::ResponseParseFailed)?;
let target_priority = client
.validate_transaction(context.best_header.hash(), selected_transaction)
.await??
.priority;
Ok(Some(target_priority))
}
/// Select transaction with target priority from the vec of queued transactions.
fn select_transaction_from_queue<C: Chain>(
mut queued_transactions: Vec<Bytes>,
context: &Context<C>,
) -> Option<Bytes> {
if queued_transactions.is_empty() {
return None
}
// the more times we resubmit transaction (`context.resubmitted`), the closer we move
// to the front of the transaction queue
let total_transactions = queued_transactions.len();
let resubmitted_factor = context.resubmitted;
let divisor =
1usize.saturating_add(1usize.checked_shl(resubmitted_factor).unwrap_or(usize::MAX));
let transactions_to_skip = total_transactions / divisor;
Some(
queued_transactions
.swap_remove(std::cmp::min(total_transactions - 1, transactions_to_skip)),
)
}
/// Try to find appropriate tip for transaction so that its priority is larger than given.
async fn update_transaction_tip<C: ChainWithTransactions>(
client: &Client<C>,
transaction_params: &TransactionParams<AccountKeyPairOf<C>>,
at_block: HeaderIdOf<C>,
tx: C::SignedTransaction,
tip_step: C::Balance,
tip_limit: C::Balance,
target_priority: TransactionPriority,
) -> Result<(bool, C::SignedTransaction), SubstrateError> {
let stx = format!("{tx:?}");
let mut current_priority = client.validate_transaction(at_block.1, tx.clone()).await??.priority;
let mut unsigned_tx = C::parse_transaction(tx).ok_or_else(|| {
SubstrateError::Custom(format!("Failed to parse {} transaction {stx}", C::NAME,))
})?;
let old_tip = unsigned_tx.tip;
let runtime_version = client.simple_runtime_version().await?;
while current_priority < target_priority {
let next_tip = unsigned_tx.tip + tip_step;
if next_tip > tip_limit {
break
}
log::trace!(
target: "bridge",
"{} transaction priority with tip={:?}: {}. Target priority: {}",
C::NAME,
unsigned_tx.tip,
current_priority,
target_priority,
);
unsigned_tx.tip = next_tip;
current_priority = client
.validate_transaction(
at_block.1,
C::sign_transaction(
SignParam {
spec_version: runtime_version.spec_version,
transaction_version: runtime_version.transaction_version,
genesis_hash: *client.genesis_hash(),
signer: transaction_params.signer.clone(),
},
unsigned_tx.clone(),
)?,
)
.await??
.priority;
}
log::debug!(
target: "bridge",
"{} transaction tip has changed from {:?} to {:?}",
C::NAME,
old_tip,
unsigned_tx.tip,
);
Ok((
old_tip != unsigned_tx.tip,
C::sign_transaction(
SignParam {
spec_version: runtime_version.spec_version,
transaction_version: runtime_version.transaction_version,
genesis_hash: *client.genesis_hash(),
signer: transaction_params.signer.clone(),
},
unsigned_tx.era(relay_substrate_client::TransactionEra::new(
at_block,
transaction_params.mortality,
)),
)?,
))
}
#[cfg(test)]
mod tests {
use super::*;
use bp_rialto::Hash;
use relay_rialto_client::Rialto;
fn context() -> Context<Rialto> {
Context {
strategy: PrioritySelectionStrategy::MakeItBestTransaction,
best_header: HeaderOf::<Rialto>::new(
Default::default(),
Default::default(),
Default::default(),
Default::default(),
Default::default(),
),
transaction: None,
resubmitted: 0,
stalled_for: Zero::zero(),
stalled_for_limit: 3,
tip_step: 100,
tip_limit: 1000,
}
}
#[test]
fn context_works() {
let mut context = context();
// when transaction is noticed 2/3 times, it isn't stalled
context = context.notice_transaction(Default::default());
assert!(!context.is_stalled());
assert_eq!(context.stalled_for, 1);
assert_eq!(context.resubmitted, 0);
context = context.notice_transaction(Default::default());
assert!(!context.is_stalled());
assert_eq!(context.stalled_for, 2);
assert_eq!(context.resubmitted, 0);
// when transaction is noticed for 3rd time in a row, it is considered stalled
context = context.notice_transaction(Default::default());
assert!(context.is_stalled());
assert_eq!(context.stalled_for, 3);
assert_eq!(context.resubmitted, 0);
// and after we resubmit it, we forget previous transaction
context = context.notice_resubmitted_transaction(Hash::from([1; 32]));
assert_eq!(context.transaction, Some(Hash::from([1; 32])));
assert_eq!(context.resubmitted, 1);
assert_eq!(context.stalled_for, 0);
}
#[test]
fn select_transaction_from_queue_works_with_empty_queue() {
assert_eq!(select_transaction_from_queue(vec![], &context()), None);
}
#[test]
fn select_transaction_from_queue_works() {
let mut context = context();
let queued_transactions = vec![
Bytes(vec![1]),
Bytes(vec![2]),
Bytes(vec![3]),
Bytes(vec![4]),
Bytes(vec![5]),
Bytes(vec![6]),
];
// when we resubmit tx for the first time, 1/2 of queue is skipped
assert_eq!(
select_transaction_from_queue(queued_transactions.clone(), &context),
Some(Bytes(vec![4])),
);
// when we resubmit tx for the second time, 1/3 of queue is skipped
context = context.notice_resubmitted_transaction(Hash::from([1; 32]));
assert_eq!(
select_transaction_from_queue(queued_transactions.clone(), &context),
Some(Bytes(vec![3])),
);
// when we resubmit tx for the third time, 1/5 of queue is skipped
context = context.notice_resubmitted_transaction(Hash::from([2; 32]));
assert_eq!(
select_transaction_from_queue(queued_transactions.clone(), &context),
Some(Bytes(vec![2])),
);
// when we resubmit tx for the second time, 1/9 of queue is skipped
context = context.notice_resubmitted_transaction(Hash::from([3; 32]));
assert_eq!(
select_transaction_from_queue(queued_transactions, &context),
Some(Bytes(vec![1])),
);
}
}

Some files were not shown because too many files have changed in this diff Show More