// Copyright 2019-2020 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 .
//! Runtime module which takes care of dispatching messages received over the bridge.
//!
//! The messages are interpreted directly as runtime `Call`. We attempt to decode
//! them and then dispatch as usual. To prevent compatibility issues, the Calls have
//! to include a `spec_version`. This will be checked before dispatch. In the case of
//! a succesful dispatch an event is emitted.
#![cfg_attr(not(feature = "std"), no_std)]
#![warn(missing_docs)]
use bp_message_dispatch::{MessageDispatch, Weight};
use bp_runtime::{derive_account_id, InstanceId, Size, SourceAccount};
use codec::{Decode, Encode};
use frame_support::{
decl_event, decl_module, decl_storage,
dispatch::{Dispatchable, Parameter},
ensure,
traits::{Filter, Get},
weights::{extract_actual_weight, GetDispatchInfo},
RuntimeDebug,
};
use frame_system::RawOrigin;
use sp_runtime::{
traits::{BadOrigin, Convert, IdentifyAccount, MaybeDisplay, MaybeSerializeDeserialize, Member, Verify},
DispatchResult,
};
use sp_std::{fmt::Debug, marker::PhantomData, prelude::*};
/// Spec version type.
pub type SpecVersion = u32;
/// 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 {
/// 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 `(, 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 call-dispatch module.
#[derive(RuntimeDebug, Encode, Decode, Clone, PartialEq, Eq)]
pub struct MessagePayload {
/// 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,
/// The call itself.
pub call: Call,
}
impl Size
for MessagePayload>
{
fn size_hint(&self) -> u32 {
self.call.len() as _
}
}
/// The module configuration trait.
pub trait Config: frame_system::Config {
/// The overarching event type.
type Event: From> + Into<::Event>;
/// Id of the message. Whenever message is passed to the dispatch module, it emits
/// event with this id + dispatch result. Could be e.g. (LaneId, MessageNonce) if
/// it comes from message-lane module.
type MessageId: Parameter;
/// Type of account ID on source chain.
type SourceChainAccountId: Parameter + Member + MaybeSerializeDeserialize + Debug + MaybeDisplay + Ord + Default;
/// Type of account public key on target chain.
type TargetChainAccountPublic: Parameter + IdentifyAccount;
/// Type of signature that may prove that the message has been signed by
/// owner of `TargetChainAccountPublic`.
type TargetChainSignature: Parameter + Verify;
/// The overarching dispatch call type.
type Call: Parameter
+ GetDispatchInfo
+ Dispatchable<
Origin = ::Origin,
PostInfo = frame_support::dispatch::PostDispatchInfo,
>;
/// Pre-dispatch filter for incoming calls.
///
/// The pallet will filter all incoming calls right before they're dispatched. If this filter
/// rejects the call, special event (`Event::MessageCallRejected`) is emitted.
type CallFilter: Filter<>::Call>;
/// The type that is used to wrap the `Self::Call` when it is moved over bridge.
///
/// The idea behind this is to avoid `Call` conversion/decoding until we'll be sure
/// that all other stuff (like `spec_version`) is ok. If we would try to decode
/// `Call` which has been encoded using previous `spec_version`, then we might end
/// up with decoding error, instead of `MessageVersionSpecMismatch`.
type EncodedCall: Decode + Encode + Into>::Call, ()>>;
/// A type which can be turned into an AccountId from a 256-bit hash.
///
/// Used when deriving target chain AccountIds from source chain AccountIds.
type AccountIdConverter: sp_runtime::traits::Convert;
}
decl_storage! {
trait Store for Module, I: Instance = DefaultInstance> as CallDispatch {}
}
decl_event!(
pub enum Event where
>::MessageId
{
/// Message has been rejected before reaching dispatch.
MessageRejected(InstanceId, MessageId),
/// Message has been rejected by dispatcher because of spec version mismatch.
/// Last two arguments are: expected and passed spec version.
MessageVersionSpecMismatch(InstanceId, MessageId, SpecVersion, SpecVersion),
/// Message has been rejected by dispatcher because of weight mismatch.
/// Last two arguments are: expected and passed call weight.
MessageWeightMismatch(InstanceId, MessageId, Weight, Weight),
/// Message signature mismatch.
MessageSignatureMismatch(InstanceId, MessageId),
/// Message has been dispatched with given result.
MessageDispatched(InstanceId, MessageId, DispatchResult),
/// We have failed to decode Call from the message.
MessageCallDecodeFailed(InstanceId, MessageId),
/// The call from the message has been rejected by the call filter.
MessageCallRejected(InstanceId, MessageId),
/// Phantom member, never used. Needed to handle multiple pallet instances.
_Dummy(PhantomData),
}
);
decl_module! {
/// Call Dispatch FRAME Pallet.
pub struct Module, I: Instance = DefaultInstance> for enum Call where origin: T::Origin {
/// Deposit one of this module's events by using the default implementation.
fn deposit_event() = default;
}
}
impl, I: Instance> MessageDispatch for Module {
type Message =
MessagePayload;
fn dispatch_weight(message: &Self::Message) -> Weight {
message.weight
}
fn dispatch(bridge: InstanceId, id: T::MessageId, message: Result) {
// emit special even if message has been rejected by external component
let message = match message {
Ok(message) => message,
Err(_) => {
log::trace!("Message {:?}/{:?}: rejected before actual dispatch", bridge, id);
Self::deposit_event(RawEvent::MessageRejected(bridge, id));
return;
}
};
// verify spec version
// (we want it to be the same, because otherwise we may decode Call improperly)
let expected_version = ::Version::get().spec_version;
if message.spec_version != expected_version {
log::trace!(
"Message {:?}/{:?}: spec_version mismatch. Expected {:?}, got {:?}",
bridge,
id,
expected_version,
message.spec_version,
);
Self::deposit_event(RawEvent::MessageVersionSpecMismatch(
bridge,
id,
expected_version,
message.spec_version,
));
return;
}
// now that we have spec version checked, let's decode the call
let call = match message.call.into() {
Ok(call) => call,
Err(_) => {
log::trace!("Failed to decode Call from message {:?}/{:?}", bridge, id,);
Self::deposit_event(RawEvent::MessageCallDecodeFailed(bridge, id));
return;
}
};
// prepare dispatch origin
let origin_account = match message.origin {
CallOrigin::SourceRoot => {
let hex_id = derive_account_id::(bridge, SourceAccount::Root);
let target_id = T::AccountIdConverter::convert(hex_id);
log::trace!("Root Account: {:?}", &target_id);
target_id
}
CallOrigin::TargetAccount(source_account_id, target_public, target_signature) => {
let digest = account_ownership_digest(&call, source_account_id, message.spec_version, bridge);
let target_account = target_public.into_account();
if !target_signature.verify(&digest[..], &target_account) {
log::trace!(
"Message {:?}/{:?}: origin proof is invalid. Expected account: {:?} from signature: {:?}",
bridge,
id,
target_account,
target_signature,
);
Self::deposit_event(RawEvent::MessageSignatureMismatch(bridge, id));
return;
}
log::trace!("Target Account: {:?}", &target_account);
target_account
}
CallOrigin::SourceAccount(source_account_id) => {
let hex_id = derive_account_id(bridge, SourceAccount::Account(source_account_id));
let target_id = T::AccountIdConverter::convert(hex_id);
log::trace!("Source Account: {:?}", &target_id);
target_id
}
};
// filter the call
if !T::CallFilter::filter(&call) {
log::trace!(
"Message {:?}/{:?}: the call ({:?}) is rejected by filter",
bridge,
id,
call,
);
Self::deposit_event(RawEvent::MessageCallRejected(bridge, id));
return;
}
// verify weight
// (we want passed weight to be at least equal to pre-dispatch weight of the call
// because otherwise Calls may be dispatched at lower price)
let dispatch_info = call.get_dispatch_info();
let expected_weight = dispatch_info.weight;
if message.weight < expected_weight {
log::trace!(
"Message {:?}/{:?}: passed weight is too low. Expected at least {:?}, got {:?}",
bridge,
id,
expected_weight,
message.weight,
);
Self::deposit_event(RawEvent::MessageWeightMismatch(
bridge,
id,
expected_weight,
message.weight,
));
return;
}
// finally dispatch message
let origin = RawOrigin::Signed(origin_account).into();
log::trace!("Message being dispatched is: {:?}", &call);
let dispatch_result = call.dispatch(origin);
let actual_call_weight = extract_actual_weight(&dispatch_result, &dispatch_info);
log::trace!(
"Message {:?}/{:?} has been dispatched. Weight: {} of {}. Result: {:?}",
bridge,
id,
actual_call_weight,
message.weight,
dispatch_result,
);
Self::deposit_event(RawEvent::MessageDispatched(
bridge,
id,
dispatch_result.map(drop).map_err(|e| e.error),
));
}
}
/// Check if the message is allowed to be dispatched on the target chain given the sender's origin
/// on the source chain.
///
/// For example, if a message is sent from a "regular" account on the source chain it will not be
/// allowed to be dispatched as Root on the target chain. This is a useful check to do on the source
/// chain _before_ sending a message whose dispatch will be rejected on the target chain.
pub fn verify_message_origin(
sender_origin: &RawOrigin,
message: &MessagePayload,
) -> Result