pallet_messenger/
extensions.rs

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
//! Extensions for unsigned general extrinsics

use crate::pallet::Call as MessengerCall;
use crate::{
    Call, Config, Origin, Pallet as Messenger, ValidatedRelayMessage, XDM_TRANSACTION_LONGEVITY,
};
use core::cmp::Ordering;
use frame_support::pallet_prelude::{PhantomData, TypeInfo};
use frame_support::RuntimeDebugNoBound;
use frame_system::pallet_prelude::RuntimeCallFor;
use parity_scale_codec::{Decode, Encode};
use scale_info::prelude::fmt;
use sp_messenger::messages::{Message, Nonce};
use sp_messenger::MAX_FUTURE_ALLOWED_NONCES;
use sp_runtime::impl_tx_ext_default;
use sp_runtime::traits::{
    AsSystemOriginSigner, DispatchInfoOf, DispatchOriginOf, Dispatchable, Implication,
    TransactionExtension, ValidateResult,
};
use sp_runtime::transaction_validity::{
    InvalidTransaction, TransactionSource, TransactionValidityError, ValidTransaction,
    ValidTransactionBuilder,
};
use sp_subspace_mmr::MmrProofVerifier;

/// Trait to convert Runtime call to possible Messenger call.
pub trait MaybeMessengerCall<Runtime>
where
    Runtime: Config,
{
    fn maybe_messenger_call(&self) -> Option<&MessengerCall<Runtime>>;
}

/// Data passed from validate to prepare.
#[derive(RuntimeDebugNoBound)]
pub enum Val<T: Config + fmt::Debug> {
    /// No validation data
    None,
    /// Validated data
    ValidatedRelayMessage(ValidatedRelayMessage<T>),
}

/// Extensions for pallet-messenger unsigned extrinsics.
#[derive(Encode, Decode, Clone, Eq, PartialEq, TypeInfo)]
pub struct MessengerExtension<Runtime>(PhantomData<Runtime>);

impl<Runtime> MessengerExtension<Runtime> {
    pub fn new() -> Self {
        Self(PhantomData)
    }
}

impl<Runtime> Default for MessengerExtension<Runtime> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T: Config> fmt::Debug for MessengerExtension<T> {
    #[cfg(feature = "std")]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "MessengerExtension",)
    }

    #[cfg(not(feature = "std"))]
    fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result {
        Ok(())
    }
}

impl<Runtime> MessengerExtension<Runtime>
where
    Runtime: Config + scale_info::TypeInfo + fmt::Debug + Send + Sync,
{
    fn check_future_nonce_and_add_requires(
        mut valid_tx_builder: ValidTransactionBuilder,
        validated_relay_message: &ValidatedRelayMessage<Runtime>,
    ) -> Result<ValidTransactionBuilder, TransactionValidityError> {
        let Message {
            dst_chain_id,
            channel_id,
            nonce: msg_nonce,
            ..
        } = &validated_relay_message.message;

        let next_nonce = validated_relay_message.next_nonce;
        // Only add the requires tag if the msg nonce is in future
        if *msg_nonce > next_nonce {
            let max_future_nonce = next_nonce.saturating_add(MAX_FUTURE_ALLOWED_NONCES.into());
            if *msg_nonce > max_future_nonce {
                return Err(InvalidTransaction::Custom(
                    crate::verification_errors::IN_FUTURE_NONCE,
                )
                .into());
            }

            valid_tx_builder =
                valid_tx_builder.and_requires((dst_chain_id, channel_id, msg_nonce - Nonce::one()));
        };

        Ok(valid_tx_builder)
    }

    fn do_validate(
        call: &MessengerCall<Runtime>,
    ) -> Result<(ValidTransaction, ValidatedRelayMessage<Runtime>), TransactionValidityError> {
        match call {
            Call::relay_message { msg: xdm } => {
                let consensus_state_root =
                    Runtime::MmrProofVerifier::verify_proof_and_extract_leaf(
                        xdm.proof.consensus_mmr_proof(),
                    )
                    .ok_or(InvalidTransaction::BadProof)?
                    .state_root();

                let validated_message =
                    Messenger::<Runtime>::validate_relay_message(xdm, consensus_state_root)?;

                let Message {
                    dst_chain_id,
                    channel_id,
                    nonce: msg_nonce,
                    ..
                } = &validated_message.message;

                let valid_tx_builder = Self::check_future_nonce_and_add_requires(
                    ValidTransaction::with_tag_prefix("MessengerInbox"),
                    &validated_message,
                )?;

                let validity = valid_tx_builder
                    // XDM have a bit higher priority than normal extrinsic but must less than
                    // fraud proof
                    .priority(1)
                    .longevity(XDM_TRANSACTION_LONGEVITY)
                    .and_provides((dst_chain_id, channel_id, msg_nonce))
                    .propagate(true)
                    .build()?;

                Ok((validity, validated_message))
            }
            Call::relay_message_response { msg: xdm } => {
                let consensus_state_root =
                    Runtime::MmrProofVerifier::verify_proof_and_extract_leaf(
                        xdm.proof.consensus_mmr_proof(),
                    )
                    .ok_or(InvalidTransaction::BadProof)?
                    .state_root();

                let validated_message = Messenger::<Runtime>::validate_relay_message_response(
                    xdm,
                    consensus_state_root,
                )?;

                let Message {
                    dst_chain_id,
                    channel_id,
                    nonce: msg_nonce,
                    ..
                } = &validated_message.message;

                let valid_tx_builder = Self::check_future_nonce_and_add_requires(
                    ValidTransaction::with_tag_prefix("MessengerOutboxResponse"),
                    &validated_message,
                )?;

                let validity = valid_tx_builder
                    // XDM have a bit higher priority than normal extrinsic but must less than
                    // fraud proof
                    .priority(1)
                    .longevity(XDM_TRANSACTION_LONGEVITY)
                    .and_provides((dst_chain_id, channel_id, msg_nonce))
                    .propagate(true)
                    .build()?;

                Ok((validity, validated_message))
            }
            _ => Err(InvalidTransaction::Call.into()),
        }
    }

    fn do_prepare(
        call: &MessengerCall<Runtime>,
        val: ValidatedRelayMessage<Runtime>,
    ) -> Result<(), TransactionValidityError> {
        let ValidatedRelayMessage {
            message,
            should_init_channel,
            next_nonce,
        } = val;

        // Reject in future message
        if message.nonce.cmp(&next_nonce) == Ordering::Greater {
            return Err(InvalidTransaction::Future.into());
        }

        match call {
            Call::relay_message { .. } => {
                Messenger::<Runtime>::pre_dispatch_relay_message(message, should_init_channel)
            }
            Call::relay_message_response { .. } => {
                Messenger::<Runtime>::pre_dispatch_relay_message_response(message)
            }
            _ => Err(InvalidTransaction::Call.into()),
        }
    }
}

impl<Runtime> TransactionExtension<RuntimeCallFor<Runtime>> for MessengerExtension<Runtime>
where
    Runtime: Config + scale_info::TypeInfo + fmt::Debug + Send + Sync,
    <RuntimeCallFor<Runtime> as Dispatchable>::RuntimeOrigin:
        AsSystemOriginSigner<<Runtime as frame_system::Config>::AccountId> + From<Origin> + Clone,
    RuntimeCallFor<Runtime>: MaybeMessengerCall<Runtime>,
{
    const IDENTIFIER: &'static str = "MessengerExtension";
    type Implicit = ();
    type Val = Val<Runtime>;
    type Pre = ();

    fn validate(
        &self,
        origin: DispatchOriginOf<RuntimeCallFor<Runtime>>,
        call: &RuntimeCallFor<Runtime>,
        _info: &DispatchInfoOf<RuntimeCallFor<Runtime>>,
        _len: usize,
        _self_implicit: Self::Implicit,
        _inherited_implication: &impl Implication,
        _source: TransactionSource,
    ) -> ValidateResult<Self::Val, RuntimeCallFor<Runtime>> {
        // we only care about unsigned calls
        if origin.as_system_origin_signer().is_some() {
            return Ok((ValidTransaction::default(), Val::None, origin));
        };

        let messenger_call = match call.maybe_messenger_call() {
            Some(messenger_call) => messenger_call,
            None => return Ok((ValidTransaction::default(), Val::None, origin)),
        };

        let (validity, validated_relay_message) = Self::do_validate(messenger_call)?;
        Ok((
            validity,
            Val::ValidatedRelayMessage(validated_relay_message),
            Origin::ValidatedUnsigned.into(),
        ))
    }

    fn prepare(
        self,
        val: Self::Val,
        _origin: &DispatchOriginOf<RuntimeCallFor<Runtime>>,
        call: &RuntimeCallFor<Runtime>,
        _info: &DispatchInfoOf<RuntimeCallFor<Runtime>>,
        _len: usize,
    ) -> Result<Self::Pre, TransactionValidityError> {
        match (call.maybe_messenger_call(), val) {
            // prepare if this is a messenger call and has been validated
            (Some(messenger_call), Val::ValidatedRelayMessage(validated_relay_message)) => {
                Self::do_prepare(messenger_call, validated_relay_message)
            }
            // return Ok for the rest of the call types
            (_, _) => Ok(()),
        }
    }

    // TODO: need benchmarking for this extension.
    impl_tx_ext_default!(RuntimeCallFor<Runtime>; weight);
}

/// Extensions for pallet-messenger unsigned extrinsics with trusted MMR verification.
#[derive(Encode, Decode, Clone, Eq, PartialEq, TypeInfo)]
pub struct MessengerTrustedMmrExtension<Runtime>(PhantomData<Runtime>);

impl<Runtime> MessengerTrustedMmrExtension<Runtime> {
    pub fn new() -> Self {
        Self(PhantomData)
    }
}

impl<Runtime> Default for MessengerTrustedMmrExtension<Runtime> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T: Config> fmt::Debug for MessengerTrustedMmrExtension<T> {
    #[cfg(feature = "std")]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "MessengerTrustedMmrExtension",)
    }

    #[cfg(not(feature = "std"))]
    fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result {
        Ok(())
    }
}

impl<Runtime> MessengerTrustedMmrExtension<Runtime>
where
    Runtime: Config + scale_info::TypeInfo + fmt::Debug + Send + Sync,
{
    fn do_validate(
        call: &MessengerCall<Runtime>,
    ) -> Result<(ValidTransaction, ValidatedRelayMessage<Runtime>), TransactionValidityError> {
        match call {
            Call::relay_message { msg: xdm } => {
                let consensus_state_root =
                    Runtime::MmrProofVerifier::extract_leaf_without_verifying(
                        xdm.proof.consensus_mmr_proof(),
                    )
                    .ok_or(InvalidTransaction::BadProof)?
                    .state_root();

                let validated_relay_message =
                    Messenger::<Runtime>::validate_relay_message(xdm, consensus_state_root)?;

                Ok((ValidTransaction::default(), validated_relay_message))
            }
            Call::relay_message_response { msg: xdm } => {
                let consensus_state_root =
                    Runtime::MmrProofVerifier::extract_leaf_without_verifying(
                        xdm.proof.consensus_mmr_proof(),
                    )
                    .ok_or(InvalidTransaction::BadProof)?
                    .state_root();

                let validated_relay_message =
                    Messenger::<Runtime>::validate_relay_message_response(
                        xdm,
                        consensus_state_root,
                    )?;

                Ok((ValidTransaction::default(), validated_relay_message))
            }
            _ => Err(InvalidTransaction::Call.into()),
        }
    }
}

impl<Runtime> TransactionExtension<RuntimeCallFor<Runtime>>
    for MessengerTrustedMmrExtension<Runtime>
where
    Runtime: Config + scale_info::TypeInfo + fmt::Debug + Send + Sync,
    <RuntimeCallFor<Runtime> as Dispatchable>::RuntimeOrigin:
        AsSystemOriginSigner<<Runtime as frame_system::Config>::AccountId> + From<Origin> + Clone,
    RuntimeCallFor<Runtime>: MaybeMessengerCall<Runtime>,
{
    const IDENTIFIER: &'static str = "MessengerTrustedMmrExtension";
    type Implicit = ();
    type Val = Val<Runtime>;
    type Pre = ();

    // TODO: need benchmarking for this extension.
    impl_tx_ext_default!(RuntimeCallFor<Runtime>; weight);

    fn validate(
        &self,
        origin: DispatchOriginOf<RuntimeCallFor<Runtime>>,
        call: &RuntimeCallFor<Runtime>,
        _info: &DispatchInfoOf<RuntimeCallFor<Runtime>>,
        _len: usize,
        _self_implicit: Self::Implicit,
        _inherited_implication: &impl Implication,
        _source: TransactionSource,
    ) -> ValidateResult<Self::Val, RuntimeCallFor<Runtime>> {
        // we only care about unsigned calls
        if origin.as_system_origin_signer().is_some() {
            return Ok((ValidTransaction::default(), Val::None, origin));
        };

        let messenger_call = match call.maybe_messenger_call() {
            Some(messenger_call) => messenger_call,
            None => return Ok((ValidTransaction::default(), Val::None, origin)),
        };

        let (validity, validated_relay_message) = Self::do_validate(messenger_call)?;
        Ok((
            validity,
            Val::ValidatedRelayMessage(validated_relay_message),
            Origin::ValidatedUnsigned.into(),
        ))
    }

    fn prepare(
        self,
        val: Self::Val,
        _origin: &DispatchOriginOf<RuntimeCallFor<Runtime>>,
        call: &RuntimeCallFor<Runtime>,
        _info: &DispatchInfoOf<RuntimeCallFor<Runtime>>,
        _len: usize,
    ) -> Result<Self::Pre, TransactionValidityError> {
        match (call.maybe_messenger_call(), val) {
            // prepare if this is a messenger call and has been validated
            (Some(messenger_call), Val::ValidatedRelayMessage(validated_relay_message)) => {
                MessengerExtension::<Runtime>::do_prepare(messenger_call, validated_relay_message)
            }
            // return Ok for the rest of the call types
            (_, _) => Ok(()),
        }
    }
}