Skip to main content

pallet_messenger/
extensions.rs

1//! Extensions for unsigned general extrinsics
2
3#[cfg(feature = "runtime-benchmarks")]
4pub mod benchmarking_between_domains;
5#[cfg(feature = "runtime-benchmarks")]
6pub mod benchmarking_from_consensus;
7#[cfg(feature = "runtime-benchmarks")]
8pub mod benchmarking_from_domains;
9pub mod weights;
10mod weights_from_consensus;
11mod weights_from_domains;
12
13pub use crate::extensions::weights::{FromConsensusWeightInfo, FromDomainWeightInfo};
14pub use crate::extensions::weights_from_consensus::WeightInfo as WeightsFromConsensus;
15pub use crate::extensions::weights_from_domains::WeightInfo as WeightsFromDomains;
16use crate::pallet::Call as MessengerCall;
17use crate::{
18    Call, Config, ExtensionWeightInfo, Origin, Pallet as Messenger, ValidatedRelayMessage,
19    XDM_TRANSACTION_LONGEVITY,
20};
21use core::cmp::Ordering;
22use frame_support::pallet_prelude::{PhantomData, TypeInfo, Weight};
23use frame_system::pallet_prelude::RuntimeCallFor;
24use parity_scale_codec::{Decode, DecodeWithMemTracking, Encode};
25use scale_info::prelude::fmt;
26use sp_messenger::MAX_FUTURE_ALLOWED_NONCES;
27use sp_messenger::messages::{Message, Nonce, Proof};
28use sp_runtime::DispatchResult;
29use sp_runtime::traits::{
30    AsSystemOriginSigner, DispatchInfoOf, DispatchOriginOf, Dispatchable, Implication,
31    PostDispatchInfoOf, TransactionExtension, ValidateResult,
32};
33use sp_runtime::transaction_validity::{
34    InvalidTransaction, TransactionSource, TransactionValidityError, ValidTransaction,
35    ValidTransactionBuilder,
36};
37use sp_subspace_mmr::MmrProofVerifier;
38
39/// Trait to convert Runtime call to possible Messenger call.
40pub trait MaybeMessengerCall<Runtime>
41where
42    Runtime: Config,
43{
44    fn maybe_messenger_call(&self) -> Option<&MessengerCall<Runtime>>;
45}
46
47/// Data passed from validate to prepare.
48#[derive(Debug)]
49pub enum Val<T: Config + fmt::Debug> {
50    /// No validation data
51    None,
52    /// Validated data
53    ValidatedRelayMessage(ValidatedRelayMessage<T>),
54}
55
56/// Data passed from prepare to post_dispatch.
57#[derive(Debug)]
58pub enum Pre {
59    Refund(Weight),
60}
61
62/// Extensions for pallet-messenger unsigned extrinsics.
63#[derive(Encode, Decode, Clone, Eq, PartialEq, TypeInfo, DecodeWithMemTracking)]
64pub struct MessengerExtension<Runtime>(PhantomData<Runtime>);
65
66impl<Runtime> MessengerExtension<Runtime> {
67    pub fn new() -> Self {
68        Self(PhantomData)
69    }
70}
71
72impl<Runtime> Default for MessengerExtension<Runtime> {
73    fn default() -> Self {
74        Self::new()
75    }
76}
77
78impl<T: Config> fmt::Debug for MessengerExtension<T> {
79    #[cfg(feature = "std")]
80    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81        write!(f, "MessengerExtension",)
82    }
83
84    #[cfg(not(feature = "std"))]
85    fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result {
86        Ok(())
87    }
88}
89
90impl<Runtime> MessengerExtension<Runtime>
91where
92    Runtime: Config + scale_info::TypeInfo + fmt::Debug + Send + Sync,
93{
94    fn check_future_nonce_and_add_requires(
95        mut valid_tx_builder: ValidTransactionBuilder,
96        validated_relay_message: &ValidatedRelayMessage<Runtime>,
97    ) -> Result<ValidTransactionBuilder, TransactionValidityError> {
98        let Message {
99            dst_chain_id,
100            channel_id,
101            nonce: msg_nonce,
102            ..
103        } = &validated_relay_message.message;
104
105        let next_nonce = validated_relay_message.next_nonce;
106        // Only add the requires tag if the msg nonce is in future
107        if *msg_nonce > next_nonce {
108            let max_future_nonce = next_nonce.saturating_add(MAX_FUTURE_ALLOWED_NONCES.into());
109            if *msg_nonce > max_future_nonce {
110                return Err(InvalidTransaction::Custom(
111                    crate::verification_errors::IN_FUTURE_NONCE,
112                )
113                .into());
114            }
115
116            valid_tx_builder =
117                valid_tx_builder.and_requires((dst_chain_id, channel_id, msg_nonce - Nonce::one()));
118        };
119
120        Ok(valid_tx_builder)
121    }
122
123    fn do_validate(
124        call: &MessengerCall<Runtime>,
125    ) -> Result<(ValidTransaction, ValidatedRelayMessage<Runtime>), TransactionValidityError> {
126        match call {
127            Call::relay_message { msg: xdm } => {
128                let consensus_state_root =
129                    Runtime::MmrProofVerifier::verify_proof_and_extract_leaf(
130                        xdm.proof.consensus_mmr_proof(),
131                    )
132                    .ok_or(InvalidTransaction::BadProof)?
133                    .state_root();
134
135                let validated_message =
136                    Messenger::<Runtime>::validate_relay_message(xdm, consensus_state_root)?;
137
138                let Message {
139                    dst_chain_id,
140                    channel_id,
141                    nonce: msg_nonce,
142                    ..
143                } = &validated_message.message;
144
145                let valid_tx_builder = Self::check_future_nonce_and_add_requires(
146                    ValidTransaction::with_tag_prefix("MessengerInbox"),
147                    &validated_message,
148                )?;
149
150                let validity = valid_tx_builder
151                    // XDM have a bit higher priority than normal extrinsic but must less than
152                    // fraud proof
153                    .priority(1)
154                    .longevity(XDM_TRANSACTION_LONGEVITY)
155                    .and_provides((dst_chain_id, channel_id, msg_nonce))
156                    .propagate(true)
157                    .build()?;
158
159                Ok((validity, validated_message))
160            }
161            Call::relay_message_response { msg: xdm } => {
162                let consensus_state_root =
163                    Runtime::MmrProofVerifier::verify_proof_and_extract_leaf(
164                        xdm.proof.consensus_mmr_proof(),
165                    )
166                    .ok_or(InvalidTransaction::BadProof)?
167                    .state_root();
168
169                let validated_message = Messenger::<Runtime>::validate_relay_message_response(
170                    xdm,
171                    consensus_state_root,
172                )?;
173
174                let Message {
175                    dst_chain_id,
176                    channel_id,
177                    nonce: msg_nonce,
178                    ..
179                } = &validated_message.message;
180
181                let valid_tx_builder = Self::check_future_nonce_and_add_requires(
182                    ValidTransaction::with_tag_prefix("MessengerOutboxResponse"),
183                    &validated_message,
184                )?;
185
186                let validity = valid_tx_builder
187                    // XDM have a bit higher priority than normal extrinsic but must less than
188                    // fraud proof
189                    .priority(1)
190                    .longevity(XDM_TRANSACTION_LONGEVITY)
191                    .and_provides((dst_chain_id, channel_id, msg_nonce))
192                    .propagate(true)
193                    .build()?;
194
195                Ok((validity, validated_message))
196            }
197            _ => Err(InvalidTransaction::Call.into()),
198        }
199    }
200
201    fn do_prepare(
202        call: &MessengerCall<Runtime>,
203        val: ValidatedRelayMessage<Runtime>,
204    ) -> Result<Pre, TransactionValidityError> {
205        let ValidatedRelayMessage {
206            message,
207            should_init_channel,
208            next_nonce,
209        } = val;
210
211        // Reject in future message
212        if message.nonce.cmp(&next_nonce) == Ordering::Greater {
213            return Err(InvalidTransaction::Future.into());
214        }
215
216        let pre = match call {
217            Call::relay_message { msg } => {
218                Messenger::<Runtime>::pre_dispatch_relay_message(message, should_init_channel)?;
219                if should_init_channel {
220                    // if this is a channel init,
221                    // there is no further refund of weight
222                    Pre::Refund(Weight::zero())
223                } else {
224                    match msg.proof {
225                        Proof::Consensus { .. } => Pre::Refund(Self::refund_weight_for_consensus()),
226                        Proof::Domain { .. } => Pre::Refund(Self::refund_weight_for_domains()),
227                    }
228                }
229            }
230            Call::relay_message_response { .. } => {
231                Messenger::<Runtime>::pre_dispatch_relay_message_response(message)?;
232                // no refund for relay response message.
233                Pre::Refund(Weight::zero())
234            }
235            _ => return Err(InvalidTransaction::Call.into()),
236        };
237
238        Ok(pre)
239    }
240
241    fn do_calculate_weight(call: &RuntimeCallFor<Runtime>) -> Weight
242    where
243        RuntimeCallFor<Runtime>: MaybeMessengerCall<Runtime>,
244        Runtime: Config,
245    {
246        let messenger_call = match call.maybe_messenger_call() {
247            Some(messenger_call) => messenger_call,
248            None => return Weight::zero(),
249        };
250
251        let (dst_chain_id, verification_weight) = match messenger_call {
252            Call::relay_message { msg } => (
253                msg.dst_chain_id,
254                match msg.proof {
255                    Proof::Consensus { .. } => {
256                        Runtime::ExtensionWeightInfo::from_consensus_relay_message().max(
257                            Runtime::ExtensionWeightInfo::from_consensus_relay_message_channel_open(
258                            ),
259                        )
260                    }
261                    Proof::Domain { .. } => {
262                        Runtime::ExtensionWeightInfo::from_domains_relay_message_channel_open()
263                            .max(Runtime::ExtensionWeightInfo::from_domains_relay_message())
264                    }
265                },
266            ),
267            Call::relay_message_response { msg } => (
268                msg.dst_chain_id,
269                match msg.proof {
270                    Proof::Consensus { .. } => {
271                        Runtime::ExtensionWeightInfo::from_consensus_relay_message_response()
272                    }
273                    Proof::Domain { .. } => {
274                        Runtime::ExtensionWeightInfo::from_domains_relay_message_response()
275                    }
276                },
277            ),
278            _ => return Weight::zero(),
279        };
280
281        let mmr_proof_weight = if dst_chain_id.is_consensus_chain() {
282            Runtime::ExtensionWeightInfo::mmr_proof_verification_on_consensus()
283        } else {
284            Runtime::ExtensionWeightInfo::mmr_proof_verification_on_domain()
285        };
286
287        mmr_proof_weight.saturating_add(verification_weight)
288    }
289
290    fn refund_weight_for_consensus() -> Weight {
291        let min = Runtime::ExtensionWeightInfo::from_consensus_relay_message_channel_open()
292            .min(Runtime::ExtensionWeightInfo::from_consensus_relay_message());
293        let max = Runtime::ExtensionWeightInfo::from_consensus_relay_message_channel_open()
294            .max(Runtime::ExtensionWeightInfo::from_consensus_relay_message());
295        max.saturating_sub(min)
296    }
297
298    fn refund_weight_for_domains() -> Weight {
299        let min = Runtime::ExtensionWeightInfo::from_domains_relay_message_channel_open()
300            .min(Runtime::ExtensionWeightInfo::from_domains_relay_message());
301        let max = Runtime::ExtensionWeightInfo::from_domains_relay_message_channel_open()
302            .max(Runtime::ExtensionWeightInfo::from_domains_relay_message());
303        max.saturating_sub(min)
304    }
305}
306
307impl<Runtime> TransactionExtension<RuntimeCallFor<Runtime>> for MessengerExtension<Runtime>
308where
309    Runtime: Config + scale_info::TypeInfo + fmt::Debug + Send + Sync,
310    <RuntimeCallFor<Runtime> as Dispatchable>::RuntimeOrigin:
311        AsSystemOriginSigner<<Runtime as frame_system::Config>::AccountId> + From<Origin> + Clone,
312    RuntimeCallFor<Runtime>: MaybeMessengerCall<Runtime>,
313{
314    const IDENTIFIER: &'static str = "MessengerExtension";
315    type Implicit = ();
316    type Val = Val<Runtime>;
317    type Pre = Pre;
318
319    fn weight(&self, call: &RuntimeCallFor<Runtime>) -> Weight {
320        Self::do_calculate_weight(call)
321    }
322
323    fn validate(
324        &self,
325        origin: DispatchOriginOf<RuntimeCallFor<Runtime>>,
326        call: &RuntimeCallFor<Runtime>,
327        _info: &DispatchInfoOf<RuntimeCallFor<Runtime>>,
328        _len: usize,
329        _self_implicit: Self::Implicit,
330        _inherited_implication: &impl Implication,
331        _source: TransactionSource,
332    ) -> ValidateResult<Self::Val, RuntimeCallFor<Runtime>> {
333        // we only care about unsigned calls
334        if origin.as_system_origin_signer().is_some() {
335            return Ok((ValidTransaction::default(), Val::None, origin));
336        };
337
338        let messenger_call = match call.maybe_messenger_call() {
339            Some(messenger_call) => messenger_call,
340            None => return Ok((ValidTransaction::default(), Val::None, origin)),
341        };
342
343        let (validity, validated_relay_message) = Self::do_validate(messenger_call)?;
344        Ok((
345            validity,
346            Val::ValidatedRelayMessage(validated_relay_message),
347            Origin::ValidatedUnsigned.into(),
348        ))
349    }
350
351    fn prepare(
352        self,
353        val: Self::Val,
354        _origin: &DispatchOriginOf<RuntimeCallFor<Runtime>>,
355        call: &RuntimeCallFor<Runtime>,
356        _info: &DispatchInfoOf<RuntimeCallFor<Runtime>>,
357        _len: usize,
358    ) -> Result<Self::Pre, TransactionValidityError> {
359        match (call.maybe_messenger_call(), val) {
360            // prepare if this is a messenger call and has been validated
361            (Some(messenger_call), Val::ValidatedRelayMessage(validated_relay_message)) => {
362                Self::do_prepare(messenger_call, validated_relay_message)
363            }
364            // return Ok for the rest of the call types and nothing to refund here as
365            // non XDM calls will have zero weight from this extension.
366            (_, _) => Ok(Pre::Refund(Weight::zero())),
367        }
368    }
369
370    fn post_dispatch_details(
371        pre: Self::Pre,
372        _info: &DispatchInfoOf<RuntimeCallFor<Runtime>>,
373        _post_info: &PostDispatchInfoOf<RuntimeCallFor<Runtime>>,
374        _len: usize,
375        _result: &DispatchResult,
376    ) -> Result<Weight, TransactionValidityError> {
377        let Pre::Refund(weight) = pre;
378        Ok(weight)
379    }
380}
381
382/// Extensions for pallet-messenger unsigned extrinsics with trusted MMR verification.
383#[derive(Encode, Decode, Clone, Eq, PartialEq, TypeInfo, DecodeWithMemTracking)]
384pub struct MessengerTrustedMmrExtension<Runtime>(PhantomData<Runtime>);
385
386impl<Runtime> MessengerTrustedMmrExtension<Runtime> {
387    pub fn new() -> Self {
388        Self(PhantomData)
389    }
390}
391
392impl<Runtime> Default for MessengerTrustedMmrExtension<Runtime> {
393    fn default() -> Self {
394        Self::new()
395    }
396}
397
398impl<T: Config> fmt::Debug for MessengerTrustedMmrExtension<T> {
399    #[cfg(feature = "std")]
400    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
401        write!(f, "MessengerTrustedMmrExtension",)
402    }
403
404    #[cfg(not(feature = "std"))]
405    fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result {
406        Ok(())
407    }
408}
409
410impl<Runtime> MessengerTrustedMmrExtension<Runtime>
411where
412    Runtime: Config + scale_info::TypeInfo + fmt::Debug + Send + Sync,
413{
414    fn do_validate(
415        call: &MessengerCall<Runtime>,
416    ) -> Result<(ValidTransaction, ValidatedRelayMessage<Runtime>), TransactionValidityError> {
417        match call {
418            Call::relay_message { msg: xdm } => {
419                let consensus_state_root =
420                    Runtime::MmrProofVerifier::extract_leaf_without_verifying(
421                        xdm.proof.consensus_mmr_proof(),
422                    )
423                    .ok_or(InvalidTransaction::BadProof)?
424                    .state_root();
425
426                let validated_relay_message =
427                    Messenger::<Runtime>::validate_relay_message(xdm, consensus_state_root)?;
428
429                Ok((ValidTransaction::default(), validated_relay_message))
430            }
431            Call::relay_message_response { msg: xdm } => {
432                let consensus_state_root =
433                    Runtime::MmrProofVerifier::extract_leaf_without_verifying(
434                        xdm.proof.consensus_mmr_proof(),
435                    )
436                    .ok_or(InvalidTransaction::BadProof)?
437                    .state_root();
438
439                let validated_relay_message =
440                    Messenger::<Runtime>::validate_relay_message_response(
441                        xdm,
442                        consensus_state_root,
443                    )?;
444
445                Ok((ValidTransaction::default(), validated_relay_message))
446            }
447            _ => Err(InvalidTransaction::Call.into()),
448        }
449    }
450}
451
452impl<Runtime> TransactionExtension<RuntimeCallFor<Runtime>>
453    for MessengerTrustedMmrExtension<Runtime>
454where
455    Runtime: Config + scale_info::TypeInfo + fmt::Debug + Send + Sync,
456    <RuntimeCallFor<Runtime> as Dispatchable>::RuntimeOrigin:
457        AsSystemOriginSigner<<Runtime as frame_system::Config>::AccountId> + From<Origin> + Clone,
458    RuntimeCallFor<Runtime>: MaybeMessengerCall<Runtime>,
459{
460    const IDENTIFIER: &'static str = "MessengerTrustedMmrExtension";
461    type Implicit = ();
462    type Val = Val<Runtime>;
463    type Pre = Pre;
464
465    fn weight(&self, call: &RuntimeCallFor<Runtime>) -> Weight {
466        MessengerExtension::<Runtime>::do_calculate_weight(call)
467    }
468
469    fn validate(
470        &self,
471        origin: DispatchOriginOf<RuntimeCallFor<Runtime>>,
472        call: &RuntimeCallFor<Runtime>,
473        _info: &DispatchInfoOf<RuntimeCallFor<Runtime>>,
474        _len: usize,
475        _self_implicit: Self::Implicit,
476        _inherited_implication: &impl Implication,
477        _source: TransactionSource,
478    ) -> ValidateResult<Self::Val, RuntimeCallFor<Runtime>> {
479        // we only care about unsigned calls
480        if origin.as_system_origin_signer().is_some() {
481            return Ok((ValidTransaction::default(), Val::None, origin));
482        };
483
484        let messenger_call = match call.maybe_messenger_call() {
485            Some(messenger_call) => messenger_call,
486            None => return Ok((ValidTransaction::default(), Val::None, origin)),
487        };
488
489        let (validity, validated_relay_message) = Self::do_validate(messenger_call)?;
490        Ok((
491            validity,
492            Val::ValidatedRelayMessage(validated_relay_message),
493            Origin::ValidatedUnsigned.into(),
494        ))
495    }
496
497    fn prepare(
498        self,
499        val: Self::Val,
500        _origin: &DispatchOriginOf<RuntimeCallFor<Runtime>>,
501        call: &RuntimeCallFor<Runtime>,
502        _info: &DispatchInfoOf<RuntimeCallFor<Runtime>>,
503        _len: usize,
504    ) -> Result<Self::Pre, TransactionValidityError> {
505        match (call.maybe_messenger_call(), val) {
506            // prepare if this is a messenger call and has been validated
507            (Some(messenger_call), Val::ValidatedRelayMessage(validated_relay_message)) => {
508                MessengerExtension::<Runtime>::do_prepare(messenger_call, validated_relay_message)
509            }
510            // return Ok for the rest of the call types
511            (_, _) => Ok(Pre::Refund(Weight::zero())),
512        }
513    }
514
515    fn post_dispatch_details(
516        pre: Self::Pre,
517        _info: &DispatchInfoOf<RuntimeCallFor<Runtime>>,
518        _post_info: &PostDispatchInfoOf<RuntimeCallFor<Runtime>>,
519        _len: usize,
520        _result: &DispatchResult,
521    ) -> Result<Weight, TransactionValidityError> {
522        let Pre::Refund(weight) = pre;
523        Ok(weight)
524    }
525}