Match substrate's fmt (#1148)

* Alter gitlab.

* Use substrate's rustfmt.toml

* cargo +nightly fmt --all

* Fix spellcheck.

* cargo +nightly fmt --all

* format.

* Fix spellcheck and fmt

* fmt?

* Fix spellcheck

Co-authored-by: Tomasz Drwięga <tomasz@parity.io>
This commit is contained in:
hacpy
2021-09-24 19:29:31 +08:00
committed by Bastian Köcher
parent 87cbb382d9
commit bd70de8b8b
174 changed files with 6095 additions and 4962 deletions
+17 -8
View File
@@ -21,7 +21,9 @@
#![allow(clippy::unnecessary_mut_passed)]
use bp_messages::{LaneId, MessageDetails, MessageNonce, UnrewardedRelayersState};
use frame_support::weights::{WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial};
use frame_support::weights::{
WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial,
};
use sp_std::prelude::*;
use sp_version::RuntimeVersion;
@@ -83,29 +85,36 @@ pub const SESSION_LENGTH: BlockNumber = time_units::HOURS;
pub const WITH_POLKADOT_MESSAGES_PALLET_NAME: &str = "BridgePolkadotMessages";
/// Name of the DOT->KSM conversion rate stored in the Kusama runtime.
pub const POLKADOT_TO_KUSAMA_CONVERSION_RATE_PARAMETER_NAME: &str = "PolkadotToKusamaConversionRate";
pub const POLKADOT_TO_KUSAMA_CONVERSION_RATE_PARAMETER_NAME: &str =
"PolkadotToKusamaConversionRate";
/// 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.
/// 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";
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";
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";
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";
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";
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.
+27 -19
View File
@@ -30,9 +30,8 @@ use frame_support::{
};
use frame_system::limits;
use sp_core::Hasher as HasherT;
use sp_runtime::traits::Convert;
use sp_runtime::{
traits::{IdentifyAccount, Verify},
traits::{Convert, IdentifyAccount, Verify},
MultiSignature, MultiSigner, Perbill,
};
use sp_std::prelude::*;
@@ -77,29 +76,32 @@ 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.
/// 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.
/// 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.
/// 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.
/// 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
@@ -264,22 +266,28 @@ pub const WITH_RIALTO_TOKEN_SWAP_PALLET_NAME: &str = "BridgeRialtoTokenSwap";
/// 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.
/// 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";
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";
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";
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";
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";
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.
+19 -10
View File
@@ -21,7 +21,9 @@
#![allow(clippy::unnecessary_mut_passed)]
use bp_messages::{LaneId, MessageDetails, MessageNonce, UnrewardedRelayersState};
use frame_support::weights::{WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial};
use frame_support::weights::{
WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial,
};
use sp_std::prelude::*;
use sp_version::RuntimeVersion;
@@ -72,8 +74,8 @@ pub const TRANSACTION_BYTE_FEE: Balance = 10 * 10_000_000_000 / 100 / 1_000;
/// Existential deposit on Polkadot.
pub const EXISTENTIAL_DEPOSIT: Balance = 10_000_000_000;
/// The target length of a session (how often authorities change) on Polkadot measured in of number of
/// blocks.
/// The target length of a session (how often authorities change) on Polkadot measured in of number
/// of blocks.
///
/// Note that since this is a target sessions may change before/after this time depending on network
/// conditions.
@@ -83,29 +85,36 @@ pub const SESSION_LENGTH: BlockNumber = 4 * time_units::HOURS;
pub const WITH_KUSAMA_MESSAGES_PALLET_NAME: &str = "BridgeKusamaMessages";
/// Name of the KSM->DOT conversion rate stored in the Polkadot runtime.
pub const KUSAMA_TO_POLKADOT_CONVERSION_RATE_PARAMETER_NAME: &str = "KusamaToPolkadotConversionRate";
pub const KUSAMA_TO_POLKADOT_CONVERSION_RATE_PARAMETER_NAME: &str =
"KusamaToPolkadotConversionRate";
/// 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.
/// 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";
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";
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";
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";
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";
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.
+26 -17
View File
@@ -68,29 +68,32 @@ 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.
/// 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.
/// 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.
/// 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.
/// 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
@@ -231,22 +234,28 @@ pub const WITH_MILLAU_MESSAGES_PALLET_NAME: &str = "BridgeMillauMessages";
/// 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.
/// 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";
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";
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";
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";
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";
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.
+22 -12
View File
@@ -21,7 +21,9 @@
#![allow(clippy::unnecessary_mut_passed)]
use bp_messages::{LaneId, MessageDetails, MessageNonce, UnrewardedRelayersState};
use frame_support::weights::{Weight, WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial};
use frame_support::weights::{
Weight, WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial,
};
use sp_std::prelude::*;
use sp_version::RuntimeVersion;
@@ -30,8 +32,8 @@ 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.
/// 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.
@@ -80,28 +82,36 @@ pub const BEST_FINALIZED_ROCOCO_HEADER_METHOD: &str = "RococoFinalityApi_best_fi
/// 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.
/// 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";
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";
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";
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";
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";
pub const FROM_ROCOCO_UNREWARDED_RELAYERS_STATE: &str =
"FromRococoInboundLaneApi_unrewarded_relayers_state";
/// Weight of pay-dispatch-fee operation for inbound messages at Rococo 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.
/// 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;
sp_api::decl_runtime_apis! {
+17 -9
View File
@@ -22,7 +22,9 @@
use bp_messages::{LaneId, MessageDetails, MessageNonce, UnrewardedRelayersState};
use bp_runtime::Chain;
use frame_support::weights::{WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial};
use frame_support::weights::{
WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial,
};
use sp_std::prelude::*;
use sp_version::RuntimeVersion;
@@ -114,25 +116,31 @@ pub const BEST_FINALIZED_WESTEND_HEADER_METHOD: &str = "WestendFinalityApi_best_
/// 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.
/// 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";
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";
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";
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";
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";
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.
/// 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.
+12 -6
View File
@@ -45,22 +45,28 @@ pub const BEST_FINALIZED_WOCOCO_HEADER_METHOD: &str = "WococoFinalityApi_best_fi
/// 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.
/// 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";
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";
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";
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";
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";
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.
@@ -71,7 +71,9 @@ pub trait MaybeLockFundsTransaction {
/// 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>>;
fn parse(
tx: &Self::Transaction,
) -> Result<LockFundsTransaction<Self::Id, Self::Recipient, Self::Amount>>;
}
/// Map that maps recipients from peer blockchain to this blockchain recipients.
+24 -29
View File
@@ -185,10 +185,7 @@ pub struct SealedEmptyStep {
impl AuraHeader {
/// Compute id of this header.
pub fn compute_id(&self) -> HeaderId {
HeaderId {
number: self.number,
hash: self.compute_hash(),
}
HeaderId { number: self.number, hash: self.compute_hash() }
}
/// Compute hash of this header (keccak of the RLP with seal).
@@ -198,10 +195,9 @@ impl AuraHeader {
/// 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,
})
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.
@@ -238,7 +234,7 @@ impl AuraHeader {
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(),
})
}
@@ -255,9 +251,7 @@ impl AuraHeader {
/// 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())
self.seal.get(2).and_then(|x| Rlp::new(x).as_list::<SealedEmptyStep>().ok())
}
/// Returns header RLP with or without seals.
@@ -368,15 +362,15 @@ impl Receipt {
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));
@@ -428,13 +422,13 @@ impl Decodable for SealedEmptyStep {
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
});
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())
}
}
@@ -498,14 +492,12 @@ pub fn transaction_decode_rlp(raw_tx: &[u8]) -> Result<Transaction, DecoderError
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_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,
})
Ok(Transaction { sender: sender_address, unsigned })
}
/// Convert public key into corresponding ethereum address.
@@ -519,7 +511,10 @@ pub fn public_to_address(public: &[u8; 64]) -> Address {
/// 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> {
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)
@@ -23,8 +23,8 @@
pub use secp256k1::SecretKey;
use crate::{
public_to_address, rlp_encode, step_validator, Address, AuraHeader, RawTransaction, UnsignedTransaction, H256,
H520, U256,
public_to_address, rlp_encode, step_validator, Address, AuraHeader, RawTransaction,
UnsignedTransaction, H256, H520, U256,
};
use secp256k1::{Message, PublicKey};
@@ -80,7 +80,8 @@ impl SignTransaction for UnsignedTransaction {
/// 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 (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();
@@ -116,10 +117,7 @@ mod tests {
let raw_tx = unsigned.clone().sign_by(&signer, Some(42));
assert_eq!(
transaction_decode_rlp(&raw_tx),
Ok(Transaction {
sender: signer_address,
unsigned,
}),
Ok(Transaction { sender: signer_address, unsigned }),
);
// case2: without chain_id replay protection + contract creation
@@ -134,10 +132,7 @@ mod tests {
let raw_tx = unsigned.clone().sign_by(&signer, None);
assert_eq!(
transaction_decode_rlp(&raw_tx),
Ok(Transaction {
sender: signer_address,
unsigned,
}),
Ok(Transaction { sender: signer_address, unsigned }),
);
}
}
@@ -24,8 +24,10 @@ 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::*;
use sp_std::{
collections::{btree_map::BTreeMap, btree_set::BTreeSet},
prelude::*,
};
/// A GRANDPA Justification is a proof that a given header was finalized
/// at a certain height and with a certain set of authorities.
@@ -37,7 +39,8 @@ 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>,
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>,
}
@@ -57,7 +60,8 @@ pub enum Error {
InvalidJustificationTarget,
/// The authority has provided an invalid signature.
InvalidAuthoritySignature,
/// The justification contains precommit for header that is not a descendant of the commit header.
/// 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.
@@ -87,7 +91,7 @@ where
{
// ensure that it is justification for the expected header
if (justification.commit.target_hash, justification.commit.target_number) != finalized_target {
return Err(Error::InvalidJustificationTarget);
return Err(Error::InvalidJustificationTarget)
}
let mut chain = AncestryChain::new(&justification.votes_ancestries);
@@ -99,30 +103,32 @@ where
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;
}
// 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
// `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;
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);
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
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
@@ -144,13 +150,13 @@ where
authorities_set_id,
&mut signature_buffer,
) {
return Err(Error::InvalidAuthoritySignature);
return Err(Error::InvalidAuthoritySignature)
}
}
// check that there are no extra headers in the justification
if !chain.unvisited.is_empty() {
return Err(Error::ExtraHeadersInVotesAncestries);
return Err(Error::ExtraHeadersInVotesAncestries)
}
// check that the cumulative weight of validators voted for the justification target (or one
@@ -186,7 +192,8 @@ impl<Header: HeaderT> AncestryChain<Header> {
AncestryChain { parents, unvisited }
}
/// Returns `Err(_)` if `precommit_target` is a descendant of the `commit_target` block and `Ok(_)` otherwise.
/// 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,
@@ -195,22 +202,22 @@ impl<Header: HeaderT> AncestryChain<Header> {
let mut current_hash = *precommit_target;
loop {
if current_hash == *commit_target {
break;
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);
// `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),
};
}
+5 -7
View File
@@ -20,15 +20,11 @@
#![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;
use core::{clone::Clone, cmp::Eq, default::Default, 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};
use sp_runtime::{generic::OpaqueDigestItemId, traits::Header as HeaderT, RuntimeDebug};
use sp_std::boxed::Box;
pub mod justification;
@@ -82,7 +78,9 @@ pub trait InclusionProofVerifier {
/// 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>;
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.
@@ -23,8 +23,8 @@
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,
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};
@@ -44,18 +44,22 @@ impl AncestryChain {
}
impl finality_grandpa::Chain<TestHash, TestNumber> for AncestryChain {
fn ancestry(&self, base: TestHash, block: TestHash) -> Result<Vec<TestHash>, finality_grandpa::Error> {
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;
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),
}
}
@@ -81,14 +85,11 @@ fn minimal_accounts_set() -> Vec<(Account, AuthorityWeight)> {
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.
/// 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()
VoterSet::new(minimal_accounts_set().iter().map(|(id, w)| (AuthorityId::from(*id), *w)))
.unwrap()
}
/// Make a valid GRANDPA justification with sensible defaults.
@@ -174,14 +175,8 @@ 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());
justification.commit.precommits.push(justification.commit.precommits[0].clone());
justification.commit.precommits.push(justification.commit.precommits[0].clone());
// our implementation succeeds
assert_eq!(
@@ -112,7 +112,12 @@ pub enum CallOrigin<SourceChainAccountId, TargetChainAccountPublic, TargetChainS
/// Message payload type used by dispatch module.
#[derive(RuntimeDebug, Encode, Decode, Clone, PartialEq, Eq)]
pub struct MessagePayload<SourceChainAccountId, TargetChainAccountPublic, TargetChainSignature, Call> {
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,
+37 -32
View File
@@ -110,22 +110,23 @@ pub struct Message<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).
/// Identifiers of relayers and messages that they have delivered to this lane (ordered by
/// message nonce).
///
/// This serves as a helper storage item, to allow the source chain to easily pay rewards
/// to the relayers who successfully delivered messages to the target chain (inbound lane).
///
/// It is guaranteed to have at most N entries, where N is configured at the module level.
/// If there are N entries in this vec, then:
/// 1) all incoming messages are rejected if they're missing corresponding `proof-of(outbound-lane.state)`;
/// 2) all incoming messages are rejected if `proof-of(outbound-lane.state).last_delivered_nonce` is
/// equal to `self.last_confirmed_nonce`.
/// Given what is said above, all nonces in this queue are in range:
/// `(self.last_confirmed_nonce; self.last_delivered_nonce()]`.
/// 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.
/// 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
@@ -141,10 +142,7 @@ pub struct InboundLaneData<RelayerId> {
impl<RelayerId> Default for InboundLaneData<RelayerId> {
fn default() -> Self {
InboundLaneData {
relayers: VecDeque::new(),
last_confirmed_nonce: 0,
}
InboundLaneData { relayers: VecDeque::new(), last_confirmed_nonce: 0 }
}
}
@@ -153,12 +151,17 @@ impl<RelayerId> InboundLaneData<RelayerId> {
/// 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> {
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);
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))
@@ -193,8 +196,8 @@ 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.
/// 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.
@@ -217,7 +220,8 @@ pub struct DeliveredMessages {
}
impl DeliveredMessages {
/// Create new `DeliveredMessages` struct that confirms delivery of single nonce with given dispatch result.
/// 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,
@@ -277,8 +281,8 @@ pub struct UnrewardedRelayersState {
/// Outbound lane data.
#[derive(Encode, Decode, Clone, RuntimeDebug, PartialEq, Eq)]
pub struct OutboundLaneData {
/// Nonce of the oldest message that we haven't yet pruned. May point to not-yet-generated message if
/// all sent messages are already pruned.
/// Nonce of the oldest message that we haven't yet pruned. May point to not-yet-generated
/// message if all sent messages are already pruned.
pub oldest_unpruned_nonce: MessageNonce,
/// Nonce of the latest message, received by bridged chain.
pub latest_received_nonce: MessageNonce,
@@ -289,7 +293,8 @@ pub struct OutboundLaneData {
impl Default for OutboundLaneData {
fn default() -> Self {
OutboundLaneData {
// it is 1 because we're pruning everything in [oldest_unpruned_nonce; latest_received_nonce]
// 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,
@@ -300,7 +305,9 @@ impl Default for OutboundLaneData {
/// 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> {
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) {
@@ -308,7 +315,7 @@ pub fn total_unrewarded_messages<RelayerId>(relayers: &VecDeque<UnrewardedRelaye
} else {
Some(0)
}
}
},
_ => Some(0),
}
}
@@ -322,10 +329,7 @@ mod tests {
assert_eq!(
total_unrewarded_messages(
&vec![
UnrewardedRelayer {
relayer: 1,
messages: DeliveredMessages::new(0, true)
},
UnrewardedRelayer { relayer: 1, messages: DeliveredMessages::new(0, true) },
UnrewardedRelayer {
relayer: 2,
messages: DeliveredMessages::new(MessageNonce::MAX, true)
@@ -349,7 +353,11 @@ mod tests {
(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 expected_size = InboundLaneData::<u8>::encoded_size_hint(
1,
relayer_entries as _,
messages_count as _,
);
let actual_size = InboundLaneData {
relayers: (1u8..=relayer_entries)
.map(|i| {
@@ -383,11 +391,8 @@ mod tests {
#[test]
fn message_dispatch_result_works() {
let delivered_messages = DeliveredMessages {
begin: 100,
end: 150,
dispatch_results: bitvec![Msb0, u8; 1; 151],
};
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));
@@ -81,7 +81,8 @@ 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.
/// 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,
@@ -190,7 +191,8 @@ impl OnMessageAccepted for () {
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";
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;
@@ -208,7 +210,9 @@ impl<Payload, AccountId> TargetHeaderChain<Payload, AccountId> for ForbidOutboun
}
}
impl<Submitter, Payload, Fee> LaneMessageVerifier<Submitter, Payload, Fee> for ForbidOutboundMessages {
impl<Submitter, Payload, Fee> LaneMessageVerifier<Submitter, Payload, Fee>
for ForbidOutboundMessages
{
type Error = &'static str;
fn verify_message(
@@ -222,7 +226,9 @@ impl<Submitter, Payload, Fee> LaneMessageVerifier<Submitter, Payload, Fee> for F
}
}
impl<AccountId, Balance> MessageDeliveryAndDispatchPayment<AccountId, Balance> for ForbidOutboundMessages {
impl<AccountId, Balance> MessageDeliveryAndDispatchPayment<AccountId, Balance>
for ForbidOutboundMessages
{
type Error = &'static str;
fn pay_delivery_and_dispatch_fee(
+11 -11
View File
@@ -111,23 +111,19 @@ pub trait MessageDispatch<AccountId, Fee> {
impl<Message> Default for ProvedLaneMessages<Message> {
fn default() -> Self {
ProvedLaneMessages {
lane_state: None,
messages: Vec::new(),
}
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(),
}
DispatchMessage { key: message.key, data: message.data.into() }
}
}
impl<DispatchPayload: Decode, Fee> From<MessageData<Fee>> for DispatchMessageData<DispatchPayload, Fee> {
impl<DispatchPayload: Decode, Fee> From<MessageData<Fee>>
for DispatchMessageData<DispatchPayload, Fee>
{
fn from(data: MessageData<Fee>) -> Self {
DispatchMessageData {
payload: DispatchPayload::decode(&mut &data.payload[..]),
@@ -141,7 +137,8 @@ impl<DispatchPayload: Decode, Fee> From<MessageData<Fee>> for DispatchMessageDat
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";
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;
@@ -162,7 +159,10 @@ impl<AccountId, Fee> MessageDispatch<AccountId, Fee> for ForbidInboundMessages {
Weight::MAX
}
fn dispatch(_: &AccountId, _: DispatchMessage<Self::DispatchPayload, Fee>) -> MessageDispatchResult {
fn dispatch(
_: &AccountId,
_: DispatchMessage<Self::DispatchPayload, Fee>,
) -> MessageDispatchResult {
MessageDispatchResult {
dispatch_result: false,
unspent_weight: 0,
+35 -30
View File
@@ -76,8 +76,9 @@ const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
/// 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 percent of the weight on average,
/// hence a single extrinsic will not be allowed to consume more than `AvailableBlockRatio - 1 percent`.
/// All Polkadot-like chains assume that an on-initialize consumes 1 percent of the weight on
/// average, hence a single extrinsic will not be allowed to consume more than
/// `AvailableBlockRatio - 1 percent`.
///
/// This is a copy-paste from the Polkadot repo's `polkadot-runtime-common` crate.
pub const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(1);
@@ -113,7 +114,8 @@ parameter_types! {
.build_or_panic();
}
/// Get the maximum weight (compute time) that a Normal extrinsic on the Polkadot-like chain can use.
/// 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)
@@ -144,18 +146,21 @@ pub const MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE: MessageNonce = 8192;
/// Maximal weight of single message delivery confirmation transaction on Polkadot-like 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.
/// 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;
/// Increase of delivery transaction weight on Polkadot-like chain with every additional message byte.
/// Increase of delivery transaction weight on Polkadot-like 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.
/// 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 number of bytes, included in the signed Polkadot-like transaction apart from the encoded call itself.
/// Maximal number of bytes, included in the signed Polkadot-like transaction apart from the encoded
/// call itself.
///
/// Can be computed by subtracting encoded call size from raw transaction size.
pub const TX_EXTRA_BYTES: u32 = 256;
@@ -163,16 +168,18 @@ pub const TX_EXTRA_BYTES: u32 = 256;
/// Weight of single regular message delivery transaction on Polkadot-like 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.
/// 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;
/// Weight of pay-dispatch-fee operation for inbound messages at Polkadot-like 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.
/// 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;
/// Re-export `time_units` to make usage easier.
@@ -240,15 +247,7 @@ pub type UncheckedExtrinsic<Call> =
pub type Address = MultiAddress<AccountId, ()>;
/// A type of the data encoded as part of the transaction.
pub type SignedExtra = (
(),
(),
(),
sp_runtime::generic::Era,
Compact<Nonce>,
(),
Compact<Balance>,
);
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).
@@ -270,7 +269,9 @@ impl<Call> parity_scale_codec::Encode for SignedExtensions<Call> {
}
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> {
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");
}
}
@@ -331,7 +332,9 @@ where
type AdditionalSigned = AdditionalSigned;
type Pre = ();
fn additional_signed(&self) -> Result<Self::AdditionalSigned, frame_support::unsigned::TransactionValidityError> {
fn additional_signed(
&self,
) -> Result<Self::AdditionalSigned, frame_support::unsigned::TransactionValidityError> {
Ok(self.additional_signed)
}
}
@@ -372,7 +375,9 @@ pub fn account_info_storage_key(id: &AccountId) -> Vec<u8> {
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());
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[..]);
@@ -400,8 +405,8 @@ mod tests {
#[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,
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);
+12 -4
View File
@@ -18,8 +18,8 @@ use frame_support::Parameter;
use num_traits::{AsPrimitive, Bounded, CheckedSub, SaturatingAdd, Zero};
use sp_runtime::{
traits::{
AtLeast32Bit, AtLeast32BitUnsigned, Hash as HashT, Header as HeaderT, MaybeDisplay, MaybeMallocSizeOf,
MaybeSerialize, MaybeSerializeDeserialize, Member, SimpleBitOps, Verify,
AtLeast32Bit, AtLeast32BitUnsigned, Hash as HashT, Header as HeaderT, MaybeDisplay,
MaybeMallocSizeOf, MaybeSerialize, MaybeSerializeDeserialize, Member, SimpleBitOps, Verify,
},
FixedPointOperand,
};
@@ -77,10 +77,18 @@ pub trait Chain: Send + Sync + 'static {
/// 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;
type Header: Parameter
+ HeaderT<Number = Self::BlockNumber, Hash = Self::Hash>
+ MaybeSerializeDeserialize;
/// The user account identifier type for the runtime.
type AccountId: Parameter + Member + MaybeSerializeDeserialize + Debug + MaybeDisplay + Ord + Default;
type AccountId: Parameter
+ Member
+ MaybeSerializeDeserialize
+ Debug
+ MaybeDisplay
+ Ord
+ Default;
/// Balance of an account in native tokens.
///
/// The chain may support multiple tokens, but this particular type is for token that is used
+46 -22
View File
@@ -25,8 +25,8 @@ use sp_io::hashing::blake2_256;
use sp_std::{convert::TryFrom, vec::Vec};
pub use chain::{
AccountIdOf, AccountPublicOf, BalanceOf, BlockNumberOf, Chain, HashOf, HasherOf, HeaderOf, IndexOf, SignatureOf,
TransactionEraOf,
AccountIdOf, AccountPublicOf, BalanceOf, BlockNumberOf, Chain, HashOf, HasherOf, HeaderOf,
IndexOf, SignatureOf, TransactionEraOf,
};
pub use storage_proof::{Error as StorageProofError, StorageProofChecker};
@@ -72,8 +72,9 @@ pub const ROOT_ACCOUNT_DERIVATION_PREFIX: &[u8] = b"pallet-bridge/account-deriva
///
/// 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.
/// 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.
@@ -103,8 +104,10 @@ 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),
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()
}
@@ -113,8 +116,8 @@ where
///
/// 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.
/// 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()
}
@@ -154,9 +157,15 @@ pub enum TransactionEra<BlockNumber, BlockHash> {
impl<BlockNumber: Copy + Into<u64>, BlockHash: Copy> TransactionEra<BlockNumber, BlockHash> {
/// Prepare transaction era, based on mortality period and current best block number.
pub fn new(best_block_number: BlockNumber, best_block_hash: BlockHash, mortality_period: Option<u32>) -> Self {
pub fn new(
best_block_number: BlockNumber,
best_block_hash: BlockHash,
mortality_period: Option<u32>,
) -> Self {
mortality_period
.map(|mortality_period| TransactionEra::Mortal(best_block_number, best_block_hash, mortality_period))
.map(|mortality_period| {
TransactionEra::Mortal(best_block_number, best_block_hash, mortality_period)
})
.unwrap_or(TransactionEra::Immortal)
}
@@ -169,9 +178,8 @@ impl<BlockNumber: Copy + Into<u64>, BlockHash: Copy> TransactionEra<BlockNumber,
pub fn frame_era(&self) -> sp_runtime::generic::Era {
match *self {
TransactionEra::Immortal => sp_runtime::generic::Era::immortal(),
TransactionEra::Mortal(header_number, _, period) => {
sp_runtime::generic::Era::mortal(period as _, header_number.into())
}
TransactionEra::Mortal(header_number, _, period) =>
sp_runtime::generic::Era::mortal(period as _, header_number.into()),
}
}
@@ -184,25 +192,40 @@ impl<BlockNumber: Copy + Into<u64>, BlockHash: Copy> TransactionEra<BlockNumber,
}
}
/// This is a copypaste of the `frame_support::storage::generator::StorageMap::storage_map_final_key`
/// for `Blake2_128Concat` maps.
/// This is a copypaste of the
/// `frame_support::storage::generator::StorageMap::storage_map_final_key` for `Blake2_128Concat`
/// maps.
///
/// We're using it because to call `storage_map_final_key` directly, we need access to the runtime
/// and pallet instance, which (sometimes) is impossible.
pub fn storage_map_final_key_blake2_128concat(pallet_prefix: &str, map_name: &str, key: &[u8]) -> StorageKey {
storage_map_final_key_identity(pallet_prefix, map_name, &frame_support::Blake2_128Concat::hash(key))
pub fn storage_map_final_key_blake2_128concat(
pallet_prefix: &str,
map_name: &str,
key: &[u8],
) -> StorageKey {
storage_map_final_key_identity(
pallet_prefix,
map_name,
&frame_support::Blake2_128Concat::hash(key),
)
}
/// This is a copypaste of the `frame_support::storage::generator::StorageMap::storage_map_final_key`
/// for `Identity` maps.
/// This is a copypaste of the
/// `frame_support::storage::generator::StorageMap::storage_map_final_key` for `Identity` maps.
///
/// We're using it because to call `storage_map_final_key` directly, we need access to the runtime
/// and pallet instance, which (sometimes) is impossible.
pub fn storage_map_final_key_identity(pallet_prefix: &str, map_name: &str, key_hashed: &[u8]) -> StorageKey {
pub fn storage_map_final_key_identity(
pallet_prefix: &str,
map_name: &str,
key_hashed: &[u8],
) -> StorageKey {
let pallet_prefix_hashed = frame_support::Twox128::hash(pallet_prefix.as_bytes());
let storage_prefix_hashed = frame_support::Twox128::hash(map_name.as_bytes());
let mut final_key = Vec::with_capacity(pallet_prefix_hashed.len() + storage_prefix_hashed.len() + key_hashed.len());
let mut final_key = Vec::with_capacity(
pallet_prefix_hashed.len() + storage_prefix_hashed.len() + key_hashed.len(),
);
final_key.extend_from_slice(&pallet_prefix_hashed[..]);
final_key.extend_from_slice(&storage_prefix_hashed[..]);
@@ -211,7 +234,8 @@ pub fn storage_map_final_key_identity(pallet_prefix: &str, map_name: &str, key_h
StorageKey(final_key)
}
/// This is how a storage key of storage parameter (`parameter_types! { storage Param: bool = false; }`) is computed.
/// This is how a storage key of storage parameter (`parameter_types! { storage Param: bool = false;
/// }`) is computed.
///
/// Copypaste from `frame_support::parameter_types` macro
pub fn storage_parameter_key(parameter_name: &str) -> StorageKey {
+2 -2
View File
@@ -50,7 +50,7 @@ pub struct MessageDispatchResult {
/// 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.
/// configuration supports pay-dispatch-fee-at-target-chain option and message sender has
/// enabled this option.
pub dispatch_fee_paid_during_dispatch: bool,
}
@@ -42,7 +42,7 @@ where
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);
return Err(Error::StorageRootMismatch)
}
let checker = StorageProofChecker { root, db };
@@ -52,7 +52,8 @@ where
/// 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)
read_trie_value::<Layout<H>, _>(&self.db, &self.root, key)
.map_err(|_| Error::StorageValueUnavailable)
}
}
@@ -97,7 +98,8 @@ pub mod tests {
let (root, proof) = craft_valid_storage_proof();
// check proof in runtime
let checker = <StorageProofChecker<sp_core::Blake2Hasher>>::new(root, proof.clone()).unwrap();
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));
+5 -6
View File
@@ -45,7 +45,8 @@ impl Account {
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.")
SecretKey::from_bytes(&bytes)
.expect("A static array of the correct length is a known good.")
}
pub fn pair(&self) -> Keypair {
@@ -57,7 +58,8 @@ impl Account {
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.")
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 {
@@ -79,10 +81,7 @@ pub fn voter_set() -> VoterSet<AuthorityId> {
/// 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()
test_keyring().iter().map(|(id, w)| (AuthorityId::from(*id), *w)).collect()
}
/// Get the corresponding identities from the keyring for the "standard" authority set.
+19 -43
View File
@@ -21,8 +21,7 @@
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_finality_grandpa::{AuthorityId, AuthoritySignature, AuthorityWeight, SetId};
use sp_runtime::traits::{Header as HeaderT, One, Zero};
use sp_std::prelude::*;
@@ -72,10 +71,7 @@ impl<H: HeaderT> Default for JustificationGeneratorParams<H> {
/// 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()
};
let params = JustificationGeneratorParams::<H> { header: header.clone(), ..Default::default() };
make_justification_for_header(params)
}
@@ -89,15 +85,11 @@ pub fn make_default_justification<H: HeaderT>(header: &H) -> GrandpaJustificatio
///
/// 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;
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![];
@@ -144,11 +136,7 @@ pub fn make_justification_for_header<H: HeaderT>(params: JustificationGeneratorP
GrandpaJustification {
round,
commit: finality_grandpa::Commit {
target_hash,
target_number,
precommits,
},
commit: finality_grandpa::Commit { target_hash, target_number, precommits },
votes_ancestries,
}
}
@@ -165,10 +153,7 @@ fn generate_chain<H: HeaderT>(fork_id: u32, depth: u32, ancestor: &H) -> Vec<H>
// 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()));
header.digest_mut().logs.push(sp_runtime::DigestItem::Other(fork_id.encode()));
headers.push(header);
}
@@ -183,29 +168,26 @@ pub fn signed_precommit<H: HeaderT>(
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 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 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
// 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,
}
finality_grandpa::SignedPrecommit { precommit, signature, id }
}
/// Get a header for testing.
@@ -213,13 +195,7 @@ pub fn signed_precommit<H: HeaderT>(
/// 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(),
)
H::new(num, Default::default(), Default::default(), Default::default(), Default::default())
};
let mut header = default(number);
+18 -14
View File
@@ -26,8 +26,8 @@ pub enum TokenSwapState {
/// The swap has been started using the `start_claim` call, but we have no proof that it has
/// happened at the Bridged chain.
Started,
/// The swap has happened at the Bridged chain and may be claimed by the Bridged chain party using
/// the `claim_swap` call.
/// The swap has happened at the Bridged chain and may be claimed by the Bridged chain party
/// using the `claim_swap` call.
Confirmed,
/// The swap has failed at the Bridged chain and This chain party may cancel it using the
/// `cancel_swap` call.
@@ -43,19 +43,20 @@ pub enum TokenSwapType<ThisBlockNumber> {
/// The `target_account_at_bridged_chain` is temporary and only have funds for single swap.
///
/// ***WARNING**: if `target_account_at_bridged_chain` still exists after the swap has been
/// completed (either by claiming or canceling), the `source_account_at_this_chain` will be able
/// to restart the swap again and repeat the swap until `target_account_at_bridged_chain` depletes.
/// completed (either by claiming or canceling), the `source_account_at_this_chain` will be
/// able to restart the swap again and repeat the swap until `target_account_at_bridged_chain`
/// depletes.
TemporaryTargetAccountAtBridgedChain,
/// This swap type prevents `source_account_at_this_chain` from restarting the swap after it has
/// been completed. There are two consequences:
/// This swap type prevents `source_account_at_this_chain` from restarting the swap after it
/// has been completed. There are two consequences:
///
/// 1) the `source_account_at_this_chain` won't be able to call `start_swap` after given <ThisBlockNumber>;
/// 2) the `target_account_at_bridged_chain` won't be able to call `claim_swap` (over the bridge) before
/// block `<ThisBlockNumber + 1>`.
/// 1) the `source_account_at_this_chain` won't be able to call `start_swap` after given
/// <ThisBlockNumber>; 2) the `target_account_at_bridged_chain` won't be able to call
/// `claim_swap` (over the bridge) before block `<ThisBlockNumber + 1>`.
///
/// The second element is the nonce of the swap. You must care about its uniqueness if you're
/// planning to perform another swap with exactly the same parameters (i.e. same amount, same accounts,
/// same `ThisBlockNumber`) to avoid collisions.
/// planning to perform another swap with exactly the same parameters (i.e. same amount, same
/// accounts, same `ThisBlockNumber`) to avoid collisions.
LockClaimUntilBlock(ThisBlockNumber, U256),
}
@@ -64,9 +65,11 @@ pub enum TokenSwapType<ThisBlockNumber> {
///
/// **IMPORTANT NOTE**: this structure is always the same during single token swap. So even
/// when chain changes, the meaning of This and Bridged are still used to point to the same chains.
/// This chain is always the chain where swap has been started. And the Bridged chain is the other chain.
/// This chain is always the chain where swap has been started. And the Bridged chain is the other
/// chain.
#[derive(Encode, Decode, Clone, RuntimeDebug, PartialEq, Eq)]
pub struct TokenSwap<ThisBlockNumber, ThisBalance, ThisAccountId, BridgedBalance, BridgedAccountId> {
pub struct TokenSwap<ThisBlockNumber, ThisBalance, ThisAccountId, BridgedBalance, BridgedAccountId>
{
/// The type of the swap.
pub swap_type: TokenSwapType<ThisBlockNumber>,
/// This chain balance to be swapped with `target_balance_at_bridged_chain`.
@@ -75,6 +78,7 @@ pub struct TokenSwap<ThisBlockNumber, ThisBalance, ThisAccountId, BridgedBalance
pub source_account_at_this_chain: ThisAccountId,
/// Bridged chain balance to be swapped with `source_balance_at_this_chain`.
pub target_balance_at_bridged_chain: BridgedBalance,
/// Account id of the party acting at the Bridged chain and owning the `target_balance_at_bridged_chain`.
/// Account id of the party acting at the Bridged chain and owning the
/// `target_balance_at_bridged_chain`.
pub target_account_at_bridged_chain: BridgedAccountId,
}