Squashed 'bridges/' changes from 23dda62482..407bf44a8a

407bf44a8a add missing license header (#1204)
9babb19810  Custom relay strategy (#1198)
c287872a11 fix clippy things (#1200)
3a40e62789 Expose some const value and type (#1186)
32b61476d1 increase sleep before connectingMillau (#1195)
aabe7041fa revert messages transactions mortality (#1194)
3651f4f909 Message transactions mortality (#1191)
364d6e155d Bump dependencies (#1180)
f0389acc08 cargo +nightly fmt --all (#1192)
b270b6a016 Unify error enums in substrate and ethereum clients with `thiserror` (#1094)
58c4946f74 Limit max call size of Rialto/Millau runtimes (#1187)
fd56a8cd56 Add UI to the deployment (#1047)
16f01dc736 Westend -> Millau alerts are pending before notifications are sent (#1184)
5628c11ece replace collective flip with babe randomness in Rialto (#1188)
1094a63b00 ignore another (pretty bad) RUSTSEC (#1185)
379fe323ea fix/ignore cargo deny issues (#1183)
92af5e6e64 additional log in finality relay + rephrase "failed" (#1182)
b996a3b681 Rialto parachain in test deployments (#1178)
28d9332b44 Resubmit transactions strategy for Polkadot/Kusama (#1175)
d0172c6847 Playing with CI (#1179)
fb6f42456d fix checks order when registering parachain (#1177)
ee828c005a Register-parachain subcommand of substrate-relay (#1170)
8cd2b1a112 Token swap pallet benchmarks (#1174)
bb811accb1 fix collision with westend bridge (#1172)
8d2fba70ed add token swaps to test deployments (#1169)
b6d1bdfe2c publish rialto parachain collator image (#1171)
834ae4a10a Fix OutboundLaneData types (#1159)
5ee0ea1626 copypasted -> copied (#1168)
c3bb835f18 fix spelling (#1167)
f90d041dc9 Upgrade `jsonrpsee` to v0.3 (#1051)
598c9b6d0d add some basic tests for swap tokens (#1164)
05e88c61f5 publish images when tag of specific format(e.g. v2021-09-27 + v2021-09-27-1) is published (#1166)
7f3f94a6e0 Fix CI again (#1165)
ff37de332f Move calculation relayer reward into `MessageDeliveryAndDispatchPayment` (#1153)
36fbba839b fix clippy warning (#1163)
16da44d018 explicit wasm build (#1158)
c9c8226449 Match substrate's fmt (#1148)
2fdd7f3e5e Fix/ignore clippy warnings (#1157)
43dfcc2686 Adding LookupAddress (#1156)
951eaa5582 Add rialto-parachain runtime and node (#1142)
803d266d61 Rename MessageId -> BridgeMessageId (#1152)
5f234484fc Box large arguments of GRANDPA pallet (#1154)
cf9abc1011 Fix spelling (#1150)
ab83ba2e58 Relay subcommand that performs token RLT <> MLAU token swap (#1141)
832536caf0 Polkadot <> Kusama relayers (#1122)
6d0daa8975 Add `OnMessageAccepted` callback (#1134)
5d03a20b3e Integrate token swap pallet into Millau runtime (#1099)
ea4cfa833e Adding MultiAddress type and ValidationCodeHash (#1139)
c20325a784 Add tests for `Raw` and `BridgeSendMessage` enum `Call` variants (#1125)
6d802416e2 increase pause before pining Rialto nodes (#1137)
b54fa56b62 calculate fee using full message payload (#1132)
ca5d8178f5 Add parachain pallets to rialto runtime (#1053)
9eaae4142e fix transaction resubmitter limits for Millau -> Rialto transactions (#1135)
9d4e17783c add --mandatory-headers-only cli option to complex relay (#1129)
1c5e0ec1cb Add local CI info to README (#1131)
a8e0929e14 chore: spellchecker fixes (#1130)
3b8e2118e3 set fee for importing mandatory headers to zero (#1127)
49bba9aa52 another bunch of words for spellchecker (#1128)
8a72eafef6 Increase pause before messages generation start (#1126)
1f0ba9a191 Move some associated types from relay_substrate_client::Chain to bp_runtime::Chain (#1087)
74bc1a5b54 Transactions resubmitter (#1083)
21ba001f26 log max balance drop when sending message (#1117)
638a7ddffa Code Cleaning (#1124)
be6555c51b Fix buildah logout (#1120)
87539c4a98 Format code work (#1116)
526fe7fdd7 fix spelling (#1119)
bd4ce7f241 Fix spelling (#1118)
3c1147858e added missing constants to Kusama/Polkadot primitives (#1114)
52093b22ab Fix delivery transaction estimation used by rational relayer (#1109)
77a2f2fbed Remove fund account checks from upgrade. (#1111)
824334802b Rename param and update comment (#1108)
d7784bfe06 Fix spellcheck (#1110)
0b18f5906a Refactor substrate messages source and substrate messages target (#1105)
b27240bbff fix compilation (#1107)
9697da4fe8 Emit mortal transactions from relay (#1073)
b29396c077 Change vault vars type to env vars (#1084)
35e0bbdc0c Make clippy mandatory. (#1103)
a517e8541f Remove unused deps (#1102)
873dae608a Remove unnessary deps (#1101)
13450b74ee Stored conversion rate updater (#1005)
74389829f3 [BREAKING] Migrate messages pallet to frame v2 (#1088)
424da938dd README fix (#1100)
865744c909 upgrade currency exchange pallet to frame v2 (#1097)
b5038148b3 Add missing docs (#1095)
0791e911c1 Common crate for substrate-relay (#1082)
3834c9d880 Update high-level-overview.md (#1093)
c93553face Increase the time window for messaging alerts. (#1092)
8b9cc3cecd migrate pallet-shift-session-manager to frame v2 (#1090)
dc91813c22 migrate eth PoA pallet to frame v2 (#1091)
f16bb098cc Migrate dispatch pallet  to frame v2 (#1089)
19f4325348 Bridge/This Chain Ids should be exposed as constants on pallet level. (#1085)
6381122df7 Change ChainSpec::from_genesis for Rialto and Millau chains to reflect the chain names. (#1079)
0f1d33e973 Make CI happy again (#1086)
238e65d96f fix typo (#1080)
fc008457b6 Token-swap-over-bridge pallet (#944)
3fb97fa5ef Fix full spellcheck (#1076)
eae4ed7170 fixed wrong trace (#1075)
219a0fad04 merge two weight-related loops in messages pallet (#1071)
fc85632fdb increase_message_fee depends on stored mesage size (#1066)
530f37a23b companion for https://github.com/paritytech/polkadot/pull/3507 (#1067)
53b8cba683 sc_basic_authorship=trace for millau nodes (#1074)
9874e05e98 Improve traces of message generator scripts (#1069)
7b5ee84fbb extract message_details impl into runtime common (#1070)
5a4aed5a8b refund weight for mot pruning messages (#1062)
90e3d1e111 Fix Westend -> Millau sync (#1064)
427d30ddfc When restarting client, also "restart" tokio runtime (#1065)
d47c05eeef Change get pipeline sensitive variables from Vault instead of GitLab settings (#1063)
d775a85415 use tokio reactor to execute jsonrpsee futures (#1061)
15c8cd61cb Use BABE to author blocks on Rialto (previously: Aura) (#1050)
5186293500 Allow reading suri && password override from file (#1059)
b506298262 Update jsonrpsee reference (#1049)
1734d00517 enable weight fee adjustent in Rialto/Millau (#1044)
607265afae Pay dispatch fee at target chain cli option (#1043)
ce79ef91be bump dependencies before start referencing polkadot repo (#1048)
924fa24f6d Cli option for greedy relayer + run no-losses relayer by default (#1042)
e21eba7b59 Yrong README Fixup + M1 Fixes (#1045)
20d08204a2 Confirm delivery detects when more than expected messages are confirmed (#1039)
994b846b52 pre and post dispatch weights of OnDeliveryConfirmed callback (#1040)
1dd5297e84 give real value to Rialto and Millau tokens (#1038)
035bee8715 Use real conversion rate in greedy relayer strategy (#1035)
9cfaecd0f7 fixed metrics prefix (#1037)
1d8d224937 Use kebab-case for bridge arguments (#1036)
f30a4c79a6 Shared reference to conversion rate metric value (#1034)
c34d7a5cbb estimate transaction fee (#1015)
93404b18bb change alert period from 2m to 10m for Westend -> Millau (GRANDPA or public node itself is lagging sometimes) (#1032)

git-subtree-dir: bridges
git-subtree-split: 407bf44a8a5f4e60aceef2dc755cd9ff09929ac3
This commit is contained in:
antonio-dropulic
2021-12-01 09:24:53 +01:00
parent feefc34567
commit 392447f5c8
1020 changed files with 30080 additions and 179754 deletions
@@ -1,28 +0,0 @@
[package]
name = "bp-kusama"
description = "Primitives of Kusama runtime."
version = "0.1.0"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2018"
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
[dependencies]
# Bridge Dependencies
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
sp-api = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-std = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
[features]
default = ["std"]
std = [
"bp-messages/std",
"bp-polkadot-core/std",
"bp-runtime/std",
"sp-api/std",
"sp-std/std",
]
@@ -1,118 +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)]
// Runtime-generated DecodeLimit::decode_all_with_depth_limit
#![allow(clippy::unnecessary_mut_passed)]
use bp_messages::{LaneId, MessageDetails, MessageNonce, UnrewardedRelayersState};
use sp_std::prelude::*;
pub use bp_polkadot_core::*;
/// Kusama Chain
pub type Kusama = PolkadotLike;
// We use this to get the account on Kusama (target) which is derived from Polkadot's (source)
// account.
pub fn derive_account_from_polkadot_id(id: bp_runtime::SourceAccount<AccountId>) -> AccountId {
let encoded_id = bp_runtime::derive_account_id(bp_runtime::POLKADOT_CHAIN_ID, id);
AccountIdConverter::convert(encoded_id)
}
/// Name of the `KusamaFinalityApi::best_finalized` runtime method.
pub const BEST_FINALIZED_KUSAMA_HEADER_METHOD: &str = "KusamaFinalityApi_best_finalized";
/// Name of the `KusamaFinalityApi::is_known_header` runtime method.
pub const IS_KNOWN_KUSAMA_HEADER_METHOD: &str = "KusamaFinalityApi_is_known_header";
/// Name of the `ToKusamaOutboundLaneApi::estimate_message_delivery_and_dispatch_fee` runtime method.
pub const TO_KUSAMA_ESTIMATE_MESSAGE_FEE_METHOD: &str =
"ToKusamaOutboundLaneApi_estimate_message_delivery_and_dispatch_fee";
/// Name of the `ToKusamaOutboundLaneApi::message_details` runtime method.
pub const TO_KUSAMA_MESSAGE_DETAILS_METHOD: &str = "ToKusamaOutboundLaneApi_message_details";
/// Name of the `ToKusamaOutboundLaneApi::latest_generated_nonce` runtime method.
pub const TO_KUSAMA_LATEST_GENERATED_NONCE_METHOD: &str = "ToKusamaOutboundLaneApi_latest_generated_nonce";
/// Name of the `ToKusamaOutboundLaneApi::latest_received_nonce` runtime method.
pub const TO_KUSAMA_LATEST_RECEIVED_NONCE_METHOD: &str = "ToKusamaOutboundLaneApi_latest_received_nonce";
/// Name of the `FromKusamaInboundLaneApi::latest_received_nonce` runtime method.
pub const FROM_KUSAMA_LATEST_RECEIVED_NONCE_METHOD: &str = "FromKusamaInboundLaneApi_latest_received_nonce";
/// Name of the `FromKusamaInboundLaneApi::latest_onfirmed_nonce` runtime method.
pub const FROM_KUSAMA_LATEST_CONFIRMED_NONCE_METHOD: &str = "FromKusamaInboundLaneApi_latest_confirmed_nonce";
/// Name of the `FromKusamaInboundLaneApi::unrewarded_relayers_state` runtime method.
pub const FROM_KUSAMA_UNREWARDED_RELAYERS_STATE: &str = "FromKusamaInboundLaneApi_unrewarded_relayers_state";
sp_api::decl_runtime_apis! {
/// API for querying information about the finalized Kusama headers.
///
/// This API is implemented by runtimes that are bridging with the Kusama chain, not the
/// Kusama runtime itself.
pub trait KusamaFinalityApi {
/// Returns number and hash of the best finalized header known to the bridge module.
fn best_finalized() -> (BlockNumber, Hash);
/// Returns true if the header is known to the runtime.
fn is_known_header(hash: Hash) -> bool;
}
/// Outbound message lane API for messages that are sent to Kusama chain.
///
/// This API is implemented by runtimes that are sending messages to Kusama chain, not the
/// Kusama runtime itself.
pub trait ToKusamaOutboundLaneApi<OutboundMessageFee: Parameter, OutboundPayload: Parameter> {
/// Estimate message delivery and dispatch fee that needs to be paid by the sender on
/// this chain.
///
/// Returns `None` if message is too expensive to be sent to Kusama from this chain.
///
/// Please keep in mind that this method returns the lowest message fee required for message
/// to be accepted to the lane. It may be good idea to pay a bit over this price to account
/// future exchange rate changes and guarantee that relayer would deliver your message
/// to the target chain.
fn estimate_message_delivery_and_dispatch_fee(
lane_id: LaneId,
payload: OutboundPayload,
) -> Option<OutboundMessageFee>;
/// Returns dispatch weight, encoded payload size and delivery+dispatch fee of all
/// messages in given inclusive range.
///
/// If some (or all) messages are missing from the storage, they'll also will
/// be missing from the resulting vector. The vector is ordered by the nonce.
fn message_details(
lane: LaneId,
begin: MessageNonce,
end: MessageNonce,
) -> Vec<MessageDetails<OutboundMessageFee>>;
/// Returns nonce of the latest message, received by bridged chain.
fn latest_received_nonce(lane: LaneId) -> MessageNonce;
/// Returns nonce of the latest message, generated by given lane.
fn latest_generated_nonce(lane: LaneId) -> MessageNonce;
}
/// Inbound message lane API for messages sent by Kusama chain.
///
/// This API is implemented by runtimes that are receiving messages from Kusama chain, not the
/// Kusama runtime itself.
pub trait FromKusamaInboundLaneApi {
/// Returns nonce of the latest message, received by given lane.
fn latest_received_nonce(lane: LaneId) -> MessageNonce;
/// Nonce of the latest message that has been confirmed to the bridged chain.
fn latest_confirmed_nonce(lane: LaneId) -> MessageNonce;
/// State of the unrewarded relayers set at given lane.
fn unrewarded_relayers_state(lane: LaneId) -> UnrewardedRelayersState;
}
}
@@ -1,54 +0,0 @@
[package]
name = "bp-millau"
description = "Primitives of Millau runtime."
version = "0.1.0"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2018"
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
[dependencies]
# Bridge Dependencies
bp-messages = { path = "../messages", default-features = false }
bp-runtime = { path = "../runtime", default-features = false }
fixed-hash = { version = "0.7.0", default-features = false }
hash256-std-hasher = { version = "0.15.2", default-features = false }
impl-codec = { version = "0.5.0", default-features = false }
impl-serde = { version = "0.3.1", optional = true }
parity-util-mem = { version = "0.9.0", default-features = false, features = ["primitive-types"] }
serde = { version = "1.0.101", optional = true, features = ["derive"] }
# Substrate Based Dependencies
frame-support = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
frame-system = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
max-encoded-len = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false, features = ["derive"] }
sp-api = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-core = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-io = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-std = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-trie = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
[features]
default = ["std"]
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",
"max-encoded-len/std",
"parity-util-mem/std",
"serde",
"sp-api/std",
"sp-core/std",
"sp-io/std",
"sp-runtime/std",
"sp-std/std",
"sp-trie/std",
]
@@ -1,342 +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)]
// Runtime-generated DecodeLimit::decode_all_With_depth_limit
#![allow(clippy::unnecessary_mut_passed)]
mod millau_hash;
use bp_messages::{LaneId, MessageDetails, MessageNonce, UnrewardedRelayersState};
use bp_runtime::Chain;
use frame_support::{
weights::{constants::WEIGHT_PER_SECOND, DispatchClass, Weight},
Parameter, RuntimeDebug,
};
use frame_system::limits;
use sp_core::Hasher as HasherT;
use sp_runtime::traits::Convert;
use sp_runtime::{
traits::{IdentifyAccount, Verify},
MultiSignature, MultiSigner, Perbill,
};
use sp_std::prelude::*;
use sp_trie::{trie_types::Layout, TrieConfiguration};
#[cfg(feature = "std")]
use serde::{Deserialize, Serialize};
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;
/// Maximal size (in bytes) of encoded (using `Encode::encode()`) account id.
pub const MAXIMAL_ENCODED_ACCOUNT_ID_SIZE: u32 = 32;
/// Maximum weight of single Millau block.
///
/// This represents 0.5 seconds of compute assuming a target block time of six seconds.
pub const MAXIMUM_BLOCK_WEIGHT: Weight = WEIGHT_PER_SECOND / 2;
/// Represents the average portion of a block's weight that will be used by an
/// `on_initialize()` runtime call.
pub const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);
/// 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 at inbound lane.
pub const MAX_UNREWARDED_RELAYER_ENTRIES_AT_INBOUND_LANE: MessageNonce = 1024;
/// Maximal number of unconfirmed messages at inbound lane.
pub const MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE: MessageNonce = 1024;
/// Weight of single regular message delivery transaction on Millau chain.
///
/// This value is a result of `pallet_bridge_messages::Pallet::receive_messages_proof_weight()` call
/// for the case when single message of `pallet_bridge_messages::EXPECTED_DEFAULT_MESSAGE_LENGTH` bytes is delivered.
/// The message must have dispatch weight set to zero. The result then must be rounded up to account
/// possible future runtime upgrades.
pub const DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT: Weight = 1_500_000_000;
/// Increase of delivery transaction weight on Millau chain with every additional message byte.
///
/// This value is a result of `pallet_bridge_messages::WeightInfoExt::storage_proof_size_overhead(1)` call. The
/// result then must be rounded up to account possible future runtime upgrades.
pub const ADDITIONAL_MESSAGE_BYTE_DELIVERY_WEIGHT: Weight = 25_000;
/// Maximal weight of single message delivery confirmation transaction on Millau chain.
///
/// This value is a result of `pallet_bridge_messages::Pallet::receive_messages_delivery_proof` weight formula computation
/// for the case when single message is confirmed. The result then must be rounded up to account possible future
/// runtime upgrades.
pub const MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT: Weight = 2_000_000_000;
/// Weight of pay-dispatch-fee operation for inbound messages at Millau chain.
///
/// This value corresponds to the result of `pallet_bridge_messages::WeightInfoExt::pay_inbound_dispatch_fee_overhead()`
/// call for your chain. Don't put too much reserve there, because it is used to **decrease**
/// `DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT` cost. So putting large reserve would make delivery transactions cheaper.
pub const PAY_INBOUND_DISPATCH_FEE_WEIGHT: Weight = 600_000_000;
/// 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;
/// 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;
/// The type of an 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;
/// Millau chain.
#[derive(RuntimeDebug)]
pub struct Millau;
impl Chain for Millau {
type BlockNumber = BlockNumber;
type Hash = Hash;
type Hasher = Hasher;
type Header = Header;
}
/// Millau Hasher (Blake2-256 ++ Keccak-256) implementation.
#[derive(PartialEq, Eq, Clone, Copy, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(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>)>) -> Self::Output {
Layout::<BlakeTwoAndKeccak256>::trie_root(input)
}
fn ordered_trie_root(input: Vec<Vec<u8>>) -> Self::Output {
Layout::<BlakeTwoAndKeccak256>::ordered_trie_root(input)
}
}
/// Convert a 256-bit hash into an AccountId.
pub struct AccountIdConverter;
impl sp_runtime::traits::Convert<sp_core::H256, AccountId> for AccountIdConverter {
fn convert(hash: sp_core::H256) -> AccountId {
hash.to_fixed_bytes().into()
}
}
/// We use this to get the account on Millau (target) which is derived from Rialto's (source)
/// account. We do this so we can fund the derived account on Millau at Genesis to it can pay
/// transaction fees.
///
/// The reason we can use the same `AccountId` type for both chains is because they share the same
/// development seed phrase.
///
/// Note that this should only be used for testing.
pub fn derive_account_from_rialto_id(id: bp_runtime::SourceAccount<AccountId>) -> AccountId {
let encoded_id = bp_runtime::derive_account_id(bp_runtime::RIALTO_CHAIN_ID, id);
AccountIdConverter::convert(encoded_id)
}
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::builder()
// Allowance for Normal class
.for_class(DispatchClass::Normal, |weights| {
weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
})
// Allowance for Operational class
.for_class(DispatchClass::Operational, |weights| {
weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
// Extra reserved space for Operational class
weights.reserved = Some(MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
})
// By default Mandatory class is not limited at all.
// This parameter is used to derive maximal size of a single extrinsic.
.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
.build_or_panic();
}
/// Get the maximum weight (compute time) that a Normal extrinsic on the Millau chain can use.
pub fn max_extrinsic_weight() -> Weight {
BlockWeights::get()
.get(DispatchClass::Normal)
.max_extrinsic
.unwrap_or(Weight::MAX)
}
/// Get the maximum length in bytes that a Normal extrinsic on the Millau chain requires.
pub fn max_extrinsic_size() -> u32 {
*BlockLength::get().max.get(DispatchClass::Normal)
}
/// Name of the `MillauFinalityApi::best_finalized` runtime method.
pub const BEST_FINALIZED_MILLAU_HEADER_METHOD: &str = "MillauFinalityApi_best_finalized";
/// Name of the `ToMillauOutboundLaneApi::estimate_message_delivery_and_dispatch_fee` runtime method.
pub const TO_MILLAU_ESTIMATE_MESSAGE_FEE_METHOD: &str =
"ToMillauOutboundLaneApi_estimate_message_delivery_and_dispatch_fee";
/// Name of the `ToMillauOutboundLaneApi::message_details` runtime method.
pub const TO_MILLAU_MESSAGE_DETAILS_METHOD: &str = "ToMillauOutboundLaneApi_message_details";
/// Name of the `ToMillauOutboundLaneApi::latest_received_nonce` runtime method.
pub const TO_MILLAU_LATEST_RECEIVED_NONCE_METHOD: &str = "ToMillauOutboundLaneApi_latest_received_nonce";
/// Name of the `ToMillauOutboundLaneApi::latest_generated_nonce` runtime method.
pub const TO_MILLAU_LATEST_GENERATED_NONCE_METHOD: &str = "ToMillauOutboundLaneApi_latest_generated_nonce";
/// Name of the `FromMillauInboundLaneApi::latest_received_nonce` runtime method.
pub const FROM_MILLAU_LATEST_RECEIVED_NONCE_METHOD: &str = "FromMillauInboundLaneApi_latest_received_nonce";
/// Name of the `FromMillauInboundLaneApi::latest_onfirmed_nonce` runtime method.
pub const FROM_MILLAU_LATEST_CONFIRMED_NONCE_METHOD: &str = "FromMillauInboundLaneApi_latest_confirmed_nonce";
/// Name of the `FromMillauInboundLaneApi::unrewarded_relayers_state` runtime method.
pub const FROM_MILLAU_UNREWARDED_RELAYERS_STATE: &str = "FromMillauInboundLaneApi_unrewarded_relayers_state";
sp_api::decl_runtime_apis! {
/// API for querying information about the finalized Millau headers.
///
/// This API is implemented by runtimes that are bridging with the Millau chain, not the
/// Millau runtime itself.
pub trait MillauFinalityApi {
/// Returns number and hash of the best finalized header known to the bridge module.
fn best_finalized() -> (BlockNumber, Hash);
/// Returns true if the header is known to the runtime.
fn is_known_header(hash: Hash) -> bool;
}
/// Outbound message lane API for messages that are sent to Millau chain.
///
/// This API is implemented by runtimes that are sending messages to Millau chain, not the
/// Millau runtime itself.
pub trait ToMillauOutboundLaneApi<OutboundMessageFee: Parameter, OutboundPayload: Parameter> {
/// Estimate message delivery and dispatch fee that needs to be paid by the sender on
/// this chain.
///
/// Returns `None` if message is too expensive to be sent to Millau from this chain.
///
/// Please keep in mind that this method returns lowest message fee required for message
/// to be accepted to the lane. It may be good idea to pay a bit over this price to account
/// future exchange rate changes and guarantee that relayer would deliver your message
/// to the target chain.
fn estimate_message_delivery_and_dispatch_fee(
lane_id: LaneId,
payload: OutboundPayload,
) -> Option<OutboundMessageFee>;
/// Returns dispatch weight, encoded payload size and delivery+dispatch fee of all
/// messages in given inclusive range.
///
/// If some (or all) messages are missing from the storage, they'll also will
/// be missing from the resulting vector. The vector is ordered by the nonce.
fn message_details(
lane: LaneId,
begin: MessageNonce,
end: MessageNonce,
) -> Vec<MessageDetails<OutboundMessageFee>>;
/// Returns nonce of the latest message, received by bridged chain.
fn latest_received_nonce(lane: LaneId) -> MessageNonce;
/// Returns nonce of the latest message, generated by given lane.
fn latest_generated_nonce(lane: LaneId) -> MessageNonce;
}
/// Inbound message lane API for messages sent by Millau chain.
///
/// This API is implemented by runtimes that are receiving messages from Millau chain, not the
/// Millau runtime itself.
pub trait FromMillauInboundLaneApi {
/// Returns nonce of the latest message, received by given lane.
fn latest_received_nonce(lane: LaneId) -> MessageNonce;
/// Nonce of latest message that has been confirmed to the bridged chain.
fn latest_confirmed_nonce(lane: LaneId) -> MessageNonce;
/// State of the unrewarded relayers set at given lane.
fn unrewarded_relayers_state(lane: LaneId) -> UnrewardedRelayersState;
}
}
#[cfg(test)]
mod tests {
use super::*;
use sp_runtime::codec::Encode;
#[test]
fn maximal_account_size_does_not_overflow_constant() {
assert!(
MAXIMAL_ENCODED_ACCOUNT_ID_SIZE as usize >= AccountId::default().encode().len(),
"Actual maximal size of encoded AccountId ({}) overflows expected ({})",
AccountId::default().encode().len(),
MAXIMAL_ENCODED_ACCOUNT_ID_SIZE,
);
}
}
@@ -1,58 +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 frame_support::traits::MaxEncodedLen;
use parity_util_mem::MallocSizeOf;
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, MaxEncodedLen)]
pub struct MillauHash(64);
}
#[cfg(feature = "std")]
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,29 +0,0 @@
[package]
name = "bp-polkadot"
description = "Primitives of Polkadot runtime."
version = "0.1.0"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2018"
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
[dependencies]
# Bridge Dependencies
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
sp-api = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-std = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
[features]
default = ["std"]
std = [
"bp-messages/std",
"bp-polkadot-core/std",
"bp-runtime/std",
"sp-api/std",
"sp-std/std",
]
@@ -1,118 +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)]
// Runtime-generated DecodeLimit::decode_all_with_depth_limit
#![allow(clippy::unnecessary_mut_passed)]
use bp_messages::{LaneId, MessageDetails, MessageNonce, UnrewardedRelayersState};
use sp_std::prelude::*;
pub use bp_polkadot_core::*;
/// Polkadot Chain
pub type Polkadot = PolkadotLike;
// We use this to get the account on Polkadot (target) which is derived from Kusama's (source)
// account.
pub fn derive_account_from_kusama_id(id: bp_runtime::SourceAccount<AccountId>) -> AccountId {
let encoded_id = bp_runtime::derive_account_id(bp_runtime::KUSAMA_CHAIN_ID, id);
AccountIdConverter::convert(encoded_id)
}
/// Name of the `PolkadotFinalityApi::best_finalized` runtime method.
pub const BEST_FINALIZED_POLKADOT_HEADER_METHOD: &str = "PolkadotFinalityApi_best_finalized";
/// Name of the `PolkadotFinalityApi::is_known_header` runtime method.
pub const IS_KNOWN_POLKADOT_HEADER_METHOD: &str = "PolkadotFinalityApi_is_known_header";
/// Name of the `ToPolkadotOutboundLaneApi::estimate_message_delivery_and_dispatch_fee` runtime method.
pub const TO_POLKADOT_ESTIMATE_MESSAGE_FEE_METHOD: &str =
"ToPolkadotOutboundLaneApi_estimate_message_delivery_and_dispatch_fee";
/// Name of the `ToPolkadotOutboundLaneApi::message_details` runtime method.
pub const TO_POLKADOT_MESSAGE_DETAILS_METHOD: &str = "ToPolkadotOutboundLaneApi_message_details";
/// Name of the `ToPolkadotOutboundLaneApi::latest_generated_nonce` runtime method.
pub const TO_POLKADOT_LATEST_GENERATED_NONCE_METHOD: &str = "ToPolkadotOutboundLaneApi_latest_generated_nonce";
/// Name of the `ToPolkadotOutboundLaneApi::latest_received_nonce` runtime method.
pub const TO_POLKADOT_LATEST_RECEIVED_NONCE_METHOD: &str = "ToPolkadotOutboundLaneApi_latest_received_nonce";
/// Name of the `FromPolkadotInboundLaneApi::latest_received_nonce` runtime method.
pub const FROM_POLKADOT_LATEST_RECEIVED_NONCE_METHOD: &str = "FromPolkadotInboundLaneApi_latest_received_nonce";
/// Name of the `FromPolkadotInboundLaneApi::latest_onfirmed_nonce` runtime method.
pub const FROM_POLKADOT_LATEST_CONFIRMED_NONCE_METHOD: &str = "FromPolkadotInboundLaneApi_latest_confirmed_nonce";
/// Name of the `FromPolkadotInboundLaneApi::unrewarded_relayers_state` runtime method.
pub const FROM_POLKADOT_UNREWARDED_RELAYERS_STATE: &str = "FromPolkadotInboundLaneApi_unrewarded_relayers_state";
sp_api::decl_runtime_apis! {
/// API for querying information about the finalized Polkadot headers.
///
/// This API is implemented by runtimes that are bridging with the Polkadot chain, not the
/// Polkadot runtime itself.
pub trait PolkadotFinalityApi {
/// Returns number and hash of the best finalized header known to the bridge module.
fn best_finalized() -> (BlockNumber, Hash);
/// Returns true if the header is known to the runtime.
fn is_known_header(hash: Hash) -> bool;
}
/// Outbound message lane API for messages that are sent to Polkadot chain.
///
/// This API is implemented by runtimes that are sending messages to Polkadot chain, not the
/// Polkadot runtime itself.
pub trait ToPolkadotOutboundLaneApi<OutboundMessageFee: Parameter, OutboundPayload: Parameter> {
/// Estimate message delivery and dispatch fee that needs to be paid by the sender on
/// this chain.
///
/// Returns `None` if message is too expensive to be sent to Polkadot from this chain.
///
/// Please keep in mind that this method returns the lowest message fee required for message
/// to be accepted to the lane. It may be good idea to pay a bit over this price to account
/// future exchange rate changes and guarantee that relayer would deliver your message
/// to the target chain.
fn estimate_message_delivery_and_dispatch_fee(
lane_id: LaneId,
payload: OutboundPayload,
) -> Option<OutboundMessageFee>;
/// Returns dispatch weight, encoded payload size and delivery+dispatch fee of all
/// messages in given inclusive range.
///
/// If some (or all) messages are missing from the storage, they'll also will
/// be missing from the resulting vector. The vector is ordered by the nonce.
fn message_details(
lane: LaneId,
begin: MessageNonce,
end: MessageNonce,
) -> Vec<MessageDetails<OutboundMessageFee>>;
/// Returns nonce of the latest message, received by bridged chain.
fn latest_received_nonce(lane: LaneId) -> MessageNonce;
/// Returns nonce of the latest message, generated by given lane.
fn latest_generated_nonce(lane: LaneId) -> MessageNonce;
}
/// Inbound message lane API for messages sent by Polkadot chain.
///
/// This API is implemented by runtimes that are receiving messages from Polkadot chain, not the
/// Polkadot runtime itself.
pub trait FromPolkadotInboundLaneApi {
/// Returns nonce of the latest message, received by given lane.
fn latest_received_nonce(lane: LaneId) -> MessageNonce;
/// Nonce of the latest message that has been confirmed to the bridged chain.
fn latest_confirmed_nonce(lane: LaneId) -> MessageNonce;
/// State of the unrewarded relayers set at given lane.
fn unrewarded_relayers_state(lane: LaneId) -> UnrewardedRelayersState;
}
}
@@ -1,36 +0,0 @@
[package]
name = "bp-rialto"
description = "Primitives of Rialto runtime."
version = "0.1.0"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2018"
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
[dependencies]
# Bridge Dependencies
bp-messages = { path = "../messages", default-features = false }
bp-runtime = { path = "../runtime", default-features = false }
# Substrate Based Dependencies
frame-support = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
frame-system = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-api = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-core = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-std = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
[features]
default = ["std"]
std = [
"bp-messages/std",
"bp-runtime/std",
"frame-support/std",
"frame-system/std",
"sp-api/std",
"sp-core/std",
"sp-runtime/std",
"sp-std/std",
]
@@ -1,303 +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)]
// Runtime-generated DecodeLimit::decode_all_With_depth_limit
#![allow(clippy::unnecessary_mut_passed)]
use bp_messages::{LaneId, MessageDetails, MessageNonce, UnrewardedRelayersState};
use bp_runtime::Chain;
use frame_support::{
weights::{constants::WEIGHT_PER_SECOND, DispatchClass, Weight},
Parameter, RuntimeDebug,
};
use frame_system::limits;
use sp_core::Hasher as HasherT;
use sp_runtime::{
traits::{BlakeTwo256, Convert, IdentifyAccount, Verify},
MultiSignature, MultiSigner, Perbill,
};
use sp_std::prelude::*;
/// 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 = 103;
/// Maximal size (in bytes) of encoded (using `Encode::encode()`) account id.
pub const MAXIMAL_ENCODED_ACCOUNT_ID_SIZE: u32 = 32;
/// Maximal weight of single Rialto block.
///
/// This represents two seconds of compute assuming a target block time of six seconds.
pub const MAXIMUM_BLOCK_WEIGHT: Weight = 2 * WEIGHT_PER_SECOND;
/// Represents the average portion of a block's weight that will be used by an
/// `on_initialize()` runtime call.
pub const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);
/// 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 at inbound lane.
pub const MAX_UNREWARDED_RELAYER_ENTRIES_AT_INBOUND_LANE: MessageNonce = 128;
/// Maximal number of unconfirmed messages at inbound lane.
pub const MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE: MessageNonce = 128;
/// Weight of single regular message delivery transaction on Rialto chain.
///
/// This value is a result of `pallet_bridge_messages::Pallet::receive_messages_proof_weight()` call
/// for the case when single message of `pallet_bridge_messages::EXPECTED_DEFAULT_MESSAGE_LENGTH` bytes is delivered.
/// The message must have dispatch weight set to zero. The result then must be rounded up to account
/// possible future runtime upgrades.
pub const DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT: Weight = 1_500_000_000;
/// Increase of delivery transaction weight on Rialto chain with every additional message byte.
///
/// This value is a result of `pallet_bridge_messages::WeightInfoExt::storage_proof_size_overhead(1)` call. The
/// result then must be rounded up to account possible future runtime upgrades.
pub const ADDITIONAL_MESSAGE_BYTE_DELIVERY_WEIGHT: Weight = 25_000;
/// Maximal weight of single message delivery confirmation transaction on Rialto chain.
///
/// This value is a result of `pallet_bridge_messages::Pallet::receive_messages_delivery_proof` weight formula computation
/// for the case when single message is confirmed. The result then must be rounded up to account possible future
/// runtime upgrades.
pub const MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT: Weight = 2_000_000_000;
/// Weight of pay-dispatch-fee operation for inbound messages at Rialto chain.
///
/// This value corresponds to the result of `pallet_bridge_messages::WeightInfoExt::pay_inbound_dispatch_fee_overhead()`
/// call for your chain. Don't put too much reserve there, because it is used to **decrease**
/// `DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT` cost. So putting large reserve would make delivery transactions cheaper.
pub const PAY_INBOUND_DISPATCH_FEE_WEIGHT: Weight = 600_000_000;
/// 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;
/// 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 Rialto.
pub type BlockNumber = u32;
/// Hash type used in Rialto.
pub type Hash = <BlakeTwo256 as HasherT>::Out;
/// The type of an 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;
/// Rialto chain.
#[derive(RuntimeDebug)]
pub struct Rialto;
impl Chain for Rialto {
type BlockNumber = BlockNumber;
type Hash = Hash;
type Hasher = Hasher;
type Header = Header;
}
/// Convert a 256-bit hash into an AccountId.
pub struct AccountIdConverter;
impl Convert<sp_core::H256, AccountId> for AccountIdConverter {
fn convert(hash: sp_core::H256) -> AccountId {
hash.to_fixed_bytes().into()
}
}
// We use this to get the account on Rialto (target) which is derived from Millau's (source)
// account. We do this so we can fund the derived account on Rialto at Genesis to it can pay
// transaction fees.
//
// The reason we can use the same `AccountId` type for both chains is because they share the same
// development seed phrase.
//
// Note that this should only be used for testing.
pub fn derive_account_from_millau_id(id: bp_runtime::SourceAccount<AccountId>) -> AccountId {
let encoded_id = bp_runtime::derive_account_id(bp_runtime::MILLAU_CHAIN_ID, id);
AccountIdConverter::convert(encoded_id)
}
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::builder()
// Allowance for Normal class
.for_class(DispatchClass::Normal, |weights| {
weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
})
// Allowance for Operational class
.for_class(DispatchClass::Operational, |weights| {
weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
// Extra reserved space for Operational class
weights.reserved = Some(MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
})
// By default Mandatory class is not limited at all.
// This parameter is used to derive maximal size of a single extrinsic.
.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
.build_or_panic();
}
/// Get the maximum weight (compute time) that a Normal extrinsic on the Millau chain can use.
pub fn max_extrinsic_weight() -> Weight {
BlockWeights::get()
.get(DispatchClass::Normal)
.max_extrinsic
.unwrap_or(Weight::MAX)
}
/// Get the maximum length in bytes that a Normal extrinsic on the Millau chain requires.
pub fn max_extrinsic_size() -> u32 {
*BlockLength::get().max.get(DispatchClass::Normal)
}
/// Name of the `RialtoFinalityApi::best_finalized` runtime method.
pub const BEST_FINALIZED_RIALTO_HEADER_METHOD: &str = "RialtoFinalityApi_best_finalized";
/// Name of the `ToRialtoOutboundLaneApi::estimate_message_delivery_and_dispatch_fee` runtime method.
pub const TO_RIALTO_ESTIMATE_MESSAGE_FEE_METHOD: &str =
"ToRialtoOutboundLaneApi_estimate_message_delivery_and_dispatch_fee";
/// Name of the `ToRialtoOutboundLaneApi::message_details` runtime method.
pub const TO_RIALTO_MESSAGE_DETAILS_METHOD: &str = "ToRialtoOutboundLaneApi_message_details";
/// Name of the `ToRialtoOutboundLaneApi::latest_generated_nonce` runtime method.
pub const TO_RIALTO_LATEST_GENERATED_NONCE_METHOD: &str = "ToRialtoOutboundLaneApi_latest_generated_nonce";
/// Name of the `ToRialtoOutboundLaneApi::latest_received_nonce` runtime method.
pub const TO_RIALTO_LATEST_RECEIVED_NONCE_METHOD: &str = "ToRialtoOutboundLaneApi_latest_received_nonce";
/// Name of the `FromRialtoInboundLaneApi::latest_received_nonce` runtime method.
pub const FROM_RIALTO_LATEST_RECEIVED_NONCE_METHOD: &str = "FromRialtoInboundLaneApi_latest_received_nonce";
/// Name of the `FromRialtoInboundLaneApi::latest_onfirmed_nonce` runtime method.
pub const FROM_RIALTO_LATEST_CONFIRMED_NONCE_METHOD: &str = "FromRialtoInboundLaneApi_latest_confirmed_nonce";
/// Name of the `FromRialtoInboundLaneApi::unrewarded_relayers_state` runtime method.
pub const FROM_RIALTO_UNREWARDED_RELAYERS_STATE: &str = "FromRialtoInboundLaneApi_unrewarded_relayers_state";
sp_api::decl_runtime_apis! {
/// API for querying information about the finalized Rialto headers.
///
/// This API is implemented by runtimes that are bridging with the Rialto chain, not the
/// Millau runtime itself.
pub trait RialtoFinalityApi {
/// Returns number and hash of the best finalized header known to the bridge module.
fn best_finalized() -> (BlockNumber, Hash);
/// Returns true if the header is known to the runtime.
fn is_known_header(hash: Hash) -> bool;
}
/// Outbound message lane API for messages that are sent to Rialto chain.
///
/// This API is implemented by runtimes that are sending messages to Rialto chain, not the
/// Rialto runtime itself.
pub trait ToRialtoOutboundLaneApi<OutboundMessageFee: Parameter, OutboundPayload: Parameter> {
/// Estimate message delivery and dispatch fee that needs to be paid by the sender on
/// this chain.
///
/// Returns `None` if message is too expensive to be sent to Rialto from this chain.
///
/// Please keep in mind that this method returns lowest message fee required for message
/// to be accepted to the lane. It may be good idea to pay a bit over this price to account
/// future exchange rate changes and guarantee that relayer would deliver your message
/// to the target chain.
fn estimate_message_delivery_and_dispatch_fee(
lane_id: LaneId,
payload: OutboundPayload,
) -> Option<OutboundMessageFee>;
/// Returns dispatch weight, encoded payload size and delivery+dispatch fee of all
/// messages in given inclusive range.
///
/// If some (or all) messages are missing from the storage, they'll also will
/// be missing from the resulting vector. The vector is ordered by the nonce.
fn message_details(
lane: LaneId,
begin: MessageNonce,
end: MessageNonce,
) -> Vec<MessageDetails<OutboundMessageFee>>;
/// Returns nonce of the latest message, received by bridged chain.
fn latest_received_nonce(lane: LaneId) -> MessageNonce;
/// Returns nonce of the latest message, generated by given lane.
fn latest_generated_nonce(lane: LaneId) -> MessageNonce;
}
/// Inbound message lane API for messages sent by Rialto chain.
///
/// This API is implemented by runtimes that are receiving messages from Rialto chain, not the
/// Rialto runtime itself.
pub trait FromRialtoInboundLaneApi {
/// Returns nonce of the latest message, received by given lane.
fn latest_received_nonce(lane: LaneId) -> MessageNonce;
/// Nonce of latest message that has been confirmed to the bridged chain.
fn latest_confirmed_nonce(lane: LaneId) -> MessageNonce;
/// State of the unrewarded relayers set at given lane.
fn unrewarded_relayers_state(lane: LaneId) -> UnrewardedRelayersState;
}
}
#[cfg(test)]
mod tests {
use super::*;
use sp_runtime::codec::Encode;
#[test]
fn maximal_account_size_does_not_overflow_constant() {
assert!(
MAXIMAL_ENCODED_ACCOUNT_ID_SIZE as usize >= AccountId::default().encode().len(),
"Actual maximal size of encoded AccountId ({}) overflows expected ({})",
AccountId::default().encode().len(),
MAXIMAL_ENCODED_ACCOUNT_ID_SIZE,
);
}
}
@@ -1,37 +0,0 @@
[package]
name = "bp-rococo"
description = "Primitives of Rococo runtime."
version = "0.1.0"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2018"
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
[dependencies]
parity-scale-codec = { version = "2.0.0", default-features = false, features = ["derive"] }
smallvec = "1.6"
# Bridge Dependencies
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/substrate", branch = "master" , default-features = false }
sp-api = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
sp-std = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
sp-version = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
[features]
default = ["std"]
std = [
"bp-messages/std",
"bp-polkadot-core/std",
"bp-runtime/std",
"frame-support/std",
"parity-scale-codec/std",
"sp-api/std",
"sp-runtime/std",
"sp-std/std",
"sp-version/std",
]
@@ -1,155 +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)]
// Runtime-generated DecodeLimit::decode_all_with_depth_limit
#![allow(clippy::unnecessary_mut_passed)]
use bp_messages::{LaneId, MessageDetails, MessageNonce, UnrewardedRelayersState};
use frame_support::weights::{WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial};
use sp_std::prelude::*;
use sp_version::RuntimeVersion;
pub use bp_polkadot_core::*;
/// Rococo Chain
pub type Rococo = PolkadotLike;
/// The target length of a session (how often authorities change) on Westend 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 = 10 * time_units::MINUTES;
// NOTE: This needs to be kept up to date with the Rococo runtime found in the Polkadot repo.
pub const VERSION: RuntimeVersion = RuntimeVersion {
spec_name: sp_version::create_runtime_str!("rococo"),
impl_name: sp_version::create_runtime_str!("parity-rococo-v1.6"),
authoring_version: 0,
spec_version: 9004,
impl_version: 0,
apis: sp_version::create_apis_vec![[]],
transaction_version: 0,
};
// NOTE: This needs to be kept up to date with the Rococo runtime found in the Polkadot repo.
pub struct WeightToFee;
impl WeightToFeePolynomial for WeightToFee {
type Balance = Balance;
fn polynomial() -> WeightToFeeCoefficients<Balance> {
const CENTS: Balance = 1_000_000_000_000 / 100;
let p = CENTS;
let q = 10 * Balance::from(ExtrinsicBaseWeight::get());
smallvec::smallvec![WeightToFeeCoefficient {
degree: 1,
negative: false,
coeff_frac: Perbill::from_rational(p % q, q),
coeff_integer: p / q,
}]
}
}
// We use this to get the account on Rococo (target) which is derived from Wococo's (source)
// account.
pub fn derive_account_from_wococo_id(id: bp_runtime::SourceAccount<AccountId>) -> AccountId {
let encoded_id = bp_runtime::derive_account_id(bp_runtime::WOCOCO_CHAIN_ID, id);
AccountIdConverter::convert(encoded_id)
}
/// Name of the `RococoFinalityApi::best_finalized` runtime method.
pub const BEST_FINALIZED_ROCOCO_HEADER_METHOD: &str = "RococoFinalityApi_best_finalized";
/// Name of the `RococoFinalityApi::is_known_header` runtime method.
pub const IS_KNOWN_ROCOCO_HEADER_METHOD: &str = "RococoFinalityApi_is_known_header";
/// Name of the `ToRococoOutboundLaneApi::estimate_message_delivery_and_dispatch_fee` runtime method.
pub const TO_ROCOCO_ESTIMATE_MESSAGE_FEE_METHOD: &str =
"ToRococoOutboundLaneApi_estimate_message_delivery_and_dispatch_fee";
/// Name of the `ToRococoOutboundLaneApi::message_details` runtime method.
pub const TO_ROCOCO_MESSAGE_DETAILS_METHOD: &str = "ToRococoOutboundLaneApi_message_details";
/// Name of the `ToRococoOutboundLaneApi::latest_generated_nonce` runtime method.
pub const TO_ROCOCO_LATEST_GENERATED_NONCE_METHOD: &str = "ToRococoOutboundLaneApi_latest_generated_nonce";
/// Name of the `ToRococoOutboundLaneApi::latest_received_nonce` runtime method.
pub const TO_ROCOCO_LATEST_RECEIVED_NONCE_METHOD: &str = "ToRococoOutboundLaneApi_latest_received_nonce";
/// Name of the `FromRococoInboundLaneApi::latest_received_nonce` runtime method.
pub const FROM_ROCOCO_LATEST_RECEIVED_NONCE_METHOD: &str = "FromRococoInboundLaneApi_latest_received_nonce";
/// Name of the `FromRococoInboundLaneApi::latest_onfirmed_nonce` runtime method.
pub const FROM_ROCOCO_LATEST_CONFIRMED_NONCE_METHOD: &str = "FromRococoInboundLaneApi_latest_confirmed_nonce";
/// Name of the `FromRococoInboundLaneApi::unrewarded_relayers_state` runtime method.
pub const FROM_ROCOCO_UNREWARDED_RELAYERS_STATE: &str = "FromRococoInboundLaneApi_unrewarded_relayers_state";
sp_api::decl_runtime_apis! {
/// API for querying information about the finalized Rococo headers.
///
/// This API is implemented by runtimes that are bridging with the Rococo chain, not the
/// Rococo runtime itself.
pub trait RococoFinalityApi {
/// Returns number and hash of the best finalized header known to the bridge module.
fn best_finalized() -> (BlockNumber, Hash);
/// Returns true if the header is known to the runtime.
fn is_known_header(hash: Hash) -> bool;
}
/// Outbound message lane API for messages that are sent to Rococo chain.
///
/// This API is implemented by runtimes that are sending messages to Rococo chain, not the
/// Rococo runtime itself.
pub trait ToRococoOutboundLaneApi<OutboundMessageFee: Parameter, OutboundPayload: Parameter> {
/// Estimate message delivery and dispatch fee that needs to be paid by the sender on
/// this chain.
///
/// Returns `None` if message is too expensive to be sent to Rococo from this chain.
///
/// Please keep in mind that this method returns the lowest message fee required for message
/// to be accepted to the lane. It may be good idea to pay a bit over this price to account
/// future exchange rate changes and guarantee that relayer would deliver your message
/// to the target chain.
fn estimate_message_delivery_and_dispatch_fee(
lane_id: LaneId,
payload: OutboundPayload,
) -> Option<OutboundMessageFee>;
/// Returns dispatch weight, encoded payload size and delivery+dispatch fee of all
/// messages in given inclusive range.
///
/// If some (or all) messages are missing from the storage, they'll also will
/// be missing from the resulting vector. The vector is ordered by the nonce.
fn message_details(
lane: LaneId,
begin: MessageNonce,
end: MessageNonce,
) -> Vec<MessageDetails<OutboundMessageFee>>;
/// Returns nonce of the latest message, received by bridged chain.
fn latest_received_nonce(lane: LaneId) -> MessageNonce;
/// Returns nonce of the latest message, generated by given lane.
fn latest_generated_nonce(lane: LaneId) -> MessageNonce;
}
/// Inbound message lane API for messages sent by Rococo chain.
///
/// This API is implemented by runtimes that are receiving messages from Rococo chain, not the
/// Rococo runtime itself.
pub trait FromRococoInboundLaneApi {
/// Returns nonce of the latest message, received by given lane.
fn latest_received_nonce(lane: LaneId) -> MessageNonce;
/// Nonce of the latest message that has been confirmed to the bridged chain.
fn latest_confirmed_nonce(lane: LaneId) -> MessageNonce;
/// State of the unrewarded relayers set at given lane.
fn unrewarded_relayers_state(lane: LaneId) -> UnrewardedRelayersState;
}
}
@@ -1,36 +0,0 @@
[package]
name = "bp-westend"
description = "Primitives of Westend runtime."
version = "0.1.0"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2018"
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
[dependencies]
parity-scale-codec = { version = "2.0.0", default-features = false, features = ["derive"] }
# Bridge Dependencies
bp-header-chain = { path = "../header-chain", 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
sp-api = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
sp-std = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
sp-version = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
[features]
default = ["std"]
std = [
"bp-header-chain/std",
"bp-messages/std",
"bp-polkadot-core/std",
"bp-runtime/std",
"parity-scale-codec/std",
"sp-api/std",
"sp-runtime/std",
"sp-std/std",
"sp-version/std",
]
@@ -1,180 +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)]
// Runtime-generated DecodeLimit::decode_all_with_depth_limit
#![allow(clippy::unnecessary_mut_passed)]
use bp_messages::{LaneId, MessageDetails, MessageNonce, UnrewardedRelayersState};
use bp_runtime::Chain;
use sp_std::prelude::*;
use sp_version::RuntimeVersion;
pub use bp_polkadot_core::*;
/// Westend Chain
pub type Westend = PolkadotLike;
pub type UncheckedExtrinsic = bp_polkadot_core::UncheckedExtrinsic<Call>;
// NOTE: This needs to be kept up to date with the Westend runtime found in the Polkadot repo.
pub const VERSION: RuntimeVersion = RuntimeVersion {
spec_name: sp_version::create_runtime_str!("westend"),
impl_name: sp_version::create_runtime_str!("parity-westend"),
authoring_version: 2,
spec_version: 51,
impl_version: 0,
apis: sp_version::create_apis_vec![[]],
transaction_version: 5,
};
/// Westend Runtime `Call` enum.
///
/// The enum represents a subset of possible `Call`s we can send to Westend chain.
/// Ideally this code would be auto-generated from Metadata, because we want to
/// avoid depending directly on the ENTIRE runtime just to get the encoding of `Dispatchable`s.
///
/// All entries here (like pretty much in the entire file) must be kept in sync with Westend
/// `construct_runtime`, so that we maintain SCALE-compatibility.
///
/// See: https://github.com/paritytech/polkadot/blob/master/runtime/westend/src/lib.rs
#[derive(parity_scale_codec::Encode, parity_scale_codec::Decode, Debug, PartialEq, Eq, Clone)]
pub enum Call {
/// Rococo bridge pallet.
#[codec(index = 40)]
BridgeGrandpaRococo(BridgeGrandpaRococoCall),
}
#[derive(parity_scale_codec::Encode, parity_scale_codec::Decode, Debug, PartialEq, Eq, Clone)]
#[allow(non_camel_case_types)]
pub enum BridgeGrandpaRococoCall {
#[codec(index = 0)]
submit_finality_proof(
<PolkadotLike as Chain>::Header,
bp_header_chain::justification::GrandpaJustification<<PolkadotLike as Chain>::Header>,
),
#[codec(index = 1)]
initialize(bp_header_chain::InitializationData<<PolkadotLike as Chain>::Header>),
}
impl sp_runtime::traits::Dispatchable for Call {
type Origin = ();
type Config = ();
type Info = ();
type PostInfo = ();
fn dispatch(self, _origin: Self::Origin) -> sp_runtime::DispatchResultWithInfo<Self::PostInfo> {
unimplemented!("The Call is not expected to be dispatched.")
}
}
// We use this to get the account on Westend (target) which is derived from Rococo's (source)
// account.
pub fn derive_account_from_rococo_id(id: bp_runtime::SourceAccount<AccountId>) -> AccountId {
let encoded_id = bp_runtime::derive_account_id(bp_runtime::ROCOCO_CHAIN_ID, id);
AccountIdConverter::convert(encoded_id)
}
/// Name of the `WestendFinalityApi::best_finalized` runtime method.
pub const BEST_FINALIZED_WESTEND_HEADER_METHOD: &str = "WestendFinalityApi_best_finalized";
/// Name of the `WestendFinalityApi::is_known_header` runtime method.
pub const IS_KNOWN_WESTEND_HEADER_METHOD: &str = "WestendFinalityApi_is_known_header";
/// Name of the `ToWestendOutboundLaneApi::estimate_message_delivery_and_dispatch_fee` runtime method.
pub const TO_WESTEND_ESTIMATE_MESSAGE_FEE_METHOD: &str =
"ToWestendOutboundLaneApi_estimate_message_delivery_and_dispatch_fee";
/// Name of the `ToWestendOutboundLaneApi::message_details` runtime method.
pub const TO_WESTEND_MESSAGE_DETAILS_METHOD: &str = "ToWestendOutboundLaneApi_message_details";
/// Name of the `ToWestendOutboundLaneApi::latest_generated_nonce` runtime method.
pub const TO_WESTEND_LATEST_GENERATED_NONCE_METHOD: &str = "ToWestendOutboundLaneApi_latest_generated_nonce";
/// Name of the `ToWestendOutboundLaneApi::latest_received_nonce` runtime method.
pub const TO_WESTEND_LATEST_RECEIVED_NONCE_METHOD: &str = "ToWestendOutboundLaneApi_latest_received_nonce";
/// Name of the `FromWestendInboundLaneApi::latest_received_nonce` runtime method.
pub const FROM_WESTEND_LATEST_RECEIVED_NONCE_METHOD: &str = "FromWestendInboundLaneApi_latest_received_nonce";
/// Name of the `FromWestendInboundLaneApi::latest_onfirmed_nonce` runtime method.
pub const FROM_WESTEND_LATEST_CONFIRMED_NONCE_METHOD: &str = "FromWestendInboundLaneApi_latest_confirmed_nonce";
/// Name of the `FromWestendInboundLaneApi::unrewarded_relayers_state` runtime method.
pub const FROM_WESTEND_UNREWARDED_RELAYERS_STATE: &str = "FromWestendInboundLaneApi_unrewarded_relayers_state";
/// The target length of a session (how often authorities change) on Westend 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 = 10 * time_units::MINUTES;
sp_api::decl_runtime_apis! {
/// API for querying information about the finalized Westend headers.
///
/// This API is implemented by runtimes that are bridging with the Westend chain, not the
/// Westend runtime itself.
pub trait WestendFinalityApi {
/// Returns number and hash of the best finalized header known to the bridge module.
fn best_finalized() -> (BlockNumber, Hash);
/// Returns true if the header is known to the runtime.
fn is_known_header(hash: Hash) -> bool;
}
/// Outbound message lane API for messages that are sent to Westend chain.
///
/// This API is implemented by runtimes that are sending messages to Westend chain, not the
/// Westend runtime itself.
pub trait ToWestendOutboundLaneApi<OutboundMessageFee: Parameter, OutboundPayload: Parameter> {
/// Estimate message delivery and dispatch fee that needs to be paid by the sender on
/// this chain.
///
/// Returns `None` if message is too expensive to be sent to Westend from this chain.
///
/// Please keep in mind that this method returns the lowest message fee required for message
/// to be accepted to the lane. It may be good idea to pay a bit over this price to account
/// future exchange rate changes and guarantee that relayer would deliver your message
/// to the target chain.
fn estimate_message_delivery_and_dispatch_fee(
lane_id: LaneId,
payload: OutboundPayload,
) -> Option<OutboundMessageFee>;
/// Returns dispatch weight, encoded payload size and delivery+dispatch fee of all
/// messages in given inclusive range.
///
/// If some (or all) messages are missing from the storage, they'll also will
/// be missing from the resulting vector. The vector is ordered by the nonce.
fn message_details(
lane: LaneId,
begin: MessageNonce,
end: MessageNonce,
) -> Vec<MessageDetails<OutboundMessageFee>>;
/// Returns nonce of the latest message, received by bridged chain.
fn latest_received_nonce(lane: LaneId) -> MessageNonce;
/// Returns nonce of the latest message, generated by given lane.
fn latest_generated_nonce(lane: LaneId) -> MessageNonce;
}
/// Inbound message lane API for messages sent by Westend chain.
///
/// This API is implemented by runtimes that are receiving messages from Westend chain, not the
/// Westend runtime itself.
pub trait FromWestendInboundLaneApi {
/// Returns nonce of the latest message, received by given lane.
fn latest_received_nonce(lane: LaneId) -> MessageNonce;
/// Nonce of the latest message that has been confirmed to the bridged chain.
fn latest_confirmed_nonce(lane: LaneId) -> MessageNonce;
/// State of the unrewarded relayers set at given lane.
fn unrewarded_relayers_state(lane: LaneId) -> UnrewardedRelayersState;
}
}
@@ -1,34 +0,0 @@
[package]
name = "bp-wococo"
description = "Primitives of Wococo runtime."
version = "0.1.0"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2018"
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
[dependencies]
parity-scale-codec = { version = "2.0.0", default-features = false, features = ["derive"] }
# Bridge Dependencies
bp-messages = { path = "../messages", default-features = false }
bp-polkadot-core = { path = "../polkadot-core", default-features = false }
bp-rococo = { path = "../chain-rococo", default-features = false }
bp-runtime = { path = "../runtime", default-features = false }
# Substrate Based Dependencies
sp-api = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
sp-std = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
[features]
default = ["std"]
std = [
"bp-messages/std",
"bp-polkadot-core/std",
"bp-runtime/std",
"bp-rococo/std",
"parity-scale-codec/std",
"sp-api/std",
"sp-runtime/std",
"sp-std/std",
]
@@ -1,120 +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)]
// Runtime-generated DecodeLimit::decode_all_with_depth_limit
#![allow(clippy::unnecessary_mut_passed)]
use bp_messages::{LaneId, MessageDetails, MessageNonce, UnrewardedRelayersState};
use sp_std::prelude::*;
pub use bp_polkadot_core::*;
// Rococo runtime = Wococo runtime
pub use bp_rococo::{WeightToFee, SESSION_LENGTH, VERSION};
/// Wococo Chain
pub type Wococo = PolkadotLike;
// We use this to get the account on Wococo (target) which is derived from Rococo's (source)
// account.
pub fn derive_account_from_rococo_id(id: bp_runtime::SourceAccount<AccountId>) -> AccountId {
let encoded_id = bp_runtime::derive_account_id(bp_runtime::ROCOCO_CHAIN_ID, id);
AccountIdConverter::convert(encoded_id)
}
/// Name of the `WococoFinalityApi::best_finalized` runtime method.
pub const BEST_FINALIZED_WOCOCO_HEADER_METHOD: &str = "WococoFinalityApi_best_finalized";
/// Name of the `WococoFinalityApi::is_known_header` runtime method.
pub const IS_KNOWN_WOCOCO_HEADER_METHOD: &str = "WococoFinalityApi_is_known_header";
/// Name of the `ToWococoOutboundLaneApi::estimate_message_delivery_and_dispatch_fee` runtime method.
pub const TO_WOCOCO_ESTIMATE_MESSAGE_FEE_METHOD: &str =
"ToWococoOutboundLaneApi_estimate_message_delivery_and_dispatch_fee";
/// Name of the `ToWococoOutboundLaneApi::message_details` runtime method.
pub const TO_WOCOCO_MESSAGE_DETAILS_METHOD: &str = "ToWococoOutboundLaneApi_message_details";
/// Name of the `ToWococoOutboundLaneApi::latest_generated_nonce` runtime method.
pub const TO_WOCOCO_LATEST_GENERATED_NONCE_METHOD: &str = "ToWococoOutboundLaneApi_latest_generated_nonce";
/// Name of the `ToWococoOutboundLaneApi::latest_received_nonce` runtime method.
pub const TO_WOCOCO_LATEST_RECEIVED_NONCE_METHOD: &str = "ToWococoOutboundLaneApi_latest_received_nonce";
/// Name of the `FromWococoInboundLaneApi::latest_received_nonce` runtime method.
pub const FROM_WOCOCO_LATEST_RECEIVED_NONCE_METHOD: &str = "FromWococoInboundLaneApi_latest_received_nonce";
/// Name of the `FromWococoInboundLaneApi::latest_onfirmed_nonce` runtime method.
pub const FROM_WOCOCO_LATEST_CONFIRMED_NONCE_METHOD: &str = "FromWococoInboundLaneApi_latest_confirmed_nonce";
/// Name of the `FromWococoInboundLaneApi::unrewarded_relayers_state` runtime method.
pub const FROM_WOCOCO_UNREWARDED_RELAYERS_STATE: &str = "FromWococoInboundLaneApi_unrewarded_relayers_state";
sp_api::decl_runtime_apis! {
/// API for querying information about the finalized Wococo headers.
///
/// This API is implemented by runtimes that are bridging with the Wococo chain, not the
/// Wococo runtime itself.
pub trait WococoFinalityApi {
/// Returns number and hash of the best finalized header known to the bridge module.
fn best_finalized() -> (BlockNumber, Hash);
/// Returns true if the header is known to the runtime.
fn is_known_header(hash: Hash) -> bool;
}
/// Outbound message lane API for messages that are sent to Wococo chain.
///
/// This API is implemented by runtimes that are sending messages to Wococo chain, not the
/// Wococo runtime itself.
pub trait ToWococoOutboundLaneApi<OutboundMessageFee: Parameter, OutboundPayload: Parameter> {
/// Estimate message delivery and dispatch fee that needs to be paid by the sender on
/// this chain.
///
/// Returns `None` if message is too expensive to be sent to Wococo from this chain.
///
/// Please keep in mind that this method returns lowest message fee required for message
/// to be accepted to the lane. It may be good idea to pay a bit over this price to account
/// future exchange rate changes and guarantee that relayer would deliver your message
/// to the target chain.
fn estimate_message_delivery_and_dispatch_fee(
lane_id: LaneId,
payload: OutboundPayload,
) -> Option<OutboundMessageFee>;
/// Returns dispatch weight, encoded payload size and delivery+dispatch fee of all
/// messages in given inclusive range.
///
/// If some (or all) messages are missing from the storage, they'll also will
/// be missing from the resulting vector. The vector is ordered by the nonce.
fn message_details(
lane: LaneId,
begin: MessageNonce,
end: MessageNonce,
) -> Vec<MessageDetails<OutboundMessageFee>>;
/// Returns nonce of the latest message, received by bridged chain.
fn latest_received_nonce(lane: LaneId) -> MessageNonce;
/// Returns nonce of the latest message, generated by given lane.
fn latest_generated_nonce(lane: LaneId) -> MessageNonce;
}
/// Inbound message lane API for messages sent by Wococo chain.
///
/// This API is implemented by runtimes that are receiving messages from Wococo chain, not the
/// Wococo runtime itself.
pub trait FromWococoInboundLaneApi {
/// Returns nonce of the latest message, received by given lane.
fn latest_received_nonce(lane: LaneId) -> MessageNonce;
/// Nonce of latest message that has been confirmed to the bridged chain.
fn latest_confirmed_nonce(lane: LaneId) -> MessageNonce;
/// State of the unrewarded relayers set at given lane.
fn unrewarded_relayers_state(lane: LaneId) -> UnrewardedRelayersState;
}
}
@@ -1,25 +0,0 @@
[package]
name = "bp-currency-exchange"
description = "Primitives of currency exchange module."
version = "0.1.0"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2018"
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
[dependencies]
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false }
# Substrate Dependencies
frame-support = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-api = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-std = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
[features]
default = ["std"]
std = [
"codec/std",
"frame-support/std",
"sp-api/std",
"sp-std/std",
]
@@ -1,150 +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)]
// Generated by `DecodeLimit::decode_with_depth_limit`
#![allow(clippy::unnecessary_mut_passed)]
use codec::{Decode, Encode, EncodeLike};
use frame_support::{Parameter, RuntimeDebug};
use sp_api::decl_runtime_apis;
use sp_std::marker::PhantomData;
/// All errors that may happen during exchange.
#[derive(RuntimeDebug, PartialEq)]
pub enum Error {
/// Invalid peer blockchain transaction provided.
InvalidTransaction,
/// Peer transaction has invalid amount.
InvalidAmount,
/// Peer transaction has invalid recipient.
InvalidRecipient,
/// Cannot map from peer recipient to this blockchain recipient.
FailedToMapRecipients,
/// Failed to convert from peer blockchain currency to this blockhain currency.
FailedToConvertCurrency,
/// Deposit has failed.
DepositFailed,
/// Deposit has partially failed (changes to recipient account were made).
DepositPartiallyFailed,
}
/// Result of all exchange operations.
pub type Result<T> = sp_std::result::Result<T, Error>;
/// Peer blockchain lock funds transaction.
#[derive(Encode, Decode, Clone, RuntimeDebug, PartialEq, Eq)]
pub struct LockFundsTransaction<TransferId, Recipient, Amount> {
/// Something that uniquely identifies this transfer.
pub id: TransferId,
/// Funds recipient on the peer chain.
pub recipient: Recipient,
/// Amount of the locked funds.
pub amount: Amount,
}
/// Peer blockchain transaction that may represent lock funds transaction.
pub trait MaybeLockFundsTransaction {
/// Transaction type.
type Transaction;
/// Identifier that uniquely identifies this transfer.
type Id: Decode + Encode + EncodeLike + sp_std::fmt::Debug;
/// Peer recipient type.
type Recipient;
/// Peer currency amount type.
type Amount;
/// Parse lock funds transaction of the peer blockchain. Returns None if
/// transaction format is unknown, or it isn't a lock funds transaction.
fn parse(tx: &Self::Transaction) -> Result<LockFundsTransaction<Self::Id, Self::Recipient, Self::Amount>>;
}
/// Map that maps recipients from peer blockchain to this blockchain recipients.
pub trait RecipientsMap {
/// Peer blockchain recipient type.
type PeerRecipient;
/// Current blockchain recipient type.
type Recipient;
/// Lookup current blockchain recipient by peer blockchain recipient.
fn map(peer_recipient: Self::PeerRecipient) -> Result<Self::Recipient>;
}
/// Conversion between two currencies.
pub trait CurrencyConverter {
/// Type of the source currency amount.
type SourceAmount;
/// Type of the target currency amount.
type TargetAmount;
/// Covert from source to target currency.
fn convert(amount: Self::SourceAmount) -> Result<Self::TargetAmount>;
}
/// Currency deposit.
pub trait DepositInto {
/// Recipient type.
type Recipient;
/// Currency amount type.
type Amount;
/// Grant some money to given account.
fn deposit_into(recipient: Self::Recipient, amount: Self::Amount) -> Result<()>;
}
/// Recipients map which is used when accounts ids are the same on both chains.
#[derive(Debug)]
pub struct IdentityRecipients<AccountId>(PhantomData<AccountId>);
impl<AccountId> RecipientsMap for IdentityRecipients<AccountId> {
type PeerRecipient = AccountId;
type Recipient = AccountId;
fn map(peer_recipient: Self::PeerRecipient) -> Result<Self::Recipient> {
Ok(peer_recipient)
}
}
/// Currency converter which is used when currency is the same on both chains.
#[derive(Debug)]
pub struct IdentityCurrencyConverter<Amount>(PhantomData<Amount>);
impl<Amount> CurrencyConverter for IdentityCurrencyConverter<Amount> {
type SourceAmount = Amount;
type TargetAmount = Amount;
fn convert(currency: Self::SourceAmount) -> Result<Self::TargetAmount> {
Ok(currency)
}
}
decl_runtime_apis! {
/// API for Rialto exchange transactions submitters.
pub trait RialtoCurrencyExchangeApi<Proof: Parameter> {
/// Returns true if currency exchange module is able to import transaction proof in
/// its current state.
fn filter_transaction_proof(proof: Proof) -> bool;
}
/// API for Kovan exchange transactions submitters.
pub trait KovanCurrencyExchangeApi<Proof: Parameter> {
/// Returns true if currency exchange module is able to import transaction proof in
/// its current state.
fn filter_transaction_proof(proof: Proof) -> bool;
}
}
@@ -1,57 +0,0 @@
[package]
name = "bp-eth-poa"
description = "Primitives of Ethereum PoA Bridge module."
version = "0.1.0"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2018"
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
[dependencies]
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false }
ethbloom = { version = "0.10.0", default-features = false, features = ["rlp"] }
fixed-hash = { version = "0.7", default-features = false }
hash-db = { version = "0.15.2", default-features = false }
impl-rlp = { version = "0.3", default-features = false }
impl-serde = { version = "0.3.1", optional = true }
libsecp256k1 = { version = "0.3.4", default-features = false, features = ["hmac"] }
parity-bytes = { version = "0.1", default-features = false }
plain_hasher = { version = "0.2.2", default-features = false }
primitive-types = { version = "0.9", default-features = false, features = ["codec", "rlp"] }
rlp = { version = "0.5", default-features = false }
serde = { version = "1.0", optional = true }
serde-big-array = { version = "0.2", optional = true }
triehash = { version = "0.8.2", default-features = false }
# Substrate Dependencies
sp-api = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-io = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-std = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
[dev-dependencies]
hex-literal = "0.2"
[features]
default = ["std"]
std = [
"codec/std",
"ethbloom/std",
"fixed-hash/std",
"hash-db/std",
"impl-rlp/std",
"impl-serde",
"libsecp256k1/std",
"parity-bytes/std",
"plain_hasher/std",
"primitive-types/std",
"primitive-types/serde",
"rlp/std",
"serde/std",
"serde-big-array",
"sp-api/std",
"sp-io/std",
"sp-runtime/std",
"sp-std/std",
"triehash/std",
]
@@ -1,734 +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)]
// Generated by `DecodeLimit::decode_with_depth_limit`
#![allow(clippy::unnecessary_mut_passed)]
pub use parity_bytes::Bytes;
pub use primitive_types::{H160, H256, H512, U128, U256};
pub use rlp::encode as rlp_encode;
use codec::{Decode, Encode};
use ethbloom::{Bloom as EthBloom, Input as BloomInput};
use fixed_hash::construct_fixed_hash;
use rlp::{Decodable, DecoderError, Rlp, RlpStream};
use sp_io::hashing::keccak_256;
use sp_runtime::RuntimeDebug;
use sp_std::prelude::*;
use impl_rlp::impl_fixed_hash_rlp;
#[cfg(feature = "std")]
use impl_serde::impl_fixed_hash_serde;
#[cfg(feature = "std")]
use serde::{Deserialize, Serialize};
#[cfg(feature = "std")]
use serde_big_array::big_array;
construct_fixed_hash! { pub struct H520(65); }
impl_fixed_hash_rlp!(H520, 65);
#[cfg(feature = "std")]
impl_fixed_hash_serde!(H520, 65);
/// Raw (RLP-encoded) ethereum transaction.
pub type RawTransaction = Vec<u8>;
/// Raw (RLP-encoded) ethereum transaction receipt.
pub type RawTransactionReceipt = Vec<u8>;
/// An ethereum address.
pub type Address = H160;
pub mod signatures;
/// Complete header id.
#[derive(Encode, Decode, Default, RuntimeDebug, PartialEq, Clone, Copy)]
pub struct HeaderId {
/// Header number.
pub number: u64,
/// Header hash.
pub hash: H256,
}
/// An Aura header.
#[derive(Clone, Default, Encode, Decode, PartialEq, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub struct AuraHeader {
/// Parent block hash.
pub parent_hash: H256,
/// Block timestamp.
pub timestamp: u64,
/// Block number.
pub number: u64,
/// Block author.
pub author: Address,
/// Transactions root.
pub transactions_root: H256,
/// Block uncles hash.
pub uncles_hash: H256,
/// Block extra data.
pub extra_data: Bytes,
/// State root.
pub state_root: H256,
/// Block receipts root.
pub receipts_root: H256,
/// Block bloom.
pub log_bloom: Bloom,
/// Gas used for contracts execution.
pub gas_used: U256,
/// Block gas limit.
pub gas_limit: U256,
/// Block difficulty.
pub difficulty: U256,
/// Vector of post-RLP-encoded fields.
pub seal: Vec<Bytes>,
}
/// Parsed ethereum transaction.
#[derive(PartialEq, RuntimeDebug)]
pub struct Transaction {
/// Sender address.
pub sender: Address,
/// Unsigned portion of ethereum transaction.
pub unsigned: UnsignedTransaction,
}
/// Unsigned portion of ethereum transaction.
#[derive(Clone, PartialEq, RuntimeDebug)]
pub struct UnsignedTransaction {
/// Sender nonce.
pub nonce: U256,
/// Gas price.
pub gas_price: U256,
/// Gas limit.
pub gas: U256,
/// Transaction destination address. None if it is contract creation transaction.
pub to: Option<Address>,
/// Value.
pub value: U256,
/// Associated data.
pub payload: Bytes,
}
/// Information describing execution of a transaction.
#[derive(Clone, Encode, Decode, PartialEq, RuntimeDebug)]
pub struct Receipt {
/// The total gas used in the block following execution of the transaction.
pub gas_used: U256,
/// The OR-wide combination of all logs' blooms for this transaction.
pub log_bloom: Bloom,
/// The logs stemming from this transaction.
pub logs: Vec<LogEntry>,
/// Transaction outcome.
pub outcome: TransactionOutcome,
}
/// Transaction outcome store in the receipt.
#[derive(Clone, Encode, Decode, PartialEq, RuntimeDebug)]
pub enum TransactionOutcome {
/// Status and state root are unknown under EIP-98 rules.
Unknown,
/// State root is known. Pre EIP-98 and EIP-658 rules.
StateRoot(H256),
/// Status code is known. EIP-658 rules.
StatusCode(u8),
}
/// A record of execution for a `LOG` operation.
#[derive(Clone, Encode, Decode, PartialEq, RuntimeDebug)]
pub struct LogEntry {
/// The address of the contract executing at the point of the `LOG` operation.
pub address: Address,
/// The topics associated with the `LOG` operation.
pub topics: Vec<H256>,
/// The data associated with the `LOG` operation.
pub data: Bytes,
}
/// Logs bloom.
#[derive(Clone, Encode, Decode)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub struct Bloom(#[cfg_attr(feature = "std", serde(with = "BigArray"))] [u8; 256]);
#[cfg(feature = "std")]
big_array! { BigArray; }
/// An empty step message that is included in a seal, the only difference is that it doesn't include
/// the `parent_hash` in order to save space. The included signature is of the original empty step
/// message, which can be reconstructed by using the parent hash of the block in which this sealed
/// empty message is included.
pub struct SealedEmptyStep {
/// Signature of the original message author.
pub signature: H520,
/// The step this message is generated for.
pub step: u64,
}
impl AuraHeader {
/// Compute id of this header.
pub fn compute_id(&self) -> HeaderId {
HeaderId {
number: self.number,
hash: self.compute_hash(),
}
}
/// Compute hash of this header (keccak of the RLP with seal).
pub fn compute_hash(&self) -> H256 {
keccak_256(&self.rlp(true)).into()
}
/// Get id of this header' parent. Returns None if this is genesis header.
pub fn parent_id(&self) -> Option<HeaderId> {
self.number.checked_sub(1).map(|parent_number| HeaderId {
number: parent_number,
hash: self.parent_hash,
})
}
/// Check if passed transactions receipts are matching receipts root in this header.
/// Returns Ok(computed-root) if check succeeds.
/// Returns Err(computed-root) if check fails.
pub fn check_receipts_root(&self, receipts: &[Receipt]) -> Result<H256, H256> {
check_merkle_proof(self.receipts_root, receipts.iter().map(|r| r.rlp()))
}
/// Check if passed raw transactions receipts are matching receipts root in this header.
/// Returns Ok(computed-root) if check succeeds.
/// Returns Err(computed-root) if check fails.
pub fn check_raw_receipts_root<'a>(
&self,
receipts: impl IntoIterator<Item = &'a RawTransactionReceipt>,
) -> Result<H256, H256> {
check_merkle_proof(self.receipts_root, receipts.into_iter())
}
/// Check if passed transactions are matching transactions root in this header.
/// Returns Ok(computed-root) if check succeeds.
/// Returns Err(computed-root) if check fails.
pub fn check_transactions_root<'a>(
&self,
transactions: impl IntoIterator<Item = &'a RawTransaction>,
) -> Result<H256, H256> {
check_merkle_proof(self.transactions_root, transactions.into_iter())
}
/// Gets the seal hash of this header.
pub fn seal_hash(&self, include_empty_steps: bool) -> Option<H256> {
Some(match include_empty_steps {
true => {
let mut message = self.compute_hash().as_bytes().to_vec();
message.extend_from_slice(self.seal.get(2)?);
keccak_256(&message).into()
}
false => keccak_256(&self.rlp(false)).into(),
})
}
/// Get step this header is generated for.
pub fn step(&self) -> Option<u64> {
self.seal.get(0).map(|x| Rlp::new(x)).and_then(|x| x.as_val().ok())
}
/// Get header author' signature.
pub fn signature(&self) -> Option<H520> {
self.seal.get(1).and_then(|x| Rlp::new(x).as_val().ok())
}
/// Extracts the empty steps from the header seal.
pub fn empty_steps(&self) -> Option<Vec<SealedEmptyStep>> {
self.seal
.get(2)
.and_then(|x| Rlp::new(x).as_list::<SealedEmptyStep>().ok())
}
/// Returns header RLP with or without seals.
fn rlp(&self, with_seal: bool) -> Bytes {
let mut s = RlpStream::new();
if with_seal {
s.begin_list(13 + self.seal.len());
} else {
s.begin_list(13);
}
s.append(&self.parent_hash);
s.append(&self.uncles_hash);
s.append(&self.author);
s.append(&self.state_root);
s.append(&self.transactions_root);
s.append(&self.receipts_root);
s.append(&EthBloom::from(self.log_bloom.0));
s.append(&self.difficulty);
s.append(&self.number);
s.append(&self.gas_limit);
s.append(&self.gas_used);
s.append(&self.timestamp);
s.append(&self.extra_data);
if with_seal {
for b in &self.seal {
s.append_raw(b, 1);
}
}
s.out().to_vec()
}
}
impl UnsignedTransaction {
/// Decode unsigned portion of raw transaction RLP.
pub fn decode_rlp(raw_tx: &[u8]) -> Result<Self, DecoderError> {
let tx_rlp = Rlp::new(raw_tx);
let to = tx_rlp.at(3)?;
Ok(UnsignedTransaction {
nonce: tx_rlp.val_at(0)?,
gas_price: tx_rlp.val_at(1)?,
gas: tx_rlp.val_at(2)?,
to: match to.is_empty() {
false => Some(to.as_val()?),
true => None,
},
value: tx_rlp.val_at(4)?,
payload: tx_rlp.val_at(5)?,
})
}
/// Returns message that has to be signed to sign this transaction.
pub fn message(&self, chain_id: Option<u64>) -> H256 {
keccak_256(&self.rlp(chain_id)).into()
}
/// Returns unsigned transaction RLP.
pub fn rlp(&self, chain_id: Option<u64>) -> Bytes {
let mut stream = RlpStream::new_list(if chain_id.is_some() { 9 } else { 6 });
self.rlp_to(chain_id, &mut stream);
stream.out().to_vec()
}
/// Encode to given rlp stream.
pub fn rlp_to(&self, chain_id: Option<u64>, stream: &mut RlpStream) {
stream.append(&self.nonce);
stream.append(&self.gas_price);
stream.append(&self.gas);
match self.to {
Some(to) => stream.append(&to),
None => stream.append(&""),
};
stream.append(&self.value);
stream.append(&self.payload);
if let Some(chain_id) = chain_id {
stream.append(&chain_id);
stream.append(&0u8);
stream.append(&0u8);
}
}
}
impl Receipt {
/// Decode status from raw transaction receipt RLP.
pub fn is_successful_raw_receipt(raw_receipt: &[u8]) -> Result<bool, DecoderError> {
let rlp = Rlp::new(raw_receipt);
if rlp.item_count()? == 3 {
// no outcome - invalid tx?
Ok(false)
} else {
let first = rlp.at(0)?;
if first.is_data() && first.data()?.len() <= 1 {
// EIP-658 transaction - status of successful transaction is 1
let status: u8 = first.as_val()?;
Ok(status == 1)
} else {
// pre-EIP-658 transaction - we do not support this kind of transactions
Ok(false)
}
}
}
/// Returns receipt RLP.
pub fn rlp(&self) -> Bytes {
let mut s = RlpStream::new();
match self.outcome {
TransactionOutcome::Unknown => {
s.begin_list(3);
}
TransactionOutcome::StateRoot(ref root) => {
s.begin_list(4);
s.append(root);
}
TransactionOutcome::StatusCode(ref status_code) => {
s.begin_list(4);
s.append(status_code);
}
}
s.append(&self.gas_used);
s.append(&EthBloom::from(self.log_bloom.0));
s.begin_list(self.logs.len());
for log in &self.logs {
s.begin_list(3);
s.append(&log.address);
s.begin_list(log.topics.len());
for topic in &log.topics {
s.append(topic);
}
s.append(&log.data);
}
s.out().to_vec()
}
}
impl SealedEmptyStep {
/// Returns message that has to be signed by the validator.
pub fn message(&self, parent_hash: &H256) -> H256 {
let mut message = RlpStream::new_list(2);
message.append(&self.step);
message.append(parent_hash);
keccak_256(&message.out()).into()
}
/// Returns rlp for the vector of empty steps (we only do encoding in tests).
pub fn rlp_of(empty_steps: &[SealedEmptyStep]) -> Bytes {
let mut s = RlpStream::new();
s.begin_list(empty_steps.len());
for empty_step in empty_steps {
s.begin_list(2).append(&empty_step.signature).append(&empty_step.step);
}
s.out().to_vec()
}
}
impl Decodable for SealedEmptyStep {
fn decode(rlp: &Rlp) -> Result<Self, DecoderError> {
let signature: H520 = rlp.val_at(0)?;
let step = rlp.val_at(1)?;
Ok(SealedEmptyStep { signature, step })
}
}
impl LogEntry {
/// Calculates the bloom of this log entry.
pub fn bloom(&self) -> Bloom {
let eth_bloom =
self.topics
.iter()
.fold(EthBloom::from(BloomInput::Raw(self.address.as_bytes())), |mut b, t| {
b.accrue(BloomInput::Raw(t.as_bytes()));
b
});
Bloom(*eth_bloom.data())
}
}
impl Bloom {
/// Returns true if this bloom has all bits from the other set.
pub fn contains(&self, other: &Bloom) -> bool {
self.0.iter().zip(other.0.iter()).all(|(l, r)| (l & r) == *r)
}
}
impl<'a> From<&'a [u8; 256]> for Bloom {
fn from(buffer: &'a [u8; 256]) -> Bloom {
Bloom(*buffer)
}
}
impl PartialEq<Bloom> for Bloom {
fn eq(&self, other: &Bloom) -> bool {
self.0.iter().zip(other.0.iter()).all(|(l, r)| l == r)
}
}
impl Default for Bloom {
fn default() -> Self {
Bloom([0; 256])
}
}
#[cfg(feature = "std")]
impl std::fmt::Debug for Bloom {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
fmt.debug_struct("Bloom").finish()
}
}
/// Decode Ethereum transaction.
pub fn transaction_decode_rlp(raw_tx: &[u8]) -> Result<Transaction, DecoderError> {
// parse transaction fields
let unsigned = UnsignedTransaction::decode_rlp(raw_tx)?;
let tx_rlp = Rlp::new(raw_tx);
let v: u64 = tx_rlp.val_at(6)?;
let r: U256 = tx_rlp.val_at(7)?;
let s: U256 = tx_rlp.val_at(8)?;
// reconstruct signature
let mut signature = [0u8; 65];
let (chain_id, v) = match v {
v if v == 27u64 => (None, 0),
v if v == 28u64 => (None, 1),
v if v >= 35u64 => (Some((v - 35) / 2), ((v - 1) % 2) as u8),
_ => (None, 4),
};
r.to_big_endian(&mut signature[0..32]);
s.to_big_endian(&mut signature[32..64]);
signature[64] = v;
// reconstruct message that has been signed
let message = unsigned.message(chain_id);
// recover tx sender
let sender_public = sp_io::crypto::secp256k1_ecdsa_recover(&signature, message.as_fixed_bytes())
.map_err(|_| rlp::DecoderError::Custom("Failed to recover transaction sender"))?;
let sender_address = public_to_address(&sender_public);
Ok(Transaction {
sender: sender_address,
unsigned,
})
}
/// Convert public key into corresponding ethereum address.
pub fn public_to_address(public: &[u8; 64]) -> Address {
let hash = keccak_256(public);
let mut result = Address::zero();
result.as_bytes_mut().copy_from_slice(&hash[12..]);
result
}
/// Check ethereum merkle proof.
/// Returns Ok(computed-root) if check succeeds.
/// Returns Err(computed-root) if check fails.
fn check_merkle_proof<T: AsRef<[u8]>>(expected_root: H256, items: impl Iterator<Item = T>) -> Result<H256, H256> {
let computed_root = compute_merkle_root(items);
if computed_root == expected_root {
Ok(computed_root)
} else {
Err(computed_root)
}
}
/// Compute ethereum merkle root.
pub fn compute_merkle_root<T: AsRef<[u8]>>(items: impl Iterator<Item = T>) -> H256 {
struct Keccak256Hasher;
impl hash_db::Hasher for Keccak256Hasher {
type Out = H256;
type StdHasher = plain_hasher::PlainHasher;
const LENGTH: usize = 32;
fn hash(x: &[u8]) -> Self::Out {
keccak_256(x).into()
}
}
triehash::ordered_trie_root::<Keccak256Hasher, _>(items)
}
/// Get validator that should author the block at given step.
pub fn step_validator<T>(header_validators: &[T], header_step: u64) -> &T {
&header_validators[(header_step % header_validators.len() as u64) as usize]
}
sp_api::decl_runtime_apis! {
/// API for querying information about headers from the Rialto Bridge Pallet
pub trait RialtoPoAHeaderApi {
/// Returns number and hash of the best block known to the bridge module.
///
/// The caller should only submit an `import_header` transaction that makes
/// (or leads to making) other header the best one.
fn best_block() -> (u64, H256);
/// Returns number and hash of the best finalized block known to the bridge module.
fn finalized_block() -> (u64, H256);
/// Returns true if the import of given block requires transactions receipts.
fn is_import_requires_receipts(header: AuraHeader) -> bool;
/// Returns true if header is known to the runtime.
fn is_known_block(hash: H256) -> bool;
}
/// API for querying information about headers from the Kovan Bridge Pallet
pub trait KovanHeaderApi {
/// Returns number and hash of the best block known to the bridge module.
///
/// The caller should only submit an `import_header` transaction that makes
/// (or leads to making) other header the best one.
fn best_block() -> (u64, H256);
/// Returns number and hash of the best finalized block known to the bridge module.
fn finalized_block() -> (u64, H256);
/// Returns true if the import of given block requires transactions receipts.
fn is_import_requires_receipts(header: AuraHeader) -> bool;
/// Returns true if header is known to the runtime.
fn is_known_block(hash: H256) -> bool;
}
}
#[cfg(test)]
mod tests {
use super::*;
use hex_literal::hex;
#[test]
fn transfer_transaction_decode_works() {
// value transfer transaction
// https://etherscan.io/tx/0xb9d4ad5408f53eac8627f9ccd840ba8fb3469d55cd9cc2a11c6e049f1eef4edd
// https://etherscan.io/getRawTx?tx=0xb9d4ad5408f53eac8627f9ccd840ba8fb3469d55cd9cc2a11c6e049f1eef4edd
let raw_tx = hex!("f86c0a85046c7cfe0083016dea94d1310c1e038bc12865d3d3997275b3e4737c6302880b503be34d9fe80080269fc7eaaa9c21f59adf8ad43ed66cf5ef9ee1c317bd4d32cd65401e7aaca47cfaa0387d79c65b90be6260d09dcfb780f29dd8133b9b1ceb20b83b7e442b4bfc30cb");
assert_eq!(
transaction_decode_rlp(&raw_tx),
Ok(Transaction {
sender: hex!("67835910d32600471f388a137bbff3eb07993c04").into(),
unsigned: UnsignedTransaction {
nonce: 10.into(),
gas_price: 19000000000u64.into(),
gas: 93674.into(),
to: Some(hex!("d1310c1e038bc12865d3d3997275b3e4737c6302").into()),
value: 815217380000000000_u64.into(),
payload: Default::default(),
}
}),
);
// Kovan value transfer transaction
// https://kovan.etherscan.io/tx/0x3b4b7bd41c1178045ccb4753aa84c1ef9864b4d712fa308b228917cd837915da
// https://kovan.etherscan.io/getRawTx?tx=0x3b4b7bd41c1178045ccb4753aa84c1ef9864b4d712fa308b228917cd837915da
let raw_tx = hex!("f86a822816808252089470c1ccde719d6f477084f07e4137ab0e55f8369f8930cf46e92063afd8008078a00e4d1f4d8aa992bda3c105ff3d6e9b9acbfd99facea00985e2131029290adbdca028ea29a46a4b66ec65b454f0706228e3768cb0ecf755f67c50ddd472f11d5994");
assert_eq!(
transaction_decode_rlp(&raw_tx),
Ok(Transaction {
sender: hex!("faadface3fbd81ce37b0e19c0b65ff4234148132").into(),
unsigned: UnsignedTransaction {
nonce: 10262.into(),
gas_price: 0.into(),
gas: 21000.into(),
to: Some(hex!("70c1ccde719d6f477084f07e4137ab0e55f8369f").into()),
value: 900379597077600000000_u128.into(),
payload: Default::default(),
},
}),
);
}
#[test]
fn payload_transaction_decode_works() {
// contract call transaction
// https://etherscan.io/tx/0xdc2b996b4d1d6922bf6dba063bfd70913279cb6170967c9bb80252aeb061cf65
// https://etherscan.io/getRawTx?tx=0xdc2b996b4d1d6922bf6dba063bfd70913279cb6170967c9bb80252aeb061cf65
let raw_tx = hex!("f8aa76850430e234008301500094dac17f958d2ee523a2206206994597c13d831ec780b844a9059cbb000000000000000000000000e08f35f66867a454835b25118f1e490e7f9e9a7400000000000000000000000000000000000000000000000000000000004c4b4025a0964e023999621dc3d4d831c43c71f7555beb6d1192dee81a3674b3f57e310f21a00f229edd86f841d1ee4dc48cc16667e2283817b1d39bae16ced10cd206ae4fd4");
assert_eq!(
transaction_decode_rlp(&raw_tx),
Ok(Transaction {
sender: hex!("2b9a4d37bdeecdf994c4c9ad7f3cf8dc632f7d70").into(),
unsigned: UnsignedTransaction {
nonce: 118.into(),
gas_price: 18000000000u64.into(),
gas: 86016.into(),
to: Some(hex!("dac17f958d2ee523a2206206994597c13d831ec7").into()),
value: 0.into(),
payload: hex!("a9059cbb000000000000000000000000e08f35f66867a454835b25118f1e490e7f9e9a7400000000000000000000000000000000000000000000000000000000004c4b40").to_vec(),
},
}),
);
// Kovan contract call transaction
// https://kovan.etherscan.io/tx/0x2904b4451d23665492239016b78da052d40d55fdebc7304b38e53cf6a37322cf
// https://kovan.etherscan.io/getRawTx?tx=0x2904b4451d23665492239016b78da052d40d55fdebc7304b38e53cf6a37322cf
let raw_tx = hex!("f8ac8302200b843b9aca00830271009484dd11eb2a29615303d18149c0dbfa24167f896680b844a9059cbb00000000000000000000000001503dfc5ad81bf630d83697e98601871bb211b600000000000000000000000000000000000000000000000000000000000027101ba0ce126d2cca81f5e245f292ff84a0d915c0a4ac52af5c51219db1e5d36aa8da35a0045298b79dac631907403888f9b04c2ab5509fe0cc31785276d30a40b915fcf9");
assert_eq!(
transaction_decode_rlp(&raw_tx),
Ok(Transaction {
sender: hex!("617da121abf03d4c1af572f5a4e313e26bef7bdc").into(),
unsigned: UnsignedTransaction {
nonce: 139275.into(),
gas_price: 1000000000.into(),
gas: 160000.into(),
to: Some(hex!("84dd11eb2a29615303d18149c0dbfa24167f8966").into()),
value: 0.into(),
payload: hex!("a9059cbb00000000000000000000000001503dfc5ad81bf630d83697e98601871bb211b60000000000000000000000000000000000000000000000000000000000002710").to_vec(),
},
}),
);
}
#[test]
fn is_successful_raw_receipt_works() {
assert!(Receipt::is_successful_raw_receipt(&[]).is_err());
assert_eq!(
Receipt::is_successful_raw_receipt(
&Receipt {
outcome: TransactionOutcome::Unknown,
gas_used: Default::default(),
log_bloom: Default::default(),
logs: Vec::new(),
}
.rlp()
),
Ok(false),
);
assert_eq!(
Receipt::is_successful_raw_receipt(
&Receipt {
outcome: TransactionOutcome::StateRoot(Default::default()),
gas_used: Default::default(),
log_bloom: Default::default(),
logs: Vec::new(),
}
.rlp()
),
Ok(false),
);
assert_eq!(
Receipt::is_successful_raw_receipt(
&Receipt {
outcome: TransactionOutcome::StatusCode(0),
gas_used: Default::default(),
log_bloom: Default::default(),
logs: Vec::new(),
}
.rlp()
),
Ok(false),
);
assert_eq!(
Receipt::is_successful_raw_receipt(
&Receipt {
outcome: TransactionOutcome::StatusCode(1),
gas_used: Default::default(),
log_bloom: Default::default(),
logs: Vec::new(),
}
.rlp()
),
Ok(true),
);
}
#[test]
fn is_successful_raw_receipt_with_empty_data() {
let mut stream = RlpStream::new();
stream.begin_list(4);
stream.append_empty_data();
stream.append(&1u64);
stream.append(&2u64);
stream.append(&3u64);
assert_eq!(Receipt::is_successful_raw_receipt(&stream.out()), Ok(false),);
}
}
@@ -1,143 +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/>.
//
//! Helpers related to signatures.
//!
//! Used for testing and benchmarking.
// reexport to avoid direct secp256k1 deps by other crates
pub use secp256k1::SecretKey;
use crate::{
public_to_address, rlp_encode, step_validator, Address, AuraHeader, RawTransaction, UnsignedTransaction, H256,
H520, U256,
};
use secp256k1::{Message, PublicKey};
/// Utilities for signing headers.
pub trait SignHeader {
/// Signs header by given author.
fn sign_by(self, author: &SecretKey) -> AuraHeader;
/// Signs header by given authors set.
fn sign_by_set(self, authors: &[SecretKey]) -> AuraHeader;
}
/// Utilities for signing transactions.
pub trait SignTransaction {
/// Sign transaction by given author.
fn sign_by(self, author: &SecretKey, chain_id: Option<u64>) -> RawTransaction;
}
impl SignHeader for AuraHeader {
fn sign_by(mut self, author: &SecretKey) -> Self {
self.author = secret_to_address(author);
let message = self.seal_hash(false).unwrap();
let signature = sign(author, message);
self.seal[1] = rlp_encode(&signature).to_vec();
self
}
fn sign_by_set(self, authors: &[SecretKey]) -> Self {
let step = self.step().unwrap();
let author = step_validator(authors, step);
self.sign_by(author)
}
}
impl SignTransaction for UnsignedTransaction {
fn sign_by(self, author: &SecretKey, chain_id: Option<u64>) -> RawTransaction {
let message = self.message(chain_id);
let signature = sign(author, message);
let signature_r = U256::from_big_endian(&signature.as_fixed_bytes()[..32][..]);
let signature_s = U256::from_big_endian(&signature.as_fixed_bytes()[32..64][..]);
let signature_v = signature.as_fixed_bytes()[64] as u64;
let signature_v = signature_v + if let Some(n) = chain_id { 35 + n * 2 } else { 27 };
let mut stream = rlp::RlpStream::new_list(9);
self.rlp_to(None, &mut stream);
stream.append(&signature_v);
stream.append(&signature_r);
stream.append(&signature_s);
stream.out().to_vec()
}
}
/// Return author's signature over given message.
pub fn sign(author: &SecretKey, message: H256) -> H520 {
let (signature, recovery_id) = secp256k1::sign(&Message::parse(message.as_fixed_bytes()), author);
let mut raw_signature = [0u8; 65];
raw_signature[..64].copy_from_slice(&signature.serialize());
raw_signature[64] = recovery_id.serialize();
raw_signature.into()
}
/// Returns address corresponding to given secret key.
pub fn secret_to_address(secret: &SecretKey) -> Address {
let public = PublicKey::from_secret_key(secret);
let mut raw_public = [0u8; 64];
raw_public.copy_from_slice(&public.serialize()[1..]);
public_to_address(&raw_public)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{transaction_decode_rlp, Transaction};
#[test]
fn transaction_signed_properly() {
// case1: with chain_id replay protection + to
let signer = SecretKey::parse(&[1u8; 32]).unwrap();
let signer_address = secret_to_address(&signer);
let unsigned = UnsignedTransaction {
nonce: 100.into(),
gas_price: 200.into(),
gas: 300.into(),
to: Some([42u8; 20].into()),
value: 400.into(),
payload: vec![1, 2, 3],
};
let raw_tx = unsigned.clone().sign_by(&signer, Some(42));
assert_eq!(
transaction_decode_rlp(&raw_tx),
Ok(Transaction {
sender: signer_address,
unsigned,
}),
);
// case2: without chain_id replay protection + contract creation
let unsigned = UnsignedTransaction {
nonce: 100.into(),
gas_price: 200.into(),
gas: 300.into(),
to: None,
value: 400.into(),
payload: vec![1, 2, 3],
};
let raw_tx = unsigned.clone().sign_by(&signer, None);
assert_eq!(
transaction_decode_rlp(&raw_tx),
Ok(Transaction {
sender: signer_address,
unsigned,
}),
);
}
}
@@ -1,37 +0,0 @@
[package]
name = "bp-header-chain"
description = "A common interface for describing what a bridge pallet should be able to do."
version = "0.1.0"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2018"
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
[dependencies]
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false }
finality-grandpa = { version = "0.14.1", default-features = false }
serde = { version = "1.0", optional = true }
# Substrate Dependencies
frame-support = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-core = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-finality-grandpa = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-std = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
[dev-dependencies]
assert_matches = "1.5"
bp-test-utils = { path = "../test-utils" }
[features]
default = ["std"]
std = [
"codec/std",
"finality-grandpa/std",
"serde/std",
"frame-support/std",
"sp-core/std",
"sp-finality-grandpa/std",
"sp-runtime/std",
"sp-std/std",
]
@@ -1,219 +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/>.
//! Pallet for checking GRANDPA Finality Proofs.
//!
//! Adapted copy of substrate/client/finality-grandpa/src/justification.rs. If origin
//! will ever be moved to the sp_finality_grandpa, we should reuse that implementation.
use codec::{Decode, Encode};
use finality_grandpa::voter_set::VoterSet;
use frame_support::RuntimeDebug;
use sp_finality_grandpa::{AuthorityId, AuthoritySignature, SetId};
use sp_runtime::traits::Header as HeaderT;
use sp_std::collections::{btree_map::BTreeMap, btree_set::BTreeSet};
use sp_std::prelude::*;
/// A GRANDPA Justification is a proof that a given header was finalized
/// at a certain height and with a certain set of authorities.
///
/// This particular proof is used to prove that headers on a bridged chain
/// (so not our chain) have been finalized correctly.
#[derive(Encode, Decode, RuntimeDebug, Clone, PartialEq, Eq)]
pub struct GrandpaJustification<Header: HeaderT> {
/// The round (voting period) this justification is valid for.
pub round: u64,
/// The set of votes for the chain which is to be finalized.
pub commit: finality_grandpa::Commit<Header::Hash, Header::Number, AuthoritySignature, AuthorityId>,
/// A proof that the chain of blocks in the commit are related to each other.
pub votes_ancestries: Vec<Header>,
}
impl<H: HeaderT> crate::FinalityProof<H::Number> for GrandpaJustification<H> {
fn target_header_number(&self) -> H::Number {
self.commit.target_number
}
}
/// Justification verification error.
#[derive(RuntimeDebug, PartialEq)]
pub enum Error {
/// Failed to decode justification.
JustificationDecode,
/// Justification is finalizing unexpected header.
InvalidJustificationTarget,
/// The authority has provided an invalid signature.
InvalidAuthoritySignature,
/// The justification contains precommit for header that is not a descendant of the commit header.
PrecommitIsNotCommitDescendant,
/// The cumulative weight of all votes in the justification is not enough to justify commit
/// header finalization.
TooLowCumulativeWeight,
/// The justification contains extra (unused) headers in its `votes_ancestries` field.
ExtraHeadersInVotesAncestries,
}
/// Decode justification target.
pub fn decode_justification_target<Header: HeaderT>(
raw_justification: &[u8],
) -> Result<(Header::Hash, Header::Number), Error> {
GrandpaJustification::<Header>::decode(&mut &*raw_justification)
.map(|justification| (justification.commit.target_hash, justification.commit.target_number))
.map_err(|_| Error::JustificationDecode)
}
/// Verify that justification, that is generated by given authority set, finalizes given header.
pub fn verify_justification<Header: HeaderT>(
finalized_target: (Header::Hash, Header::Number),
authorities_set_id: SetId,
authorities_set: &VoterSet<AuthorityId>,
justification: &GrandpaJustification<Header>,
) -> Result<(), Error>
where
Header::Number: finality_grandpa::BlockNumberOps,
{
// ensure that it is justification for the expected header
if (justification.commit.target_hash, justification.commit.target_number) != finalized_target {
return Err(Error::InvalidJustificationTarget);
}
let mut chain = AncestryChain::new(&justification.votes_ancestries);
let mut signature_buffer = Vec::new();
let mut votes = BTreeSet::new();
let mut cumulative_weight = 0u64;
for signed in &justification.commit.precommits {
// authority must be in the set
let authority_info = match authorities_set.get(&signed.id) {
Some(authority_info) => authority_info,
None => {
// just ignore precommit from unknown authority as `finality_grandpa::import_precommit` does
continue;
}
};
// check if authority has already voted in the same round.
//
// there's a lot of code in `validate_commit` and `import_precommit` functions inside
// `finality-grandpa` crate (mostly related to reporing equivocations). But the only thing that we
// care about is that only first vote from the authority is accepted
if !votes.insert(signed.id.clone()) {
continue;
}
// everything below this line can't just `continue`, because state is already altered
// all precommits must be for block higher than the target
if signed.precommit.target_number < justification.commit.target_number {
return Err(Error::PrecommitIsNotCommitDescendant);
}
// all precommits must be for target block descendents
chain = chain.ensure_descendant(&justification.commit.target_hash, &signed.precommit.target_hash)?;
// since we know now that the precommit target is the descendant of the justification target,
// we may increase 'weight' of the justification target
//
// there's a lot of code in the `VoteGraph::insert` method inside `finality-grandpa` crate,
// but in the end it is only used to find GHOST, which we don't care about. The only thing
// that we care about is that the justification target has enough weight
cumulative_weight = cumulative_weight.checked_add(authority_info.weight().0.into()).expect(
"sum of weights of ALL authorities is expected not to overflow - this is guaranteed by\
existence of VoterSet;\
the order of loop conditions guarantees that we can account vote from same authority\
multiple times;\
thus we'll never overflow the u64::MAX;\
qed",
);
// verify authority signature
if !sp_finality_grandpa::check_message_signature_with_buffer(
&finality_grandpa::Message::Precommit(signed.precommit.clone()),
&signed.id,
&signed.signature,
justification.round,
authorities_set_id,
&mut signature_buffer,
) {
return Err(Error::InvalidAuthoritySignature);
}
}
// check that there are no extra headers in the justification
if !chain.unvisited.is_empty() {
return Err(Error::ExtraHeadersInVotesAncestries);
}
// check that the cumulative weight of validators voted for the justification target (or one
// of its descendents) is larger than required threshold.
let threshold = authorities_set.threshold().0.into();
if cumulative_weight >= threshold {
Ok(())
} else {
Err(Error::TooLowCumulativeWeight)
}
}
/// Votes ancestries with useful methods.
#[derive(RuntimeDebug)]
pub struct AncestryChain<Header: HeaderT> {
/// Header hash => parent header hash mapping.
pub parents: BTreeMap<Header::Hash, Header::Hash>,
/// Hashes of headers that weren't visited by `is_ancestor` method.
pub unvisited: BTreeSet<Header::Hash>,
}
impl<Header: HeaderT> AncestryChain<Header> {
/// Create new ancestry chain.
pub fn new(ancestry: &[Header]) -> AncestryChain<Header> {
let mut parents = BTreeMap::new();
let mut unvisited = BTreeSet::new();
for ancestor in ancestry {
let hash = ancestor.hash();
let parent_hash = *ancestor.parent_hash();
parents.insert(hash, parent_hash);
unvisited.insert(hash);
}
AncestryChain { parents, unvisited }
}
/// Returns `Err(_)` if `precommit_target` is a descendant of the `commit_target` block and `Ok(_)` otherwise.
pub fn ensure_descendant(
mut self,
commit_target: &Header::Hash,
precommit_target: &Header::Hash,
) -> Result<Self, Error> {
let mut current_hash = *precommit_target;
loop {
if current_hash == *commit_target {
break;
}
let is_visited_before = !self.unvisited.remove(&current_hash);
current_hash = match self.parents.get(&current_hash) {
Some(parent_hash) => {
if is_visited_before {
// `Some(parent_hash)` means that the `current_hash` is in the `parents` container
// `is_visited_before` means that it has been visited before in some of previous calls
// => since we assume that previous call has finished with `true`, this also will
// be finished with `true`
return Ok(self);
}
*parent_hash
}
None => return Err(Error::PrecommitIsNotCommitDescendant),
};
}
Ok(self)
}
}
@@ -1,133 +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/>.
//! Defines traits which represent a common interface for Substrate pallets which want to
//! incorporate bridge functionality.
#![cfg_attr(not(feature = "std"), no_std)]
use codec::{Codec, Decode, Encode, EncodeLike};
use core::clone::Clone;
use core::cmp::Eq;
use core::default::Default;
use core::fmt::Debug;
#[cfg(feature = "std")]
use serde::{Deserialize, Serialize};
use sp_finality_grandpa::{AuthorityList, ConsensusLog, SetId, GRANDPA_ENGINE_ID};
use sp_runtime::RuntimeDebug;
use sp_runtime::{generic::OpaqueDigestItemId, traits::Header as HeaderT};
pub mod justification;
/// A type that can be used as a parameter in a dispatchable function.
///
/// When using `decl_module` all arguments for call functions must implement this trait.
pub trait Parameter: Codec + EncodeLike + Clone + Eq + Debug {}
impl<T> Parameter for T where T: Codec + EncodeLike + Clone + Eq + Debug {}
/// A GRANDPA Authority List and ID.
#[derive(Default, Encode, Decode, RuntimeDebug, PartialEq, Clone)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub struct AuthoritySet {
/// List of GRANDPA authorities for the current round.
pub authorities: AuthorityList,
/// Monotonic identifier of the current GRANDPA authority set.
pub set_id: SetId,
}
impl AuthoritySet {
/// Create a new GRANDPA Authority Set.
pub fn new(authorities: AuthorityList, set_id: SetId) -> Self {
Self { authorities, set_id }
}
}
/// Data required for initializing the bridge pallet.
///
/// The bridge needs to know where to start its sync from, and this provides that initial context.
#[derive(Default, Encode, Decode, RuntimeDebug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub struct InitializationData<H: HeaderT> {
/// The header from which we should start syncing.
pub header: H,
/// The initial authorities of the pallet.
pub authority_list: AuthorityList,
/// The ID of the initial authority set.
pub set_id: SetId,
/// Should the pallet block transaction immediately after initialization.
pub is_halted: bool,
}
/// base trait for verifying transaction inclusion proofs.
pub trait InclusionProofVerifier {
/// Transaction type.
type Transaction: Parameter;
/// Transaction inclusion proof type.
type TransactionInclusionProof: Parameter;
/// Verify that transaction is a part of given block.
///
/// Returns Some(transaction) if proof is valid and None otherwise.
fn verify_transaction_inclusion_proof(proof: &Self::TransactionInclusionProof) -> Option<Self::Transaction>;
}
/// A trait for pallets which want to keep track of finalized headers from a bridged chain.
pub trait HeaderChain<H, E> {
/// Get the best finalized header known to the header chain.
fn best_finalized() -> H;
/// Get the best authority set known to the header chain.
fn authority_set() -> AuthoritySet;
/// Write a header finalized by GRANDPA to the underlying pallet storage.
fn append_header(header: H) -> Result<(), E>;
}
impl<H: Default, E> HeaderChain<H, E> for () {
fn best_finalized() -> H {
H::default()
}
fn authority_set() -> AuthoritySet {
AuthoritySet::default()
}
fn append_header(_header: H) -> Result<(), E> {
Ok(())
}
}
/// Abstract finality proof that is justifying block finality.
pub trait FinalityProof<Number>: Clone + Send + Sync + Debug {
/// Return number of header that this proof is generated for.
fn target_header_number(&self) -> Number;
}
/// Find header digest that schedules next GRANDPA authorities set.
pub fn find_grandpa_authorities_scheduled_change<H: HeaderT>(
header: &H,
) -> Option<sp_finality_grandpa::ScheduledChange<H::Number>> {
let id = OpaqueDigestItemId::Consensus(&GRANDPA_ENGINE_ID);
let filter_log = |log: ConsensusLog<H::Number>| match log {
ConsensusLog::ScheduledChange(change) => Some(change),
_ => None,
};
// find the first consensus digest with the right ID which converts to
// the right kind of consensus log.
header.digest().convert_first(|l| l.try_to(id).and_then(filter_log))
}
@@ -1,317 +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/>.
//! Tests inside this module are made to ensure that our custom justification verification
//! implementation works exactly as `fn finality_grandpa::validate_commit`.
//!
//! Some of tests in this module may partially duplicate tests from `justification.rs`,
//! but their purpose is different.
use assert_matches::assert_matches;
use bp_header_chain::justification::{verify_justification, Error, GrandpaJustification};
use bp_test_utils::{
header_id, make_justification_for_header, signed_precommit, test_header, Account, JustificationGeneratorParams,
ALICE, BOB, CHARLIE, DAVE, EVE, TEST_GRANDPA_SET_ID,
};
use finality_grandpa::voter_set::VoterSet;
use sp_finality_grandpa::{AuthorityId, AuthorityWeight};
use sp_runtime::traits::Header as HeaderT;
type TestHeader = sp_runtime::testing::Header;
type TestHash = <TestHeader as HeaderT>::Hash;
type TestNumber = <TestHeader as HeaderT>::Number;
/// Implementation of `finality_grandpa::Chain` that is used in tests.
struct AncestryChain(bp_header_chain::justification::AncestryChain<TestHeader>);
impl AncestryChain {
fn new(ancestry: &[TestHeader]) -> Self {
Self(bp_header_chain::justification::AncestryChain::new(ancestry))
}
}
impl finality_grandpa::Chain<TestHash, TestNumber> for AncestryChain {
fn ancestry(&self, base: TestHash, block: TestHash) -> Result<Vec<TestHash>, finality_grandpa::Error> {
let mut route = Vec::new();
let mut current_hash = block;
loop {
if current_hash == base {
break;
}
match self.0.parents.get(&current_hash).cloned() {
Some(parent_hash) => {
current_hash = parent_hash;
route.push(current_hash);
}
_ => return Err(finality_grandpa::Error::NotDescendent),
}
}
route.pop(); // remove the base
Ok(route)
}
}
/// Get a full set of accounts.
fn full_accounts_set() -> Vec<(Account, AuthorityWeight)> {
vec![(ALICE, 1), (BOB, 1), (CHARLIE, 1), (DAVE, 1), (EVE, 1)]
}
/// Get a full set of GRANDPA authorities.
fn full_voter_set() -> VoterSet<AuthorityId> {
VoterSet::new(full_accounts_set().iter().map(|(id, w)| (AuthorityId::from(*id), *w))).unwrap()
}
/// Get a minimal set of accounts.
fn minimal_accounts_set() -> Vec<(Account, AuthorityWeight)> {
// there are 5 accounts in the full set => we need 2/3 + 1 accounts, which results in 4 accounts
vec![(ALICE, 1), (BOB, 1), (CHARLIE, 1), (DAVE, 1)]
}
/// Get a minimal subset of GRANDPA authorities that have enough cumulative vote weight to justify a header finality.
pub fn minimal_voter_set() -> VoterSet<AuthorityId> {
VoterSet::new(
minimal_accounts_set()
.iter()
.map(|(id, w)| (AuthorityId::from(*id), *w)),
)
.unwrap()
}
/// Make a valid GRANDPA justification with sensible defaults.
pub fn make_default_justification(header: &TestHeader) -> GrandpaJustification<TestHeader> {
make_justification_for_header(JustificationGeneratorParams {
header: header.clone(),
authorities: minimal_accounts_set(),
..Default::default()
})
}
// the `finality_grandpa::validate_commit` function has two ways to report an unsuccessful
// commit validation:
//
// 1) to return `Err()` (which only may happen if `finality_grandpa::Chain` implementation
// returns an error);
// 2) to return `Ok(validation_result) if validation_result.ghost().is_none()`.
//
// Our implementation would just return error in both cases.
#[test]
fn same_result_when_precommit_target_has_lower_number_than_commit_target() {
let mut justification = make_default_justification(&test_header(1));
// the number of header in precommit (0) is lower than number of header in commit (1)
justification.commit.precommits[0].precommit.target_number = 0;
// our implementation returns an error
assert_eq!(
verify_justification::<TestHeader>(
header_id::<TestHeader>(1),
TEST_GRANDPA_SET_ID,
&full_voter_set(),
&justification,
),
Err(Error::PrecommitIsNotCommitDescendant),
);
// original implementation returns empty GHOST
assert_matches!(
finality_grandpa::validate_commit(
&justification.commit,
&full_voter_set(),
&AncestryChain::new(&justification.votes_ancestries),
)
.map(|result| result.ghost().cloned()),
Ok(None)
);
}
#[test]
fn same_result_when_precommit_target_is_not_descendant_of_commit_target() {
let not_descendant = test_header::<TestHeader>(10);
let mut justification = make_default_justification(&test_header(1));
// the route from header of commit (1) to header of precommit (10) is missing from
// the votes ancestries
justification.commit.precommits[0].precommit.target_number = *not_descendant.number();
justification.commit.precommits[0].precommit.target_hash = not_descendant.hash();
justification.votes_ancestries.push(not_descendant);
// our implementation returns an error
assert_eq!(
verify_justification::<TestHeader>(
header_id::<TestHeader>(1),
TEST_GRANDPA_SET_ID,
&full_voter_set(),
&justification,
),
Err(Error::PrecommitIsNotCommitDescendant),
);
// original implementation returns empty GHOST
assert_matches!(
finality_grandpa::validate_commit(
&justification.commit,
&full_voter_set(),
&AncestryChain::new(&justification.votes_ancestries),
)
.map(|result| result.ghost().cloned()),
Ok(None)
);
}
#[test]
fn same_result_when_justification_contains_duplicate_vote() {
let mut justification = make_default_justification(&test_header(1));
// the justification may contain exactly the same vote (i.e. same precommit and same signature)
// multiple times && it isn't treated as an error by original implementation
justification
.commit
.precommits
.push(justification.commit.precommits[0].clone());
justification
.commit
.precommits
.push(justification.commit.precommits[0].clone());
// our implementation succeeds
assert_eq!(
verify_justification::<TestHeader>(
header_id::<TestHeader>(1),
TEST_GRANDPA_SET_ID,
&full_voter_set(),
&justification,
),
Ok(()),
);
// original implementation returns non-empty GHOST
assert_matches!(
finality_grandpa::validate_commit(
&justification.commit,
&full_voter_set(),
&AncestryChain::new(&justification.votes_ancestries),
)
.map(|result| result.ghost().cloned()),
Ok(Some(_))
);
}
#[test]
fn same_result_when_authority_equivocates_once_in_a_round() {
let mut justification = make_default_justification(&test_header(1));
// the justification original implementation allows authority to submit two different
// votes in a single round, of which only first is 'accepted'
justification.commit.precommits.push(signed_precommit::<TestHeader>(
&ALICE,
header_id::<TestHeader>(1),
justification.round,
TEST_GRANDPA_SET_ID,
));
// our implementation succeeds
assert_eq!(
verify_justification::<TestHeader>(
header_id::<TestHeader>(1),
TEST_GRANDPA_SET_ID,
&full_voter_set(),
&justification,
),
Ok(()),
);
// original implementation returns non-empty GHOST
assert_matches!(
finality_grandpa::validate_commit(
&justification.commit,
&full_voter_set(),
&AncestryChain::new(&justification.votes_ancestries),
)
.map(|result| result.ghost().cloned()),
Ok(Some(_))
);
}
#[test]
fn same_result_when_authority_equivocates_twice_in_a_round() {
let mut justification = make_default_justification(&test_header(1));
// there's some code in the original implementation that should return an error when
// same authority submits more than two different votes in a single round:
// https://github.com/paritytech/finality-grandpa/blob/6aeea2d1159d0f418f0b86e70739f2130629ca09/src/lib.rs#L473
// but there's also a code that prevents this from happening:
// https://github.com/paritytech/finality-grandpa/blob/6aeea2d1159d0f418f0b86e70739f2130629ca09/src/round.rs#L287
// => so now we are also just ignoring all votes from the same authority, except the first one
justification.commit.precommits.push(signed_precommit::<TestHeader>(
&ALICE,
header_id::<TestHeader>(1),
justification.round,
TEST_GRANDPA_SET_ID,
));
justification.commit.precommits.push(signed_precommit::<TestHeader>(
&ALICE,
header_id::<TestHeader>(1),
justification.round,
TEST_GRANDPA_SET_ID,
));
// our implementation succeeds
assert_eq!(
verify_justification::<TestHeader>(
header_id::<TestHeader>(1),
TEST_GRANDPA_SET_ID,
&full_voter_set(),
&justification,
),
Ok(()),
);
// original implementation returns non-empty GHOST
assert_matches!(
finality_grandpa::validate_commit(
&justification.commit,
&full_voter_set(),
&AncestryChain::new(&justification.votes_ancestries),
)
.map(|result| result.ghost().cloned()),
Ok(Some(_))
);
}
#[test]
fn same_result_when_there_are_not_enough_cumulative_weight_to_finalize_commit_target() {
// just remove one authority from the minimal set and we shall not reach the threshold
let mut authorities_set = minimal_accounts_set();
authorities_set.pop();
let justification = make_justification_for_header(JustificationGeneratorParams {
header: test_header(1),
authorities: authorities_set,
..Default::default()
});
// our implementation returns an error
assert_eq!(
verify_justification::<TestHeader>(
header_id::<TestHeader>(1),
TEST_GRANDPA_SET_ID,
&full_voter_set(),
&justification,
),
Err(Error::TooLowCumulativeWeight),
);
// original implementation returns empty GHOST
assert_matches!(
finality_grandpa::validate_commit(
&justification.commit,
&full_voter_set(),
&AncestryChain::new(&justification.votes_ancestries),
)
.map(|result| result.ghost().cloned()),
Ok(None)
);
}
@@ -1,191 +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/>.
//! Tests for Grandpa Justification code.
use bp_header_chain::justification::{verify_justification, Error};
use bp_test_utils::*;
type TestHeader = sp_runtime::testing::Header;
#[test]
fn valid_justification_accepted() {
let authorities = vec![(ALICE, 1), (BOB, 1), (CHARLIE, 1), (DAVE, 1)];
let params = JustificationGeneratorParams {
header: test_header(1),
round: TEST_GRANDPA_ROUND,
set_id: TEST_GRANDPA_SET_ID,
authorities: authorities.clone(),
ancestors: 7,
forks: 3,
};
let justification = make_justification_for_header::<TestHeader>(params.clone());
assert_eq!(
verify_justification::<TestHeader>(
header_id::<TestHeader>(1),
TEST_GRANDPA_SET_ID,
&voter_set(),
&justification,
),
Ok(()),
);
assert_eq!(justification.commit.precommits.len(), authorities.len());
assert_eq!(justification.votes_ancestries.len(), params.ancestors as usize);
}
#[test]
fn valid_justification_accepted_with_single_fork() {
let params = JustificationGeneratorParams {
header: test_header(1),
round: TEST_GRANDPA_ROUND,
set_id: TEST_GRANDPA_SET_ID,
authorities: vec![(ALICE, 1), (BOB, 1), (CHARLIE, 1), (DAVE, 1), (EVE, 1)],
ancestors: 5,
forks: 1,
};
assert_eq!(
verify_justification::<TestHeader>(
header_id::<TestHeader>(1),
TEST_GRANDPA_SET_ID,
&voter_set(),
&make_justification_for_header::<TestHeader>(params)
),
Ok(()),
);
}
#[test]
fn valid_justification_accepted_with_arbitrary_number_of_authorities() {
use finality_grandpa::voter_set::VoterSet;
use sp_finality_grandpa::AuthorityId;
let n = 15;
let authorities = accounts(n).iter().map(|k| (*k, 1)).collect::<Vec<_>>();
let params = JustificationGeneratorParams {
header: test_header(1),
round: TEST_GRANDPA_ROUND,
set_id: TEST_GRANDPA_SET_ID,
authorities: authorities.clone(),
ancestors: n.into(),
forks: n.into(),
};
let authorities = authorities
.iter()
.map(|(id, w)| (AuthorityId::from(*id), *w))
.collect::<Vec<(AuthorityId, _)>>();
let voter_set = VoterSet::new(authorities).unwrap();
assert_eq!(
verify_justification::<TestHeader>(
header_id::<TestHeader>(1),
TEST_GRANDPA_SET_ID,
&voter_set,
&make_justification_for_header::<TestHeader>(params)
),
Ok(()),
);
}
#[test]
fn justification_with_invalid_target_rejected() {
assert_eq!(
verify_justification::<TestHeader>(
header_id::<TestHeader>(2),
TEST_GRANDPA_SET_ID,
&voter_set(),
&make_default_justification::<TestHeader>(&test_header(1)),
),
Err(Error::InvalidJustificationTarget),
);
}
#[test]
fn justification_with_invalid_commit_rejected() {
let mut justification = make_default_justification::<TestHeader>(&test_header(1));
justification.commit.precommits.clear();
assert_eq!(
verify_justification::<TestHeader>(
header_id::<TestHeader>(1),
TEST_GRANDPA_SET_ID,
&voter_set(),
&justification,
),
Err(Error::ExtraHeadersInVotesAncestries),
);
}
#[test]
fn justification_with_invalid_authority_signature_rejected() {
let mut justification = make_default_justification::<TestHeader>(&test_header(1));
justification.commit.precommits[0].signature = Default::default();
assert_eq!(
verify_justification::<TestHeader>(
header_id::<TestHeader>(1),
TEST_GRANDPA_SET_ID,
&voter_set(),
&justification,
),
Err(Error::InvalidAuthoritySignature),
);
}
#[test]
fn justification_with_invalid_precommit_ancestry() {
let mut justification = make_default_justification::<TestHeader>(&test_header(1));
justification.votes_ancestries.push(test_header(10));
assert_eq!(
verify_justification::<TestHeader>(
header_id::<TestHeader>(1),
TEST_GRANDPA_SET_ID,
&voter_set(),
&justification,
),
Err(Error::ExtraHeadersInVotesAncestries),
);
}
#[test]
fn justification_is_invalid_if_we_dont_meet_threshold() {
// Need at least three authorities to sign off or else the voter set threshold can't be reached
let authorities = vec![(ALICE, 1), (BOB, 1)];
let params = JustificationGeneratorParams {
header: test_header(1),
round: TEST_GRANDPA_ROUND,
set_id: TEST_GRANDPA_SET_ID,
authorities: authorities.clone(),
ancestors: 2 * authorities.len() as u32,
forks: 2,
};
assert_eq!(
verify_justification::<TestHeader>(
header_id::<TestHeader>(1),
TEST_GRANDPA_SET_ID,
&voter_set(),
&make_justification_for_header::<TestHeader>(params)
),
Err(Error::TooLowCumulativeWeight),
);
}
@@ -1,25 +0,0 @@
[package]
name = "bp-message-dispatch"
description = "Primitives of bridge messages dispatch modules."
version = "0.1.0"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2018"
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
[dependencies]
bp-runtime = { path = "../runtime", default-features = false }
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false }
# Substrate Dependencies
frame-support = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-std = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
[features]
default = ["std"]
std = [
"bp-runtime/std",
"codec/std",
"frame-support/std",
"sp-std/std",
]
@@ -1,136 +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/>.
//! A common interface for all Bridge Message Dispatch modules.
#![cfg_attr(not(feature = "std"), no_std)]
#![warn(missing_docs)]
use bp_runtime::{
messages::{DispatchFeePayment, MessageDispatchResult},
ChainId, Size,
};
use codec::{Decode, Encode};
use frame_support::RuntimeDebug;
use sp_std::prelude::*;
/// Message dispatch weight.
pub type Weight = u64;
/// Spec version type.
pub type SpecVersion = u32;
/// A generic trait to dispatch arbitrary messages delivered over the bridge.
pub trait MessageDispatch<AccountId, MessageId> {
/// A type of the message to be dispatched.
type Message: codec::Decode;
/// Estimate dispatch weight.
///
/// This function must: (1) be instant and (2) return correct upper bound
/// of dispatch weight.
fn dispatch_weight(message: &Self::Message) -> Weight;
/// Dispatches the message internally.
///
/// `source_chain` indicates the chain where the message came from.
/// `target_chain` indicates the chain where message dispatch happens.
///
/// `id` is a short unique identifier of the message.
///
/// If message is `Ok`, then it should be dispatched. If it is `Err`, then it's just
/// a sign that some other component has rejected the message even before it has
/// reached `dispatch` method (right now this may only be caused if we fail to decode
/// the whole message).
///
/// Returns unspent dispatch weight.
fn dispatch<P: FnOnce(&AccountId, Weight) -> Result<(), ()>>(
source_chain: ChainId,
target_chain: ChainId,
id: MessageId,
message: Result<Self::Message, ()>,
pay_dispatch_fee: P,
) -> MessageDispatchResult;
}
/// Origin of a Call when it is dispatched on the target chain.
///
/// The source chain can (and should) verify that the message can be dispatched on the target chain
/// with a particular origin given the source chain's origin. This can be done with the
/// `verify_message_origin()` function.
#[derive(RuntimeDebug, Encode, Decode, Clone, PartialEq, Eq)]
pub enum CallOrigin<SourceChainAccountId, TargetChainAccountPublic, TargetChainSignature> {
/// Call is sent by the Root origin on the source chain. On the target chain it is dispatched
/// from a derived account.
///
/// The derived account represents the source Root account on the target chain. This is useful
/// if the target chain needs some way of knowing that a call came from a priviledged origin on
/// the source chain (maybe to allow a configuration change for example).
SourceRoot,
/// Call is sent by `SourceChainAccountId` on the source chain. On the target chain it is
/// dispatched from an account controlled by a private key on the target chain.
///
/// The account can be identified by `TargetChainAccountPublic`. The proof that the
/// `SourceChainAccountId` controls `TargetChainAccountPublic` is the `TargetChainSignature`
/// over `(Call, SourceChainAccountId, TargetChainSpecVersion, SourceChainBridgeId).encode()`.
///
/// NOTE sending messages using this origin (or any other) does not have replay protection!
/// The assumption is that both the source account and the target account is controlled by
/// the same entity, so source-chain replay protection is sufficient.
/// As a consequence, it's extremely important for the target chain user to never produce
/// a signature with their target-private key on something that could be sent over the bridge,
/// i.e. if the target user signs `(<some-source-account-id>, Call::Transfer(X, 5))`
/// The owner of `some-source-account-id` can send that message multiple times, which would
/// result with multiple transfer calls being dispatched on the target chain.
/// So please, NEVER USE YOUR PRIVATE KEY TO SIGN SOMETHING YOU DON'T FULLY UNDERSTAND!
TargetAccount(SourceChainAccountId, TargetChainAccountPublic, TargetChainSignature),
/// Call is sent by the `SourceChainAccountId` on the source chain. On the target chain it is
/// dispatched from a derived account ID.
///
/// The account ID on the target chain is derived from the source account ID. This is useful if
/// you need a way to represent foreign accounts on this chain for call dispatch purposes.
///
/// Note that the derived account does not need to have a private key on the target chain. This
/// origin can therefore represent proxies, pallets, etc. as well as "regular" accounts.
SourceAccount(SourceChainAccountId),
}
/// Message payload type used by dispatch module.
#[derive(RuntimeDebug, Encode, Decode, Clone, PartialEq, Eq)]
pub struct MessagePayload<SourceChainAccountId, TargetChainAccountPublic, TargetChainSignature, Call> {
/// Runtime specification version. We only dispatch messages that have the same
/// runtime version. Otherwise we risk to misinterpret encoded calls.
pub spec_version: SpecVersion,
/// Weight of the call, declared by the message sender. If it is less than actual
/// static weight, the call is not dispatched.
pub weight: Weight,
/// Call origin to be used during dispatch.
pub origin: CallOrigin<SourceChainAccountId, TargetChainAccountPublic, TargetChainSignature>,
/// Where the fee for dispatching message is paid?
pub dispatch_fee_payment: DispatchFeePayment,
/// The call itself.
pub call: Call,
}
impl<SourceChainAccountId, TargetChainAccountPublic, TargetChainSignature> Size
for MessagePayload<SourceChainAccountId, TargetChainAccountPublic, TargetChainSignature, Vec<u8>>
{
fn size_hint(&self) -> u32 {
self.call.len() as _
}
}
@@ -1,34 +0,0 @@
[package]
name = "bp-messages"
description = "Primitives of messages module."
version = "0.1.0"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2018"
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
[dependencies]
bitvec = { version = "0.20", default-features = false, features = ["alloc"] }
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive", "bit-vec"] }
impl-trait-for-tuples = "0.2"
serde = { version = "1.0.101", optional = true, features = ["derive"] }
# Bridge dependencies
bp-runtime = { path = "../runtime", default-features = false }
# Substrate Dependencies
frame-support = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
frame-system = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-std = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
[features]
default = ["std"]
std = [
"bp-runtime/std",
"codec/std",
"frame-support/std",
"frame-system/std",
"serde",
"sp-std/std"
]
@@ -1,390 +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/>.
//! Primitives of messages module.
#![cfg_attr(not(feature = "std"), no_std)]
// RuntimeApi generated functions
#![allow(clippy::too_many_arguments)]
// Generated by `DecodeLimit::decode_with_depth_limit`
#![allow(clippy::unnecessary_mut_passed)]
use bitvec::prelude::*;
use bp_runtime::messages::DispatchFeePayment;
use codec::{Decode, Encode};
use frame_support::RuntimeDebug;
use sp_std::{collections::vec_deque::VecDeque, prelude::*};
pub mod source_chain;
pub mod target_chain;
// Weight is reexported to avoid additional frame-support dependencies in related crates.
pub use frame_support::weights::Weight;
/// Messages pallet operating mode.
#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))]
pub enum OperatingMode {
/// Normal mode, when all operations are allowed.
Normal,
/// The pallet is not accepting outbound messages. Inbound messages and receival proofs
/// are still accepted.
///
/// This mode may be used e.g. when bridged chain expects upgrade. Then to avoid dispatch
/// failures, the pallet owner may stop accepting new messages, while continuing to deliver
/// queued messages to the bridged chain. Once upgrade is completed, the mode may be switched
/// back to `Normal`.
RejectingOutboundMessages,
/// The pallet is halted. All operations (except operating mode change) are prohibited.
Halted,
}
impl Default for OperatingMode {
fn default() -> Self {
OperatingMode::Normal
}
}
/// Messages pallet parameter.
pub trait Parameter: frame_support::Parameter {
/// Save parameter value in the runtime storage.
fn save(&self);
}
impl Parameter for () {
fn save(&self) {}
}
/// Lane identifier.
pub type LaneId = [u8; 4];
/// Message nonce. Valid messages will never have 0 nonce.
pub type MessageNonce = u64;
/// Message id as a tuple.
pub type MessageId = (LaneId, MessageNonce);
/// Opaque message payload. We only decode this payload when it is dispatched.
pub type MessagePayload = Vec<u8>;
/// Message key (unique message identifier) as it is stored in the storage.
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug)]
pub struct MessageKey {
/// ID of the message lane.
pub lane_id: LaneId,
/// Message nonce.
pub nonce: MessageNonce,
}
/// Message data as it is stored in the storage.
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug)]
pub struct MessageData<Fee> {
/// Message payload.
pub payload: MessagePayload,
/// Message delivery and dispatch fee, paid by the submitter.
pub fee: Fee,
}
/// Message as it is stored in the storage.
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug)]
pub struct Message<Fee> {
/// Message key.
pub key: MessageKey,
/// Message data.
pub data: MessageData<Fee>,
}
/// Inbound lane data.
#[derive(Encode, Decode, Clone, RuntimeDebug, PartialEq, Eq)]
pub struct InboundLaneData<RelayerId> {
/// Identifiers of relayers and messages that they have delivered to this lane (ordered by message nonce).
///
/// This serves as a helper storage item, to allow the source chain to easily pay rewards
/// to the relayers who succesfuly delivered messages to the target chain (inbound lane).
///
/// It is guaranteed to have at most N entries, where N is configured at the module level.
/// If there are N entries in this vec, then:
/// 1) all incoming messages are rejected if they're missing corresponding `proof-of(outbound-lane.state)`;
/// 2) all incoming messages are rejected if `proof-of(outbound-lane.state).last_delivered_nonce` is
/// equal to `self.last_confirmed_nonce`.
/// Given what is said above, all nonces in this queue are in range:
/// `(self.last_confirmed_nonce; self.last_delivered_nonce()]`.
///
/// When a relayer sends a single message, both of MessageNonces are the same.
/// When relayer sends messages in a batch, the first arg is the lowest nonce, second arg the highest nonce.
/// Multiple dispatches from the same relayer are allowed.
pub relayers: VecDeque<UnrewardedRelayer<RelayerId>>,
/// Nonce of the last message that
/// a) has been delivered to the target (this) chain and
/// b) the delivery has been confirmed on the source chain
///
/// that the target chain knows of.
///
/// This value is updated indirectly when an `OutboundLane` state of the source
/// chain is received alongside with new messages delivery.
pub last_confirmed_nonce: MessageNonce,
}
impl<RelayerId> Default for InboundLaneData<RelayerId> {
fn default() -> Self {
InboundLaneData {
relayers: VecDeque::new(),
last_confirmed_nonce: 0,
}
}
}
impl<RelayerId> InboundLaneData<RelayerId> {
/// Returns approximate size of the struct, given number of entries in the `relayers` set and
/// size of each entry.
///
/// Returns `None` if size overflows `u32` limits.
pub fn encoded_size_hint(relayer_id_encoded_size: u32, relayers_entries: u32, messages_count: u32) -> Option<u32> {
let message_nonce_size = 8;
let relayers_entry_size = relayer_id_encoded_size.checked_add(2 * message_nonce_size)?;
let relayers_size = relayers_entries.checked_mul(relayers_entry_size)?;
let dispatch_results_per_byte = 8;
let dispatch_result_size = sp_std::cmp::max(relayers_entries, messages_count / dispatch_results_per_byte);
relayers_size
.checked_add(message_nonce_size)
.and_then(|result| result.checked_add(dispatch_result_size))
}
/// Nonce of the last message that has been delivered to this (target) chain.
pub fn last_delivered_nonce(&self) -> MessageNonce {
self.relayers
.back()
.map(|entry| entry.messages.end)
.unwrap_or(self.last_confirmed_nonce)
}
}
/// Message details, returned by runtime APIs.
#[derive(Clone, Encode, Decode, RuntimeDebug, PartialEq, Eq)]
pub struct MessageDetails<OutboundMessageFee> {
/// Nonce assigned to the message.
pub nonce: MessageNonce,
/// Message dispatch weight, declared by the submitter.
pub dispatch_weight: Weight,
/// Size of the encoded message.
pub size: u32,
/// Delivery+dispatch fee paid by the message submitter at the source chain.
pub delivery_and_dispatch_fee: OutboundMessageFee,
/// Where the fee for dispatching message is paid?
pub dispatch_fee_payment: DispatchFeePayment,
}
/// Bit vector of message dispatch results.
pub type DispatchResultsBitVec = BitVec<Msb0, u8>;
/// Unrewarded relayer entry stored in the inbound lane data.
///
/// This struct represents a continuous range of messages that have been delivered by the same relayer
/// and whose confirmations are still pending.
#[derive(Encode, Decode, Clone, RuntimeDebug, PartialEq, Eq)]
pub struct UnrewardedRelayer<RelayerId> {
/// Identifier of the relayer.
pub relayer: RelayerId,
/// Messages range, delivered by this relayer.
pub messages: DeliveredMessages,
}
/// Delivered messages with their dispatch result.
#[derive(Clone, Default, Encode, Decode, RuntimeDebug, PartialEq, Eq)]
pub struct DeliveredMessages {
/// Nonce of the first message that has been delivered (inclusive).
pub begin: MessageNonce,
/// Nonce of the last message that has been delivered (inclusive).
pub end: MessageNonce,
/// Dispatch result (`false`/`true`), returned by the message dispatcher for every
/// message in the `[begin; end]` range. See `dispatch_result` field of the
/// `bp_runtime::messages::MessageDispatchResult` structure for more information.
pub dispatch_results: DispatchResultsBitVec,
}
impl DeliveredMessages {
/// Create new `DeliveredMessages` struct that confirms delivery of single nonce with given dispatch result.
pub fn new(nonce: MessageNonce, dispatch_result: bool) -> Self {
DeliveredMessages {
begin: nonce,
end: nonce,
dispatch_results: bitvec![Msb0, u8; if dispatch_result { 1 } else { 0 }],
}
}
/// Note new dispatched message.
pub fn note_dispatched_message(&mut self, dispatch_result: bool) {
self.end += 1;
self.dispatch_results.push(dispatch_result);
}
/// Returns true if delivered messages contain message with given nonce.
pub fn contains_message(&self, nonce: MessageNonce) -> bool {
(self.begin..=self.end).contains(&nonce)
}
/// Get dispatch result flag by message nonce.
///
/// Dispatch result flag must be interpreted using the knowledge of dispatch mechanism
/// at the target chain. See `dispatch_result` field of the
/// `bp_runtime::messages::MessageDispatchResult` structure for more information.
///
/// Panics if message nonce is not in the `begin..=end` range. Typically you'll first
/// check if message is within the range by calling `contains_message`.
pub fn message_dispatch_result(&self, nonce: MessageNonce) -> bool {
const INVALID_NONCE: &str = "Invalid nonce used to index dispatch_results";
let index = nonce.checked_sub(self.begin).expect(INVALID_NONCE) as usize;
*self.dispatch_results.get(index).expect(INVALID_NONCE)
}
}
/// Gist of `InboundLaneData::relayers` field used by runtime APIs.
#[derive(Clone, Default, Encode, Decode, RuntimeDebug, PartialEq, Eq)]
pub struct UnrewardedRelayersState {
/// Number of entries in the `InboundLaneData::relayers` set.
pub unrewarded_relayer_entries: MessageNonce,
/// Number of messages in the oldest entry of `InboundLaneData::relayers`. This is the
/// minimal number of reward proofs required to push out this entry from the set.
pub messages_in_oldest_entry: MessageNonce,
/// Total number of messages in the relayers vector.
pub total_messages: MessageNonce,
}
/// Outbound lane data.
#[derive(Encode, Decode, Clone, RuntimeDebug, PartialEq, Eq)]
pub struct OutboundLaneData {
/// Nonce of oldest message that we haven't yet pruned. May point to not-yet-generated message if
/// all sent messages are already pruned.
pub oldest_unpruned_nonce: MessageNonce,
/// Nonce of latest message, received by bridged chain.
pub latest_received_nonce: MessageNonce,
/// Nonce of latest message, generated by us.
pub latest_generated_nonce: MessageNonce,
}
impl Default for OutboundLaneData {
fn default() -> Self {
OutboundLaneData {
// it is 1 because we're pruning everything in [oldest_unpruned_nonce; latest_received_nonce]
oldest_unpruned_nonce: 1,
latest_received_nonce: 0,
latest_generated_nonce: 0,
}
}
}
/// Returns total number of messages in the `InboundLaneData::relayers` vector.
///
/// Returns `None` if there are more messages that `MessageNonce` may fit (i.e. `MessageNonce + 1`).
pub fn total_unrewarded_messages<RelayerId>(relayers: &VecDeque<UnrewardedRelayer<RelayerId>>) -> Option<MessageNonce> {
match (relayers.front(), relayers.back()) {
(Some(front), Some(back)) => {
if let Some(difference) = back.messages.end.checked_sub(front.messages.begin) {
difference.checked_add(1)
} else {
Some(0)
}
}
_ => Some(0),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn total_unrewarded_messages_does_not_overflow() {
assert_eq!(
total_unrewarded_messages(
&vec![
UnrewardedRelayer {
relayer: 1,
messages: DeliveredMessages::new(0, true)
},
UnrewardedRelayer {
relayer: 2,
messages: DeliveredMessages::new(MessageNonce::MAX, true)
},
]
.into_iter()
.collect()
),
None,
);
}
#[test]
fn inbound_lane_data_returns_correct_hint() {
let test_cases = vec![
// single relayer, multiple messages
(1, 128u8),
// multiple relayers, single message per relayer
(128u8, 128u8),
// several messages per relayer
(13u8, 128u8),
];
for (relayer_entries, messages_count) in test_cases {
let expected_size = InboundLaneData::<u8>::encoded_size_hint(1, relayer_entries as _, messages_count as _);
let actual_size = InboundLaneData {
relayers: (1u8..=relayer_entries)
.map(|i| {
let mut entry = UnrewardedRelayer {
relayer: i,
messages: DeliveredMessages::new(i as _, true),
};
entry.messages.dispatch_results = bitvec![
Msb0, u8;
1;
(messages_count / relayer_entries) as _
];
entry
})
.collect(),
last_confirmed_nonce: messages_count as _,
}
.encode()
.len();
let difference = (expected_size.unwrap() as f64 - actual_size as f64).abs();
assert!(
difference / (std::cmp::min(actual_size, expected_size.unwrap() as usize) as f64) < 0.1,
"Too large difference between actual ({}) and expected ({:?}) inbound lane data size. Test case: {}+{}",
actual_size,
expected_size,
relayer_entries,
messages_count,
);
}
}
#[test]
fn message_dispatch_result_works() {
let delivered_messages = DeliveredMessages {
begin: 100,
end: 150,
dispatch_results: bitvec![Msb0, u8; 1; 151],
};
assert!(!delivered_messages.contains_message(99));
assert!(delivered_messages.contains_message(100));
assert!(delivered_messages.contains_message(150));
assert!(!delivered_messages.contains_message(151));
assert!(delivered_messages.message_dispatch_result(125));
}
}
@@ -1,201 +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/>.
//! Primitives of messages module, that are used on the source chain.
use crate::{DeliveredMessages, InboundLaneData, LaneId, MessageNonce, OutboundLaneData};
use bp_runtime::Size;
use frame_support::{Parameter, RuntimeDebug};
use sp_std::{collections::btree_map::BTreeMap, fmt::Debug};
/// The sender of the message on the source chain.
pub type Sender<AccountId> = frame_system::RawOrigin<AccountId>;
/// Relayers rewards, grouped by relayer account id.
pub type RelayersRewards<AccountId, Balance> = BTreeMap<AccountId, RelayerRewards<Balance>>;
/// Single relayer rewards.
#[derive(RuntimeDebug, Default)]
pub struct RelayerRewards<Balance> {
/// Total rewards that are to be paid to the relayer.
pub reward: Balance,
/// Total number of messages relayed by this relayer.
pub messages: MessageNonce,
}
/// Target chain API. Used by source chain to verify target chain proofs.
///
/// All implementations of this trait should only work with finalized data that
/// can't change. Wrong implementation may lead to invalid lane states (i.e. lane
/// that's stuck) and/or processing messages without paying fees.
pub trait TargetHeaderChain<Payload, AccountId> {
/// Error type.
type Error: Debug + Into<&'static str>;
/// Proof that messages have been received by target chain.
type MessagesDeliveryProof: Parameter + Size;
/// Verify message payload before we accept it.
///
/// **CAUTION**: this is very important function. Incorrect implementation may lead
/// to stuck lanes and/or relayers loses.
///
/// The proper implementation must ensure that the delivery-transaction with this
/// payload would (at least) be accepted into target chain transaction pool AND
/// eventually will be successfully 'mined'. The most obvious incorrect implementation
/// example would be implementation for BTC chain that accepts payloads larger than
/// 1MB. BTC nodes aren't accepting transactions that are larger than 1MB, so relayer
/// will be unable to craft valid transaction => this (and all subsequent) messages will
/// never be delivered.
fn verify_message(payload: &Payload) -> Result<(), Self::Error>;
/// Verify messages delivery proof and return lane && nonce of the latest recevied message.
fn verify_messages_delivery_proof(
proof: Self::MessagesDeliveryProof,
) -> Result<(LaneId, InboundLaneData<AccountId>), Self::Error>;
}
/// Lane message verifier.
///
/// Runtime developer may implement any additional validation logic over message-lane mechanism.
/// E.g. if lanes should have some security (e.g. you can only accept Lane1 messages from
/// Submitter1, Lane2 messages for those who has submitted first message to this lane, disable
/// Lane3 until some block, ...), then it may be built using this verifier.
///
/// Any fee requirements should also be enforced here.
pub trait LaneMessageVerifier<Submitter, Payload, Fee> {
/// Error type.
type Error: Debug + Into<&'static str>;
/// Verify message payload and return Ok(()) if message is valid and allowed to be sent over the lane.
fn verify_message(
submitter: &Sender<Submitter>,
delivery_and_dispatch_fee: &Fee,
lane: &LaneId,
outbound_data: &OutboundLaneData,
payload: &Payload,
) -> Result<(), Self::Error>;
}
/// Message delivery payment. It is called as a part of submit-message transaction. Transaction
/// submitter is paying (in source chain tokens/assets) for:
///
/// 1) submit-message-transaction-fee itself. This fee is not included in the
/// `delivery_and_dispatch_fee` and is witheld by the regular transaction payment mechanism;
/// 2) message-delivery-transaction-fee. It is submitted to the target node by relayer;
/// 3) message-dispatch fee. It is paid by relayer for processing message by target chain;
/// 4) message-receiving-delivery-transaction-fee. It is submitted to the source node
/// by relayer.
///
/// So to be sure that any non-altruist relayer would agree to deliver message, submitter
/// should set `delivery_and_dispatch_fee` to at least (equialent of): sum of fees from (2)
/// to (4) above, plus some interest for the relayer.
pub trait MessageDeliveryAndDispatchPayment<AccountId, Balance> {
/// Error type.
type Error: Debug + Into<&'static str>;
/// Withhold/write-off delivery_and_dispatch_fee from submitter account to
/// some relayers-fund account.
fn pay_delivery_and_dispatch_fee(
submitter: &Sender<AccountId>,
fee: &Balance,
relayer_fund_account: &AccountId,
) -> Result<(), Self::Error>;
/// Pay rewards for delivering messages to the given relayers.
///
/// The implementation may also choose to pay reward to the `confirmation_relayer`, which is
/// a relayer that has submitted delivery confirmation transaction.
fn pay_relayers_rewards(
confirmation_relayer: &AccountId,
relayers_rewards: RelayersRewards<AccountId, Balance>,
relayer_fund_account: &AccountId,
);
/// Perform some initialization in externalities-provided environment.
///
/// For instance you may ensure that particular required accounts or storage items are present.
/// Returns the number of storage reads performed.
fn initialize(_relayer_fund_account: &AccountId) -> usize {
0
}
}
/// Handler for messages delivery confirmation.
#[impl_trait_for_tuples::impl_for_tuples(30)]
pub trait OnDeliveryConfirmed {
/// Called when we receive confirmation that our messages have been delivered to the
/// target chain. The confirmation also has single bit dispatch result for every
/// confirmed message (see `DeliveredMessages` for details).
fn on_messages_delivered(_lane: &LaneId, _messages: &DeliveredMessages) {}
}
/// Structure that may be used in place of `TargetHeaderChain`, `LaneMessageVerifier` and
/// `MessageDeliveryAndDispatchPayment` on chains, where outbound messages are forbidden.
pub struct ForbidOutboundMessages;
/// Error message that is used in `ForbidOutboundMessages` implementation.
const ALL_OUTBOUND_MESSAGES_REJECTED: &str = "This chain is configured to reject all outbound messages";
impl<Payload, AccountId> TargetHeaderChain<Payload, AccountId> for ForbidOutboundMessages {
type Error = &'static str;
type MessagesDeliveryProof = ();
fn verify_message(_payload: &Payload) -> Result<(), Self::Error> {
Err(ALL_OUTBOUND_MESSAGES_REJECTED)
}
fn verify_messages_delivery_proof(
_proof: Self::MessagesDeliveryProof,
) -> Result<(LaneId, InboundLaneData<AccountId>), Self::Error> {
Err(ALL_OUTBOUND_MESSAGES_REJECTED)
}
}
impl<Submitter, Payload, Fee> LaneMessageVerifier<Submitter, Payload, Fee> for ForbidOutboundMessages {
type Error = &'static str;
fn verify_message(
_submitter: &Sender<Submitter>,
_delivery_and_dispatch_fee: &Fee,
_lane: &LaneId,
_outbound_data: &OutboundLaneData,
_payload: &Payload,
) -> Result<(), Self::Error> {
Err(ALL_OUTBOUND_MESSAGES_REJECTED)
}
}
impl<AccountId, Balance> MessageDeliveryAndDispatchPayment<AccountId, Balance> for ForbidOutboundMessages {
type Error = &'static str;
fn pay_delivery_and_dispatch_fee(
_submitter: &Sender<AccountId>,
_fee: &Balance,
_relayer_fund_account: &AccountId,
) -> Result<(), Self::Error> {
Err(ALL_OUTBOUND_MESSAGES_REJECTED)
}
fn pay_relayers_rewards(
_confirmation_relayer: &AccountId,
_relayers_rewards: RelayersRewards<AccountId, Balance>,
_relayer_fund_account: &AccountId,
) {
}
}
@@ -1,172 +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/>.
//! Primitives of messages module, that are used on the target chain.
use crate::{LaneId, Message, MessageData, MessageKey, OutboundLaneData};
use bp_runtime::{messages::MessageDispatchResult, Size};
use codec::{Decode, Encode, Error as CodecError};
use frame_support::{weights::Weight, Parameter, RuntimeDebug};
use sp_std::{collections::btree_map::BTreeMap, fmt::Debug, prelude::*};
/// Proved messages from the source chain.
pub type ProvedMessages<Message> = BTreeMap<LaneId, ProvedLaneMessages<Message>>;
/// Proved messages from single lane of the source chain.
#[derive(RuntimeDebug, Encode, Decode, Clone, PartialEq, Eq)]
pub struct ProvedLaneMessages<Message> {
/// Optional outbound lane state.
pub lane_state: Option<OutboundLaneData>,
/// Messages sent through this lane.
pub messages: Vec<Message>,
}
/// Message data with decoded dispatch payload.
#[derive(RuntimeDebug)]
pub struct DispatchMessageData<DispatchPayload, Fee> {
/// Result of dispatch payload decoding.
pub payload: Result<DispatchPayload, CodecError>,
/// Message delivery and dispatch fee, paid by the submitter.
pub fee: Fee,
}
/// Message with decoded dispatch payload.
#[derive(RuntimeDebug)]
pub struct DispatchMessage<DispatchPayload, Fee> {
/// Message key.
pub key: MessageKey,
/// Message data with decoded dispatch payload.
pub data: DispatchMessageData<DispatchPayload, Fee>,
}
/// Source chain API. Used by target chain, to verify source chain proofs.
///
/// All implementations of this trait should only work with finalized data that
/// can't change. Wrong implementation may lead to invalid lane states (i.e. lane
/// that's stuck) and/or processing messages without paying fees.
pub trait SourceHeaderChain<Fee> {
/// Error type.
type Error: Debug + Into<&'static str>;
/// Proof that messages are sent from source chain. This may also include proof
/// of corresponding outbound lane states.
type MessagesProof: Parameter + Size;
/// Verify messages proof and return proved messages.
///
/// Returns error if either proof is incorrect, or the number of messages in the proof
/// is not matching the `messages_count`.
///
/// Messages vector is required to be sorted by nonce within each lane. Out-of-order
/// messages will be rejected.
///
/// The `messages_count` argument verification (sane limits) is supposed to be made
/// outside of this function. This function only verifies that the proof declares exactly
/// `messages_count` messages.
fn verify_messages_proof(
proof: Self::MessagesProof,
messages_count: u32,
) -> Result<ProvedMessages<Message<Fee>>, Self::Error>;
}
/// Called when inbound message is received.
pub trait MessageDispatch<AccountId, Fee> {
/// Decoded message payload type. Valid message may contain invalid payload. In this case
/// message is delivered, but dispatch fails. Therefore, two separate types of payload
/// (opaque `MessagePayload` used in delivery and this `DispatchPayload` used in dispatch).
type DispatchPayload: Decode;
/// Estimate dispatch weight.
///
/// This function must: (1) be instant and (2) return correct upper bound
/// of dispatch weight.
fn dispatch_weight(message: &DispatchMessage<Self::DispatchPayload, Fee>) -> Weight;
/// Called when inbound message is received.
///
/// It is up to the implementers of this trait to determine whether the message
/// is invalid (i.e. improperly encoded, has too large weight, ...) or not.
///
/// If your configuration allows paying dispatch fee at the target chain, then
/// it must be paid inside this method to the `relayer_account`.
fn dispatch(
relayer_account: &AccountId,
message: DispatchMessage<Self::DispatchPayload, Fee>,
) -> MessageDispatchResult;
}
impl<Message> Default for ProvedLaneMessages<Message> {
fn default() -> Self {
ProvedLaneMessages {
lane_state: None,
messages: Vec::new(),
}
}
}
impl<DispatchPayload: Decode, Fee> From<Message<Fee>> for DispatchMessage<DispatchPayload, Fee> {
fn from(message: Message<Fee>) -> Self {
DispatchMessage {
key: message.key,
data: message.data.into(),
}
}
}
impl<DispatchPayload: Decode, Fee> From<MessageData<Fee>> for DispatchMessageData<DispatchPayload, Fee> {
fn from(data: MessageData<Fee>) -> Self {
DispatchMessageData {
payload: DispatchPayload::decode(&mut &data.payload[..]),
fee: data.fee,
}
}
}
/// Structure that may be used in place of `SourceHeaderChain` and `MessageDispatch` on chains,
/// where inbound messages are forbidden.
pub struct ForbidInboundMessages;
/// Error message that is used in `ForbidOutboundMessages` implementation.
const ALL_INBOUND_MESSAGES_REJECTED: &str = "This chain is configured to reject all inbound messages";
impl<Fee> SourceHeaderChain<Fee> for ForbidInboundMessages {
type Error = &'static str;
type MessagesProof = ();
fn verify_messages_proof(
_proof: Self::MessagesProof,
_messages_count: u32,
) -> Result<ProvedMessages<Message<Fee>>, Self::Error> {
Err(ALL_INBOUND_MESSAGES_REJECTED)
}
}
impl<AccountId, Fee> MessageDispatch<AccountId, Fee> for ForbidInboundMessages {
type DispatchPayload = ();
fn dispatch_weight(_message: &DispatchMessage<Self::DispatchPayload, Fee>) -> Weight {
Weight::MAX
}
fn dispatch(_: &AccountId, _: DispatchMessage<Self::DispatchPayload, Fee>) -> MessageDispatchResult {
MessageDispatchResult {
dispatch_result: false,
unspent_weight: 0,
dispatch_fee_paid_during_dispatch: false,
}
}
}
@@ -1,43 +0,0 @@
[package]
name = "bp-polkadot-core"
description = "Primitives of Polkadot-like runtime."
version = "0.1.0"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2018"
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
[dependencies]
parity-scale-codec = { version = "2.0.0", default-features = false, features = ["derive"] }
# Bridge Dependencies
bp-messages = { path = "../messages", default-features = false }
bp-runtime = { path = "../runtime", default-features = false }
# Substrate Based Dependencies
frame-support = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
frame-system = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-api = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-core = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
sp-std = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
sp-version = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
[dev-dependencies]
hex = "0.4"
[features]
default = ["std"]
std = [
"bp-messages/std",
"bp-runtime/std",
"frame-support/std",
"frame-system/std",
"parity-scale-codec/std",
"sp-api/std",
"sp-core/std",
"sp-runtime/std",
"sp-std/std",
"sp-version/std",
]
@@ -1,350 +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)]
use bp_messages::MessageNonce;
use bp_runtime::Chain;
use frame_support::{
dispatch::Dispatchable,
parameter_types,
weights::{
constants::{BlockExecutionWeight, WEIGHT_PER_SECOND},
DispatchClass, Weight,
},
Blake2_128Concat, RuntimeDebug, StorageHasher, Twox128,
};
use frame_system::limits;
use parity_scale_codec::Compact;
use sp_core::Hasher as HasherT;
use sp_runtime::{
generic,
traits::{BlakeTwo256, IdentifyAccount, Verify},
MultiAddress, MultiSignature, OpaqueExtrinsic,
};
use sp_std::prelude::Vec;
// Re-export's to avoid extra substrate dependencies in chain-specific crates.
pub use frame_support::{weights::constants::ExtrinsicBaseWeight, Parameter};
pub use sp_runtime::{traits::Convert, Perbill};
/// Number of extra bytes (excluding size of storage value itself) of storage proof, built at
/// Polkadot-like chain. This mostly depends on number of entries in the storage trie.
/// Some reserve is reserved to account future chain growth.
///
/// To compute this value, we've synced Kusama chain blocks [0; 6545733] to see if there were
/// any significant changes of the storage proof size (NO):
///
/// - at block 3072 the storage proof size overhead was 579 bytes;
/// - at block 2479616 it was 578 bytes;
/// - at block 4118528 it was 711 bytes;
/// - at block 6540800 it was 779 bytes.
///
/// The number of storage entries at the block 6546170 was 351207 and number of trie nodes in
/// the storage proof was 5 (log(16, 351207) ~ 4.6).
///
/// So the assumption is that the storage proof size overhead won't be larger than 1024 in the
/// nearest future. If it'll ever break this barrier, then we'll need to update this constant
/// at next runtime upgrade.
pub const EXTRA_STORAGE_PROOF_SIZE: u32 = 1024;
/// Maximal size (in bytes) of encoded (using `Encode::encode()`) account id.
///
/// All polkadot-like chains are using same crypto.
pub const MAXIMAL_ENCODED_ACCOUNT_ID_SIZE: u32 = 32;
/// All Polkadot-like chains allow normal extrinsics to fill block up to 75%.
///
/// This is a copy-paste from the Polkadot repo's `polkadot-runtime-common` crate.
const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
/// All Polkadot-like chains allow 2 seconds of compute with a 6 second average block time.
///
/// This is a copy-paste from the Polkadot repo's `polkadot-runtime-common` crate.
pub const MAXIMUM_BLOCK_WEIGHT: Weight = 2 * WEIGHT_PER_SECOND;
/// All Polkadot-like chains assume that an on-initialize consumes 1% of the weight on average,
/// hence a single extrinsic will not be allowed to consume more than `AvailableBlockRatio - 1%`.
///
/// This is a copy-paste from the Polkadot repo's `polkadot-runtime-common` crate.
pub const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(1);
parameter_types! {
/// All Polkadot-like chains have maximal block size set to 5MB.
///
/// This is a copy-paste from the Polkadot repo's `polkadot-runtime-common` crate.
pub BlockLength: limits::BlockLength = limits::BlockLength::max_with_normal_ratio(
5 * 1024 * 1024,
NORMAL_DISPATCH_RATIO,
);
/// All Polkadot-like chains have the same block weights.
///
/// This is a copy-paste from the Polkadot repo's `polkadot-runtime-common` crate.
pub BlockWeights: limits::BlockWeights = limits::BlockWeights::builder()
.base_block(BlockExecutionWeight::get())
.for_class(DispatchClass::all(), |weights| {
weights.base_extrinsic = ExtrinsicBaseWeight::get();
})
.for_class(DispatchClass::Normal, |weights| {
weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
})
.for_class(DispatchClass::Operational, |weights| {
weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
// Operational transactions have an extra reserved space, so that they
// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.
weights.reserved = Some(
MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT,
);
})
.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
.build_or_panic();
}
/// Get the maximum weight (compute time) that a Normal extrinsic on the Polkadot-like chain can use.
pub fn max_extrinsic_weight() -> Weight {
BlockWeights::get()
.get(DispatchClass::Normal)
.max_extrinsic
.unwrap_or(Weight::MAX)
}
/// Get the maximum length in bytes that a Normal extrinsic on the Polkadot-like chain requires.
pub fn max_extrinsic_size() -> u32 {
*BlockLength::get().max.get(DispatchClass::Normal)
}
// TODO [#78] may need to be updated after https://github.com/paritytech/parity-bridges-common/issues/78
/// Maximal number of messages in single delivery transaction.
pub const MAX_MESSAGES_IN_DELIVERY_TRANSACTION: MessageNonce = 128;
/// Maximal number of unrewarded relayer entries at inbound lane.
pub const MAX_UNREWARDED_RELAYER_ENTRIES_AT_INBOUND_LANE: MessageNonce = 128;
// TODO [#438] should be selected keeping in mind:
// finality delay on both chains + reward payout cost + messages throughput.
/// Maximal number of unconfirmed messages at inbound lane.
pub const MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE: MessageNonce = 8192;
/// Re-export `time_units` to make usage easier.
pub use time_units::*;
/// Human readable time units defined in terms of number of blocks.
pub mod time_units {
use super::BlockNumber;
pub const MILLISECS_PER_BLOCK: u64 = 6000;
pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;
pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);
pub const HOURS: BlockNumber = MINUTES * 60;
pub const DAYS: BlockNumber = HOURS * 24;
}
/// Block number type used in Polkadot-like chains.
pub type BlockNumber = u32;
/// Hash type used in Polkadot-like chains.
pub type Hash = <BlakeTwo256 as HasherT>::Out;
/// Account Index (a.k.a. nonce).
pub type Index = u32;
/// Hashing type.
pub type Hashing = BlakeTwo256;
/// The type of an object that can produce hashes on Polkadot-like chains.
pub type Hasher = BlakeTwo256;
/// The header type used by Polkadot-like chains.
pub type Header = generic::Header<BlockNumber, Hasher>;
/// Signature type used by Polkadot-like chains.
pub type Signature = MultiSignature;
/// Public key of account on Polkadot-like chains.
pub type AccountPublic = <Signature as Verify>::Signer;
/// Id of account on Polkadot-like chains.
pub type AccountId = <AccountPublic as IdentifyAccount>::AccountId;
/// Index of a transaction on the Polkadot-like chains.
pub type Nonce = u32;
/// Block type of Polkadot-like chains.
pub type Block = generic::Block<Header, OpaqueExtrinsic>;
/// Polkadot-like block signed with a Justification.
pub type SignedBlock = generic::SignedBlock<Block>;
/// The balance of an account on Polkadot-like chain.
pub type Balance = u128;
/// Unchecked Extrinsic type.
pub type UncheckedExtrinsic<Call> =
generic::UncheckedExtrinsic<MultiAddress<AccountId, ()>, Call, Signature, SignedExtensions<Call>>;
/// A type of the data encoded as part of the transaction.
pub type SignedExtra = (
(),
(),
(),
sp_runtime::generic::Era,
Compact<Nonce>,
(),
Compact<Balance>,
);
/// Parameters which are part of the payload used to produce transaction signature,
/// but don't end up in the transaction itself (i.e. inherent part of the runtime).
pub type AdditionalSigned = (u32, u32, Hash, Hash, (), (), ());
/// A simplified version of signed extensions meant for producing signed transactions
/// and signed payload in the client code.
#[derive(PartialEq, Eq, Clone, RuntimeDebug)]
pub struct SignedExtensions<Call> {
encode_payload: SignedExtra,
additional_signed: AdditionalSigned,
_data: sp_std::marker::PhantomData<Call>,
}
impl<Call> parity_scale_codec::Encode for SignedExtensions<Call> {
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
self.encode_payload.using_encoded(f)
}
}
impl<Call> parity_scale_codec::Decode for SignedExtensions<Call> {
fn decode<I: parity_scale_codec::Input>(_input: &mut I) -> Result<Self, parity_scale_codec::Error> {
unimplemented!("SignedExtensions are never meant to be decoded, they are only used to create transaction");
}
}
impl<Call> SignedExtensions<Call> {
pub fn new(
version: sp_version::RuntimeVersion,
era: sp_runtime::generic::Era,
genesis_hash: Hash,
nonce: Nonce,
tip: Balance,
) -> Self {
Self {
encode_payload: (
(), // spec version
(), // tx version
(), // genesis
era, // era
nonce.into(), // nonce (compact encoding)
(), // Check weight
tip.into(), // transaction payment / tip (compact encoding)
),
additional_signed: (
version.spec_version,
version.transaction_version,
genesis_hash,
genesis_hash,
(),
(),
(),
),
_data: Default::default(),
}
}
}
impl<Call> sp_runtime::traits::SignedExtension for SignedExtensions<Call>
where
Call: parity_scale_codec::Codec + sp_std::fmt::Debug + Sync + Send + Clone + Eq + PartialEq,
Call: Dispatchable,
{
const IDENTIFIER: &'static str = "Not needed.";
type AccountId = AccountId;
type Call = Call;
type AdditionalSigned = AdditionalSigned;
type Pre = ();
fn additional_signed(&self) -> Result<Self::AdditionalSigned, frame_support::unsigned::TransactionValidityError> {
Ok(self.additional_signed)
}
}
/// Polkadot-like chain.
#[derive(RuntimeDebug)]
pub struct PolkadotLike;
impl Chain for PolkadotLike {
type BlockNumber = BlockNumber;
type Hash = Hash;
type Hasher = Hasher;
type Header = Header;
}
/// Convert a 256-bit hash into an AccountId.
pub struct AccountIdConverter;
impl Convert<sp_core::H256, AccountId> for AccountIdConverter {
fn convert(hash: sp_core::H256) -> AccountId {
hash.to_fixed_bytes().into()
}
}
/// Return a storage key for account data.
///
/// This is based on FRAME storage-generation code from Substrate:
/// https://github.com/paritytech/substrate/blob/c939ceba381b6313462d47334f775e128ea4e95d/frame/support/src/storage/generator/map.rs#L74
/// The equivalent command to invoke in case full `Runtime` is known is this:
/// `let key = frame_system::Account::<Runtime>::storage_map_final_key(&account_id);`
pub fn account_info_storage_key(id: &AccountId) -> Vec<u8> {
let module_prefix_hashed = Twox128::hash(b"System");
let storage_prefix_hashed = Twox128::hash(b"Account");
let key_hashed = parity_scale_codec::Encode::using_encoded(id, Blake2_128Concat::hash);
let mut final_key = Vec::with_capacity(module_prefix_hashed.len() + storage_prefix_hashed.len() + key_hashed.len());
final_key.extend_from_slice(&module_prefix_hashed[..]);
final_key.extend_from_slice(&storage_prefix_hashed[..]);
final_key.extend_from_slice(&key_hashed);
final_key
}
#[cfg(test)]
mod tests {
use super::*;
use sp_runtime::codec::Encode;
#[test]
fn maximal_encoded_account_id_size_is_correct() {
let actual_size = AccountId::default().encode().len();
assert!(
actual_size <= MAXIMAL_ENCODED_ACCOUNT_ID_SIZE as usize,
"Actual size of encoded account id for Polkadot-like chains ({}) is larger than expected {}",
actual_size,
MAXIMAL_ENCODED_ACCOUNT_ID_SIZE,
);
}
#[test]
fn should_generate_storage_key() {
let acc = [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32,
]
.into();
let key = account_info_storage_key(&acc);
assert_eq!(hex::encode(key), "26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da92dccd599abfe1920a1cff8a7358231430102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20");
}
}
@@ -1,41 +0,0 @@
[package]
name = "bp-runtime"
description = "Primitives that may be used at (bridges) runtime level."
version = "0.1.0"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2018"
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
[dependencies]
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false }
hash-db = { version = "0.15.2", default-features = false }
num-traits = { version = "0.2", default-features = false }
# Substrate Dependencies
frame-support = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-core = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-io = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-state-machine = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
sp-std = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-trie = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
[dev-dependencies]
sp-core = { git = "https://github.com/paritytech/substrate", branch = "master" }
[features]
default = ["std"]
std = [
"codec/std",
"frame-support/std",
"hash-db/std",
"num-traits/std",
"sp-core/std",
"sp-io/std",
"sp-runtime/std",
"sp-std/std",
"sp-state-machine/std",
"sp-trie/std",
]
@@ -1,87 +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 frame_support::Parameter;
use num_traits::AsPrimitive;
use sp_runtime::traits::{
AtLeast32BitUnsigned, Hash as HashT, Header as HeaderT, MaybeDisplay, MaybeMallocSizeOf, MaybeSerializeDeserialize,
Member, SimpleBitOps,
};
use sp_std::str::FromStr;
/// Minimal Substrate-based chain representation that may be used from no_std environment.
pub trait Chain: Send + Sync + 'static {
/// A type that fulfills the abstract idea of what a Substrate block number is.
// Constraits come from the associated Number type of `sp_runtime::traits::Header`
// See here for more info:
// https://crates.parity.io/sp_runtime/traits/trait.Header.html#associatedtype.Number
//
// Note that the `AsPrimitive<usize>` trait is required by the GRANDPA justification
// verifier, and is not usually part of a Substrate Header's Number type.
type BlockNumber: Parameter
+ Member
+ MaybeSerializeDeserialize
+ sp_std::hash::Hash
+ Copy
+ Default
+ MaybeDisplay
+ AtLeast32BitUnsigned
+ FromStr
+ MaybeMallocSizeOf
+ AsPrimitive<usize>
+ Default;
/// A type that fulfills the abstract idea of what a Substrate hash is.
// Constraits come from the associated Hash type of `sp_runtime::traits::Header`
// See here for more info:
// https://crates.parity.io/sp_runtime/traits/trait.Header.html#associatedtype.Hash
type Hash: Parameter
+ Member
+ MaybeSerializeDeserialize
+ sp_std::hash::Hash
+ Ord
+ Copy
+ MaybeDisplay
+ Default
+ SimpleBitOps
+ AsRef<[u8]>
+ AsMut<[u8]>
+ MaybeMallocSizeOf;
/// A type that fulfills the abstract idea of what a Substrate hasher (a type
/// that produces hashes) is.
// Constraits come from the associated Hashing type of `sp_runtime::traits::Header`
// See here for more info:
// https://crates.parity.io/sp_runtime/traits/trait.Header.html#associatedtype.Hashing
type Hasher: HashT<Output = Self::Hash>;
/// A type that fulfills the abstract idea of what a Substrate header is.
// See here for more info:
// https://crates.parity.io/sp_runtime/traits/trait.Header.html
type Header: Parameter + HeaderT<Number = Self::BlockNumber, Hash = Self::Hash> + MaybeSerializeDeserialize;
}
/// Block number used by the chain.
pub type BlockNumberOf<C> = <C as Chain>::BlockNumber;
/// Hash type used by the chain.
pub type HashOf<C> = <C as Chain>::Hash;
/// Hasher type used by the chain.
pub type HasherOf<C> = <C as Chain>::Hasher;
/// Header type used by the chain.
pub type HeaderOf<C> = <C as Chain>::Header;
@@ -1,140 +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/>.
//! Primitives that may be used at (bridges) runtime level.
#![cfg_attr(not(feature = "std"), no_std)]
use codec::Encode;
use sp_core::hash::H256;
use sp_io::hashing::blake2_256;
use sp_std::convert::TryFrom;
pub use chain::{BlockNumberOf, Chain, HashOf, HasherOf, HeaderOf};
pub use storage_proof::{Error as StorageProofError, StorageProofChecker};
#[cfg(feature = "std")]
pub use storage_proof::craft_valid_storage_proof;
pub mod messages;
mod chain;
mod storage_proof;
/// Use this when something must be shared among all instances.
pub const NO_INSTANCE_ID: ChainId = [0, 0, 0, 0];
/// Bridge-with-Rialto instance id.
pub const RIALTO_CHAIN_ID: ChainId = *b"rlto";
/// Bridge-with-Millau instance id.
pub const MILLAU_CHAIN_ID: ChainId = *b"mlau";
/// Bridge-with-Polkadot instance id.
pub const POLKADOT_CHAIN_ID: ChainId = *b"pdot";
/// Bridge-with-Kusama instance id.
pub const KUSAMA_CHAIN_ID: ChainId = *b"ksma";
/// Bridge-with-Rococo instance id.
pub const ROCOCO_CHAIN_ID: ChainId = *b"roco";
/// Bridge-with-Wococo instance id.
pub const WOCOCO_CHAIN_ID: ChainId = *b"woco";
/// Call-dispatch module prefix.
pub const CALL_DISPATCH_MODULE_PREFIX: &[u8] = b"pallet-bridge/dispatch";
/// A unique prefix for entropy when generating cross-chain account IDs.
pub const ACCOUNT_DERIVATION_PREFIX: &[u8] = b"pallet-bridge/account-derivation/account";
/// A unique prefix for entropy when generating a cross-chain account ID for the Root account.
pub const ROOT_ACCOUNT_DERIVATION_PREFIX: &[u8] = b"pallet-bridge/account-derivation/root";
/// Unique identifier of the chain.
///
/// In addition to its main function (identifying the chain), this type may also be used to
/// identify module instance. We have a bunch of pallets that may be used in different bridges. E.g.
/// messages pallet may be deployed twice in the same runtime to bridge ThisChain with Chain1 and Chain2.
/// Sometimes we need to be able to identify deployed instance dynamically. This type may be used for that.
pub type ChainId = [u8; 4];
/// Type of accounts on the source chain.
pub enum SourceAccount<T> {
/// An account that belongs to Root (privileged origin).
Root,
/// A non-priviledged account.
///
/// The embedded account ID may or may not have a private key depending on the "owner" of the
/// account (private key, pallet, proxy, etc.).
Account(T),
}
/// Derive an account ID from a foreign account ID.
///
/// This function returns an encoded Blake2 hash. It is the responsibility of the caller to ensure
/// this can be successfully decoded into an AccountId.
///
/// The `bridge_id` is used to provide extra entropy when producing account IDs. This helps prevent
/// AccountId collisions between different bridges on a single target chain.
///
/// Note: If the same `bridge_id` is used across different chains (for example, if one source chain
/// is bridged to multiple target chains), then all the derived accounts would be the same across
/// the different chains. This could negatively impact users' privacy across chains.
pub fn derive_account_id<AccountId>(bridge_id: ChainId, id: SourceAccount<AccountId>) -> H256
where
AccountId: Encode,
{
match id {
SourceAccount::Root => (ROOT_ACCOUNT_DERIVATION_PREFIX, bridge_id).using_encoded(blake2_256),
SourceAccount::Account(id) => (ACCOUNT_DERIVATION_PREFIX, bridge_id, id).using_encoded(blake2_256),
}
.into()
}
/// Derive the account ID of the shared relayer fund account.
///
/// This account is used to collect fees for relayers that are passing messages across the bridge.
///
/// The account ID can be the same across different instances of `pallet-bridge-messages` if the same
/// `bridge_id` is used.
pub fn derive_relayer_fund_account_id(bridge_id: ChainId) -> H256 {
("relayer-fund-account", bridge_id).using_encoded(blake2_256).into()
}
/// Anything that has size.
pub trait Size {
/// Return approximate size of this object (in bytes).
///
/// This function should be lightweight. The result should not necessary be absolutely
/// accurate.
fn size_hint(&self) -> u32;
}
impl Size for () {
fn size_hint(&self) -> u32 {
0
}
}
/// Pre-computed size.
pub struct PreComputedSize(pub usize);
impl Size for PreComputedSize {
fn size_hint(&self) -> u32 {
u32::try_from(self.0).unwrap_or(u32::MAX)
}
}
@@ -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/>.
//! Primitives that may be used by different message delivery and dispatch mechanisms.
use codec::{Decode, Encode};
use frame_support::{weights::Weight, RuntimeDebug};
/// Where message dispatch fee is paid?
#[derive(Encode, Decode, RuntimeDebug, Clone, Copy, PartialEq, Eq)]
pub enum DispatchFeePayment {
/// The dispacth fee is paid at the source chain.
AtSourceChain,
/// The dispatch fee is paid at the target chain.
///
/// The fee will be paid right before the message is dispatched. So in case of any other
/// issues (like invalid call encoding, invalid signature, ...) the dispatch module won't
/// do any direct transfers. Instead, it'll return fee related to this message dispatch to the
/// relayer.
AtTargetChain,
}
/// Message dispatch result.
#[derive(Encode, Decode, RuntimeDebug, Clone, PartialEq, Eq)]
pub struct MessageDispatchResult {
/// Dispatch result flag. This flag is relayed back to the source chain and, generally
/// speaking, may bring any (that fits in single bit) information from the dispatcher at
/// the target chain to the message submitter at the source chain. If you're using immediate
/// call dispatcher, then it'll be result of the dispatch - `true` if dispatch has succeeded
/// and `false` otherwise.
pub dispatch_result: bool,
/// Unspent dispatch weight. This weight that will be deducted from total delivery transaction
/// weight, thus reducing the transaction cost. This shall not be zero in (at least) two cases:
///
/// 1) if message has been dispatched successfully, but post-dispatch weight is less than
/// the weight, declared by the message sender;
/// 2) if message has not been dispatched at all.
pub unspent_weight: Weight,
/// Whether the message dispatch fee has been paid during dispatch. This will be true if your
/// configuration supports pay-dispatch-fee-at-target-chain option and message sender has enabled
/// this option.
pub dispatch_fee_paid_during_dispatch: bool,
}
@@ -1,112 +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/>.
//! Logic for checking Substrate storage proofs.
use hash_db::{HashDB, Hasher, EMPTY_PREFIX};
use sp_runtime::RuntimeDebug;
use sp_std::vec::Vec;
use sp_trie::{read_trie_value, Layout, MemoryDB, StorageProof};
/// This struct is used to read storage values from a subset of a Merklized database. The "proof"
/// is a subset of the nodes in the Merkle structure of the database, so that it provides
/// authentication against a known Merkle root as well as the values in the database themselves.
pub struct StorageProofChecker<H>
where
H: Hasher,
{
root: H::Out,
db: MemoryDB<H>,
}
impl<H> StorageProofChecker<H>
where
H: Hasher,
{
/// Constructs a new storage proof checker.
///
/// This returns an error if the given proof is invalid with respect to the given root.
pub fn new(root: H::Out, proof: StorageProof) -> Result<Self, Error> {
let db = proof.into_memory_db();
if !db.contains(&root, EMPTY_PREFIX) {
return Err(Error::StorageRootMismatch);
}
let checker = StorageProofChecker { root, db };
Ok(checker)
}
/// Reads a value from the available subset of storage. If the value cannot be read due to an
/// incomplete or otherwise invalid proof, this returns an error.
pub fn read_value(&self, key: &[u8]) -> Result<Option<Vec<u8>>, Error> {
read_trie_value::<Layout<H>, _>(&self.db, &self.root, key).map_err(|_| Error::StorageValueUnavailable)
}
}
#[derive(RuntimeDebug, PartialEq)]
pub enum Error {
StorageRootMismatch,
StorageValueUnavailable,
}
/// Return valid storage proof and state root.
///
/// NOTE: This should only be used for **testing**.
#[cfg(feature = "std")]
pub fn craft_valid_storage_proof() -> (sp_core::H256, StorageProof) {
use sp_state_machine::{backend::Backend, prove_read, InMemoryBackend};
// construct storage proof
let backend = <InMemoryBackend<sp_core::Blake2Hasher>>::from(vec![
(None, vec![(b"key1".to_vec(), Some(b"value1".to_vec()))]),
(None, vec![(b"key2".to_vec(), Some(b"value2".to_vec()))]),
(None, vec![(b"key3".to_vec(), Some(b"value3".to_vec()))]),
// Value is too big to fit in a branch node
(None, vec![(b"key11".to_vec(), Some(vec![0u8; 32]))]),
]);
let root = backend.storage_root(std::iter::empty()).0;
let proof = StorageProof::new(
prove_read(backend, &[&b"key1"[..], &b"key2"[..], &b"key22"[..]])
.unwrap()
.iter_nodes()
.collect(),
);
(root, proof)
}
#[cfg(test)]
pub mod tests {
use super::*;
#[test]
fn storage_proof_check() {
let (root, proof) = craft_valid_storage_proof();
// check proof in runtime
let checker = <StorageProofChecker<sp_core::Blake2Hasher>>::new(root, proof.clone()).unwrap();
assert_eq!(checker.read_value(b"key1"), Ok(Some(b"value1".to_vec())));
assert_eq!(checker.read_value(b"key2"), Ok(Some(b"value2".to_vec())));
assert_eq!(checker.read_value(b"key11111"), Err(Error::StorageValueUnavailable));
assert_eq!(checker.read_value(b"key22"), Ok(None));
// checking proof against invalid commitment fails
assert_eq!(
<StorageProofChecker<sp_core::Blake2Hasher>>::new(sp_core::H256::random(), proof).err(),
Some(Error::StorageRootMismatch)
);
}
}
@@ -1,29 +0,0 @@
[package]
name = "bp-test-utils"
version = "0.1.0"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2018"
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
[dependencies]
bp-header-chain = { path = "../header-chain", default-features = false }
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false }
ed25519-dalek = { version = "1.0", default-features = false, features = ["u64_backend"] }
finality-grandpa = { version = "0.14.1", default-features = false }
sp-application-crypto = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
sp-finality-grandpa = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
sp-std = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
[features]
default = ["std"]
std = [
"bp-header-chain/std",
"codec/std",
"ed25519-dalek/std",
"finality-grandpa/std",
"sp-application-crypto/std",
"sp-finality-grandpa/std",
"sp-runtime/std",
"sp-std/std",
]
@@ -1,96 +0,0 @@
// Copyright 2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.
// Parity Bridges Common is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity Bridges Common is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
//! Utilities for working with test accounts.
use codec::Encode;
use ed25519_dalek::{Keypair, PublicKey, SecretKey, Signature};
use finality_grandpa::voter_set::VoterSet;
use sp_application_crypto::Public;
use sp_finality_grandpa::{AuthorityId, AuthorityList, AuthorityWeight};
use sp_runtime::RuntimeDebug;
use sp_std::prelude::*;
/// Set of test accounts with friendly names.
pub const ALICE: Account = Account(0);
pub const BOB: Account = Account(1);
pub const CHARLIE: Account = Account(2);
pub const DAVE: Account = Account(3);
pub const EVE: Account = Account(4);
pub const FERDIE: Account = Account(5);
/// A test account which can be used to sign messages.
#[derive(RuntimeDebug, Clone, Copy)]
pub struct Account(pub u16);
impl Account {
pub fn public(&self) -> PublicKey {
(&self.secret()).into()
}
pub fn secret(&self) -> SecretKey {
let data = self.0.encode();
let mut bytes = [0_u8; 32];
bytes[0..data.len()].copy_from_slice(&*data);
SecretKey::from_bytes(&bytes).expect("A static array of the correct length is a known good.")
}
pub fn pair(&self) -> Keypair {
let mut pair: [u8; 64] = [0; 64];
let secret = self.secret();
pair[..32].copy_from_slice(&secret.to_bytes());
let public = self.public();
pair[32..].copy_from_slice(&public.to_bytes());
Keypair::from_bytes(&pair).expect("We expect the SecretKey to be good, so this must also be good.")
}
pub fn sign(&self, msg: &[u8]) -> Signature {
use ed25519_dalek::Signer;
self.pair().sign(msg)
}
}
impl From<Account> for AuthorityId {
fn from(p: Account) -> Self {
AuthorityId::from_slice(&p.public().to_bytes())
}
}
/// Get a valid set of voters for a Grandpa round.
pub fn voter_set() -> VoterSet<AuthorityId> {
VoterSet::new(authority_list()).unwrap()
}
/// Convenience function to get a list of Grandpa authorities.
pub fn authority_list() -> AuthorityList {
test_keyring()
.iter()
.map(|(id, w)| (AuthorityId::from(*id), *w))
.collect()
}
/// Get the corresponding identities from the keyring for the "standard" authority set.
pub fn test_keyring() -> Vec<(Account, AuthorityWeight)> {
vec![(ALICE, 1), (BOB, 1), (CHARLIE, 1)]
}
/// Get a list of "unique" accounts.
pub fn accounts(len: u16) -> Vec<Account> {
(0..len).into_iter().map(Account).collect()
}
@@ -1,237 +0,0 @@
// Copyright 2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.
// Parity Bridges Common is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity Bridges Common is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
//! Utilities for testing runtime code.
#![cfg_attr(not(feature = "std"), no_std)]
use bp_header_chain::justification::GrandpaJustification;
use codec::Encode;
use sp_application_crypto::TryFrom;
use sp_finality_grandpa::{AuthorityId, AuthorityWeight};
use sp_finality_grandpa::{AuthoritySignature, SetId};
use sp_runtime::traits::{Header as HeaderT, One, Zero};
use sp_std::prelude::*;
// Re-export all our test account utilities
pub use keyring::*;
mod keyring;
pub const TEST_GRANDPA_ROUND: u64 = 1;
pub const TEST_GRANDPA_SET_ID: SetId = 1;
/// Configuration parameters when generating test GRANDPA justifications.
#[derive(Clone)]
pub struct JustificationGeneratorParams<H> {
/// The header which we want to finalize.
pub header: H,
/// The GRANDPA round number for the current authority set.
pub round: u64,
/// The current authority set ID.
pub set_id: SetId,
/// The current GRANDPA authority set.
///
/// The size of the set will determine the number of pre-commits in our justification.
pub authorities: Vec<(Account, AuthorityWeight)>,
/// The total number of precommit ancestors in the `votes_ancestries` field our justification.
///
/// These may be distributed among many different forks.
pub ancestors: u32,
/// The number of forks.
///
/// Useful for creating a "worst-case" scenario in which each authority is on its own fork.
pub forks: u32,
}
impl<H: HeaderT> Default for JustificationGeneratorParams<H> {
fn default() -> Self {
Self {
header: test_header(One::one()),
round: TEST_GRANDPA_ROUND,
set_id: TEST_GRANDPA_SET_ID,
authorities: test_keyring(),
ancestors: 2,
forks: 1,
}
}
}
/// Make a valid GRANDPA justification with sensible defaults
pub fn make_default_justification<H: HeaderT>(header: &H) -> GrandpaJustification<H> {
let params = JustificationGeneratorParams::<H> {
header: header.clone(),
..Default::default()
};
make_justification_for_header(params)
}
/// Generate justifications in a way where we are able to tune the number of pre-commits
/// and vote ancestries which are included in the justification.
///
/// This is useful for benchmarkings where we want to generate valid justifications with
/// a specific number of pre-commits (tuned with the number of "authorities") and/or a specific
/// number of vote ancestries (tuned with the "votes" parameter).
///
/// Note: This needs at least three authorities or else the verifier will complain about
/// being given an invalid commit.
pub fn make_justification_for_header<H: HeaderT>(params: JustificationGeneratorParams<H>) -> GrandpaJustification<H> {
let JustificationGeneratorParams {
header,
round,
set_id,
authorities,
mut ancestors,
forks,
} = params;
let (target_hash, target_number) = (header.hash(), *header.number());
let mut votes_ancestries = vec![];
let mut precommits = vec![];
assert!(forks != 0, "Need at least one fork to have a chain..");
assert!(
forks as usize <= authorities.len(),
"If we have more forks than authorities we can't create valid pre-commits for all the forks."
);
// Roughly, how many vote ancestries do we want per fork
let target_depth = (ancestors + forks - 1) / forks;
let mut unsigned_precommits = vec![];
for i in 0..forks {
let depth = if ancestors >= target_depth {
ancestors -= target_depth;
target_depth
} else {
ancestors
};
// Note: Adding 1 to account for the target header
let chain = generate_chain(i as u32, depth + 1, &header);
// We don't include our finality target header in the vote ancestries
for child in &chain[1..] {
votes_ancestries.push(child.clone());
}
// The header we need to use when pre-commiting is the one at the highest height
// on our chain.
let precommit_candidate = chain.last().map(|h| (h.hash(), *h.number())).unwrap();
unsigned_precommits.push(precommit_candidate);
}
for (i, (id, _weight)) in authorities.iter().enumerate() {
// Assign authorities to sign pre-commits in a round-robin fashion
let target = unsigned_precommits[i % forks as usize];
let precommit = signed_precommit::<H>(id, target, round, set_id);
precommits.push(precommit);
}
GrandpaJustification {
round,
commit: finality_grandpa::Commit {
target_hash,
target_number,
precommits,
},
votes_ancestries,
}
}
fn generate_chain<H: HeaderT>(fork_id: u32, depth: u32, ancestor: &H) -> Vec<H> {
let mut headers = vec![ancestor.clone()];
for i in 1..depth {
let parent = &headers[(i - 1) as usize];
let (hash, num) = (parent.hash(), *parent.number());
let mut header = test_header::<H>(num + One::one());
header.set_parent_hash(hash);
// Modifying the digest so headers at the same height but in different forks have different
// hashes
header
.digest_mut()
.logs
.push(sp_runtime::DigestItem::Other(fork_id.encode()));
headers.push(header);
}
headers
}
/// Create signed precommit with given target.
pub fn signed_precommit<H: HeaderT>(
signer: &Account,
target: (H::Hash, H::Number),
round: u64,
set_id: SetId,
) -> finality_grandpa::SignedPrecommit<H::Hash, H::Number, AuthoritySignature, AuthorityId> {
let precommit = finality_grandpa::Precommit {
target_hash: target.0,
target_number: target.1,
};
let encoded =
sp_finality_grandpa::localized_payload(round, set_id, &finality_grandpa::Message::Precommit(precommit.clone()));
let signature = signer.sign(&encoded);
let raw_signature: Vec<u8> = signature.to_bytes().into();
// Need to wrap our signature and id types that they match what our `SignedPrecommit` is expecting
let signature = AuthoritySignature::try_from(raw_signature).expect(
"We know our Keypair is good,
so our signature must also be good.",
);
let id = (*signer).into();
finality_grandpa::SignedPrecommit {
precommit,
signature,
id,
}
}
/// Get a header for testing.
///
/// The correct parent hash will be used if given a non-zero header.
pub fn test_header<H: HeaderT>(number: H::Number) -> H {
let default = |num| {
H::new(
num,
Default::default(),
Default::default(),
Default::default(),
Default::default(),
)
};
let mut header = default(number);
if number != Zero::zero() {
let parent_hash = default(number - One::one()).hash();
header.set_parent_hash(parent_hash);
}
header
}
/// Convenience function for generating a Header ID at a given block number.
pub fn header_id<H: HeaderT>(index: u8) -> (H::Hash, H::Number) {
(test_header::<H>(index.into()).hash(), index.into())
}