1
// Copyright (C) Moondance Labs Ltd.
2
// This file is part of Tanssi.
3

            
4
// Tanssi is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8

            
9
// Tanssi is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13

            
14
// You should have received a copy of the GNU General Public License
15
// along with Tanssi.  If not, see <http://www.gnu.org/licenses/>
16

            
17
//! # XCM Core Buyer Pallet
18
//!
19
//! This pallet allows collators to buy parathread cores on demand.
20

            
21
#![cfg_attr(not(feature = "std"), no_std)]
22
extern crate alloc;
23

            
24
use frame_support::{Deserialize, Serialize};
25
pub use pallet::*;
26
use sp_runtime::{SaturatedConversion, Saturating};
27

            
28
#[cfg(test)]
29
mod mock;
30

            
31
#[cfg(test)]
32
mod tests;
33

            
34
#[cfg(any(test, feature = "runtime-benchmarks"))]
35
mod benchmarks;
36
pub mod weights;
37
pub use weights::WeightInfo;
38

            
39
#[cfg(feature = "runtime-benchmarks")]
40
use tp_traits::BlockNumber;
41
use {
42
    alloc::{vec, vec::Vec},
43
    dp_core::ParaId,
44
    frame_support::{
45
        dispatch::GetDispatchInfo,
46
        pallet_prelude::*,
47
        traits::fungible::{Balanced, Inspect},
48
    },
49
    frame_system::pallet_prelude::*,
50
    parity_scale_codec::EncodeLike,
51
    sp_consensus_slots::Slot,
52
    sp_runtime::traits::{AccountIdConversion, Convert, Get},
53
    tp_traits::{
54
        AuthorNotingHook, AuthorNotingInfo, LatestAuthorInfoFetcher, ParathreadParams,
55
        SlotFrequency,
56
    },
57
    tp_xcm_core_buyer::BuyCoreCollatorProof,
58
    xcm::{
59
        latest::{Asset, Assets, InteriorLocation, Response, Xcm},
60
        prelude::*,
61
    },
62
};
63

            
64
pub trait XCMNotifier<T: Config> {
65
    fn new_notify_query(
66
        responder: impl Into<Location>,
67
        notify: impl Into<<T as Config>::RuntimeCall>,
68
        timeout: BlockNumberFor<T>,
69
        match_querier: impl Into<Location>,
70
    ) -> u64;
71
}
72

            
73
/// Dummy implementation. Should only be used for testing.
74
impl<T: Config> XCMNotifier<T> for () {
75
20
    fn new_notify_query(
76
20
        _responder: impl Into<Location>,
77
20
        _notify: impl Into<<T as Config>::RuntimeCall>,
78
20
        _timeout: BlockNumberFor<T>,
79
20
        _match_querier: impl Into<Location>,
80
20
    ) -> u64 {
81
20
        0
82
20
    }
83
}
84

            
85
#[derive(
86
    RuntimeDebug,
87
    PartialEq,
88
    Eq,
89
    Encode,
90
    Decode,
91
    Clone,
92
    TypeInfo,
93
    Serialize,
94
    Deserialize,
95
    MaxEncodedLen,
96
)]
97
pub struct InFlightCoreBuyingOrder<BN> {
98
    para_id: ParaId,
99
    query_id: QueryId,
100
    ttl: BN,
101
}
102

            
103
#[derive(
104
    Debug, Clone, PartialEq, Eq, Encode, Decode, scale_info::TypeInfo, Serialize, Deserialize,
105
)]
106
pub enum BuyingError<BlockNumber> {
107
    OrderAlreadyExists {
108
        ttl: BlockNumber,
109
        current_block_number: BlockNumber,
110
    },
111
    BlockProductionPending {
112
        ttl: BlockNumber,
113
        current_block_number: BlockNumber,
114
    },
115
    NotAParathread,
116
    NotAllowedToProduceBlockRightNow {
117
        slot_frequency: SlotFrequency,
118
        max_slot_earlier_core_buying_permitted: Slot,
119
        last_block_production_slot: Slot,
120
    },
121
}
122

            
123
impl<T: Config> AuthorNotingHook<T::AccountId> for Pallet<T> {
124
102
    fn on_container_authors_noted(info: &[AuthorNotingInfo<T::AccountId>]) -> Weight {
125
102
        let writes = info.len().saturated_into();
126

            
127
214
        for info in info {
128
112
            let para_id = info.para_id;
129
112
            PendingBlocks::<T>::remove(para_id);
130
112
        }
131

            
132
102
        T::DbWeight::get().writes(writes)
133
102
    }
134

            
135
    #[cfg(feature = "runtime-benchmarks")]
136
    fn prepare_worst_case_for_bench(
137
        _author: &T::AccountId,
138
        _block_number: BlockNumber,
139
        para_id: ParaId,
140
    ) {
141
        // We insert the some data in the storage being removed.
142
        // Not sure if this is necessary.
143
        PendingBlocks::<T>::insert(para_id, BlockNumberFor::<T>::from(42u32));
144
    }
145
}
146

            
147
#[frame_support::pallet]
148
pub mod pallet {
149
    use {
150
        super::*,
151
        nimbus_primitives::SlotBeacon,
152
        pallet_xcm::ensure_response,
153
        sp_runtime::{app_crypto::AppCrypto, RuntimeAppPublic},
154
    };
155

            
156
    #[pallet::pallet]
157
    pub struct Pallet<T>(PhantomData<T>);
158

            
159
    #[pallet::config]
160
    pub trait Config: frame_system::Config {
161
        type Currency: Inspect<Self::AccountId> + Balanced<Self::AccountId>;
162

            
163
        type XcmSender: SendXcm;
164
        /// Get encoded call to buy a core in the relay chain. This will be passed to the XCM
165
        /// `Transact` instruction.
166
        type GetPurchaseCoreCall: GetPurchaseCoreCall<Self::RelayChain>;
167
        /// How to convert a `ParaId` into an `AccountId32`. Used to derive the parathread tank
168
        /// account in `interior_multilocation`.
169
        type GetParathreadAccountId: Convert<ParaId, [u8; 32]>;
170
        /// The max price that the parathread is willing to pay for a core, in relay chain currency.
171
        /// If `None`, defaults to `u128::MAX`, the parathread will pay the market price with no
172
        /// upper bound.
173
        type GetParathreadMaxCorePrice: GetParathreadMaxCorePrice;
174
        /// Orchestartor chain `ParaId`. Used in `absolute_multilocation` to convert the
175
        /// `interior_multilocation` into what the relay chain needs to allow to `DepositAsset`.
176
        type SelfParaId: Get<ParaId>;
177
        type RelayChain: Default
178
            + Encode
179
            + Decode
180
            + TypeInfo
181
            + EncodeLike
182
            + Clone
183
            + PartialEq
184
            + alloc::fmt::Debug
185
            + MaxEncodedLen;
186

            
187
        /// Get the parathread params. Used to verify that the para id is a parathread.
188
        // TODO: and in the future to restrict the ability to buy a core depending on slot frequency
189
        type GetParathreadParams: GetParathreadParams;
190
        /// Validate if particular account id and public key pair belongs to a collator and the collator
191
        /// is selected to collate for particular para id.
192
        type CheckCollatorValidity: CheckCollatorValidity<Self::AccountId, Self::CollatorPublicKey>;
193
        /// A configuration for base priority of unsigned transactions.
194
        ///
195
        /// This is exposed so that it can be tuned for particular runtime, when
196
        /// multiple pallets send unsigned transactions.
197
        #[pallet::constant]
198
        type UnsignedPriority: Get<TransactionPriority>;
199

            
200
        /// TTL for pending blocks entry, which prevents anyone to submit another core buying xcm.
201
        #[pallet::constant]
202
        type PendingBlocksTtl: Get<BlockNumberFor<Self>>;
203

            
204
        /// TTL to be used in xcm's notify query
205
        #[pallet::constant]
206
        type CoreBuyingXCMQueryTtl: Get<BlockNumberFor<Self>>;
207

            
208
        /// Additional ttl for in flight orders (total would be CoreBuyingXCMQueryTtl + AdditionalTtlForInflightOrders)
209
        /// after which the in flight orders can be cleaned up by anyone.
210
        #[pallet::constant]
211
        type AdditionalTtlForInflightOrders: Get<BlockNumberFor<Self>>;
212

            
213
        /// Slot drift allowed for core buying
214
        #[pallet::constant]
215
        type BuyCoreSlotDrift: Get<Slot>;
216

            
217
        #[pallet::constant]
218
        type UniversalLocation: Get<InteriorLocation>;
219

            
220
        type RuntimeOrigin: Into<Result<pallet_xcm::Origin, <Self as Config>::RuntimeOrigin>>
221
            + From<<Self as frame_system::Config>::RuntimeOrigin>;
222

            
223
        /// The overarching call type
224
        type RuntimeCall: From<Call<Self>> + Encode + GetDispatchInfo;
225

            
226
        /// Outcome notifier implements functionality to enable reporting back the outcome
227
        type XCMNotifier: XCMNotifier<Self>;
228

            
229
        type LatestAuthorInfoFetcher: LatestAuthorInfoFetcher<Self::AccountId>;
230

            
231
        type SlotBeacon: SlotBeacon;
232

            
233
        /// A PublicKey can be converted into an `AccountId`. This is required in order to verify
234
        /// the collator signature
235
        type CollatorPublicKey: Member
236
            + Parameter
237
            + RuntimeAppPublic
238
            + AppCrypto
239
            + MaybeSerializeDeserialize
240
            + MaxEncodedLen;
241

            
242
        type WeightInfo: WeightInfo;
243
    }
244

            
245
    #[pallet::event]
246
    #[pallet::generate_deposit(pub(super) fn deposit_event)]
247
    pub enum Event<T: Config> {
248
        /// An XCM message to buy a core for this parathread has been sent to the relay chain.
249
        BuyCoreXcmSent {
250
            para_id: ParaId,
251
            transaction_status_query_id: QueryId,
252
        },
253
        /// We received response for xcm
254
        ReceivedBuyCoreXCMResult { para_id: ParaId, response: Response },
255

            
256
        /// We cleaned up expired pending blocks entries.
257
        CleanedUpExpiredPendingBlocksEntries { para_ids: Vec<ParaId> },
258

            
259
        /// We cleaned up expired in flight orders entries.
260
        CleanedUpExpiredInFlightOrderEntries { para_ids: Vec<ParaId> },
261
    }
262

            
263
    #[pallet::error]
264
    pub enum Error<T> {
265
        InvalidProof,
266
        ErrorValidatingXCM,
267
        ErrorDeliveringXCM,
268
        /// An order for this para id already exists
269
        OrderAlreadyExists,
270
        /// The para id is not a parathread
271
        NotAParathread,
272
        /// There are too many in-flight orders, buying cores will not work until some of those
273
        /// orders finish.
274
        InFlightLimitReached,
275
        /// There are no collators assigned to this parathread, so no point in buying a core
276
        NoAssignedCollators,
277
        /// This collator is not assigned to this parathread
278
        CollatorNotAssigned,
279
        /// The `XcmWeights` storage has not been set. This must have been set by root with the
280
        /// value of the relay chain xcm call weight and extrinsic weight
281
        XcmWeightStorageNotSet,
282
        /// Converting a multilocation into a relay relative multilocation failed
283
        ReanchorFailed,
284
        /// Inverting location from destination point of view failed
285
        LocationInversionFailed,
286
        /// Modifying XCM to report the result of XCM failed
287
        ReportNotifyingSetupFailed,
288
        /// Unexpected XCM response
289
        UnexpectedXCMResponse,
290
        /// Block production is pending for para id with successfully placed order
291
        BlockProductionPending,
292
        /// Block production is not allowed for current slot
293
        NotAllowedToProduceBlockRightNow,
294
        /// Collator signature nonce is incorrect
295
        IncorrectCollatorSignatureNonce,
296
        /// Collator signature is invalid
297
        InvalidCollatorSignature,
298
    }
299

            
300
    impl<T: Config> From<BuyingError<BlockNumberFor<T>>> for Error<T> {
301
10
        fn from(value: BuyingError<BlockNumberFor<T>>) -> Self {
302
10
            match value {
303
5
                BuyingError::OrderAlreadyExists { .. } => Error::<T>::OrderAlreadyExists,
304
2
                BuyingError::BlockProductionPending { .. } => Error::<T>::BlockProductionPending,
305
1
                BuyingError::NotAParathread => Error::<T>::NotAParathread,
306
                BuyingError::NotAllowedToProduceBlockRightNow { .. } => {
307
2
                    Error::<T>::NotAllowedToProduceBlockRightNow
308
                }
309
            }
310
10
        }
311
    }
312

            
313
    /// Set of parathreads that have already sent an XCM message to buy a core recently.
314
    /// Used to avoid 2 collators buying a core at the same time, because it is only possible to buy
315
    /// 1 core in 1 relay block for the same parathread.
316
    #[pallet::storage]
317
    pub type InFlightOrders<T: Config> =
318
        StorageMap<_, Twox128, ParaId, InFlightCoreBuyingOrder<BlockNumberFor<T>>, OptionQuery>;
319

            
320
    /// Number of pending blocks
321
    #[pallet::storage]
322
    pub type PendingBlocks<T: Config> =
323
        StorageMap<_, Twox128, ParaId, BlockNumberFor<T>, OptionQuery>;
324

            
325
    /// Mapping of QueryId to ParaId
326
    #[pallet::storage]
327
    pub type QueryIdToParaId<T: Config> = StorageMap<_, Twox128, QueryId, ParaId, OptionQuery>;
328

            
329
    /// This must be set by root with the value of the relay chain xcm call weight and extrinsic
330
    /// weight limit. This is a storage item because relay chain weights can change, so we need to
331
    /// be able to adjust them without doing a runtime upgrade.
332
    #[pallet::storage]
333
    pub type RelayXcmWeightConfig<T: Config> =
334
        StorageValue<_, RelayXcmWeightConfigInner<T>, OptionQuery>;
335

            
336
    /// Collator signature nonce for reply protection
337
    #[pallet::storage]
338
    pub type CollatorSignatureNonce<T: Config> = StorageMap<_, Twox128, ParaId, u64, ValueQuery>;
339

            
340
    #[derive(
341
        Encode,
342
        Decode,
343
        CloneNoBound,
344
        PartialEq,
345
        Eq,
346
        DebugNoBound,
347
        TypeInfo,
348
        MaxEncodedLen,
349
        DecodeWithMemTracking,
350
    )]
351
    #[scale_info(skip_type_params(T))]
352
    pub struct RelayXcmWeightConfigInner<T> {
353
        pub buy_execution_cost: u128,
354
        pub weight_at_most: Weight,
355
        pub _phantom: PhantomData<T>,
356
    }
357

            
358
    /// This must be set by root with the value of the relay chain xcm call weight and extrinsic
359
    /// weight limit. This is a storage item because relay chain weights can change, so we need to
360
    /// be able to adjust them without doing a runtime upgrade.
361
    #[pallet::storage]
362
    pub type RelayChain<T: Config> = StorageValue<_, T::RelayChain, ValueQuery>;
363

            
364
    #[pallet::call]
365
    impl<T: Config> Pallet<T> {
366
        /// Buy a core for this parathread id.
367
        /// Collators should call this to indicate that they intend to produce a block, but they
368
        /// cannot do it because this para id has no available cores.
369
        /// The purchase is automatic using XCM, and collators do not need to do anything.
370
        // Note that the collators that will be calling this function are parathread collators, not
371
        // tanssi collators. So we cannot force them to provide a complex proof, e.g. against relay
372
        // state.
373
        #[pallet::call_index(0)]
374
        #[pallet::weight(T::WeightInfo::buy_core())]
375
        pub fn buy_core(
376
            origin: OriginFor<T>,
377
            para_id: ParaId,
378
            // Below parameter are already validated during `validate_unsigned` cal
379
            proof: BuyCoreCollatorProof<T::CollatorPublicKey>,
380
14
        ) -> DispatchResult {
381
14
            ensure_none(origin)?;
382

            
383
14
            let current_nonce = CollatorSignatureNonce::<T>::get(para_id);
384
14
            CollatorSignatureNonce::<T>::set(para_id, current_nonce.saturating_add(1));
385

            
386
14
            Self::on_collator_instantaneous_core_requested(para_id, Some(proof.public_key))
387
        }
388

            
389
        /// Buy core for para id as root. Does not require any proof, useful in tests.
390
        #[pallet::call_index(1)]
391
        #[pallet::weight(T::WeightInfo::force_buy_core())]
392
30
        pub fn force_buy_core(origin: OriginFor<T>, para_id: ParaId) -> DispatchResult {
393
30
            ensure_root(origin)?;
394

            
395
29
            Self::on_collator_instantaneous_core_requested(para_id, None)
396
        }
397

            
398
        #[pallet::call_index(2)]
399
        #[pallet::weight(T::WeightInfo::set_relay_xcm_weight_config())]
400
        pub fn set_relay_xcm_weight_config(
401
            origin: OriginFor<T>,
402
            xcm_weights: Option<RelayXcmWeightConfigInner<T>>,
403
30
        ) -> DispatchResult {
404
30
            ensure_root(origin)?;
405

            
406
30
            RelayXcmWeightConfig::<T>::set(xcm_weights);
407

            
408
30
            Ok(())
409
        }
410

            
411
        #[pallet::call_index(3)]
412
        #[pallet::weight(T::WeightInfo::set_relay_chain())]
413
        pub fn set_relay_chain(
414
            origin: OriginFor<T>,
415
            relay_chain: Option<T::RelayChain>,
416
12
        ) -> DispatchResult {
417
12
            ensure_root(origin)?;
418

            
419
12
            if let Some(relay_chain) = relay_chain {
420
12
                RelayChain::<T>::put(relay_chain);
421
12
            } else {
422
                RelayChain::<T>::kill();
423
            }
424

            
425
12
            Ok(())
426
        }
427

            
428
        #[pallet::call_index(4)]
429
        #[pallet::weight(T::WeightInfo::query_response())]
430
        pub fn query_response(
431
            origin: OriginFor<T>,
432
            query_id: QueryId,
433
            response: Response,
434
106
        ) -> DispatchResult {
435
106
            let _responder = ensure_response(<T as Config>::RuntimeOrigin::from(origin))?;
436

            
437
106
            let maybe_para_id = QueryIdToParaId::<T>::get(query_id);
438

            
439
106
            let para_id = if let Some(para_id) = maybe_para_id {
440
106
                para_id
441
            } else {
442
                // Most probably entry was expired or removed in some other way. Let's return early.
443
                return Ok(());
444
            };
445

            
446
106
            QueryIdToParaId::<T>::remove(query_id);
447
106
            InFlightOrders::<T>::remove(para_id);
448

            
449
106
            match response {
450
44
                Response::DispatchResult(MaybeErrorCode::Success) => {
451
44
                    // Success. Add para id to pending block
452
44
                    let now = <frame_system::Pallet<T>>::block_number();
453
44
                    let ttl = T::PendingBlocksTtl::get();
454
44
                    PendingBlocks::<T>::insert(para_id, now.saturating_add(ttl));
455
44
                }
456
62
                Response::DispatchResult(_) => {
457
62
                    // We do not add paraid to pending block on failure
458
62
                }
459
                _ => {
460
                    // Unexpected.
461
                    return Err(Error::<T>::UnexpectedXCMResponse.into());
462
                }
463
            }
464

            
465
106
            Self::deposit_event(Event::ReceivedBuyCoreXCMResult { para_id, response });
466

            
467
106
            Ok(())
468
        }
469

            
470
        #[pallet::call_index(5)]
471
        #[pallet::weight(T::WeightInfo::clean_up_expired_in_flight_orders(expired_pending_blocks_para_id.len() as u32))]
472
        pub fn clean_up_expired_pending_blocks(
473
            origin: OriginFor<T>,
474
            expired_pending_blocks_para_id: Vec<ParaId>,
475
2
        ) -> DispatchResult {
476
2
            let _ = ensure_signed(origin)?;
477
2
            let now = frame_system::Pallet::<T>::block_number();
478
2
            let mut cleaned_up_para_ids = vec![];
479

            
480
4
            for para_id in expired_pending_blocks_para_id {
481
2
                let maybe_pending_block_ttl = PendingBlocks::<T>::get(para_id);
482
2
                if let Some(pending_block_ttl) = maybe_pending_block_ttl {
483
2
                    if pending_block_ttl < now {
484
1
                        PendingBlocks::<T>::remove(para_id);
485
1
                        cleaned_up_para_ids.push(para_id);
486
1
                    } else {
487
1
                        // Ignore if not expired
488
1
                    }
489
                }
490
            }
491

            
492
2
            Self::deposit_event(Event::CleanedUpExpiredPendingBlocksEntries {
493
2
                para_ids: cleaned_up_para_ids,
494
2
            });
495

            
496
2
            Ok(())
497
        }
498

            
499
        #[pallet::call_index(6)]
500
        #[pallet::weight(T::WeightInfo::clean_up_expired_in_flight_orders(expired_in_flight_orders.len() as u32))]
501
        pub fn clean_up_expired_in_flight_orders(
502
            origin: OriginFor<T>,
503
            expired_in_flight_orders: Vec<ParaId>,
504
2
        ) -> DispatchResult {
505
2
            let _ = ensure_signed(origin)?;
506
2
            let now = frame_system::Pallet::<T>::block_number();
507
2
            let mut cleaned_up_para_ids = vec![];
508

            
509
4
            for para_id in expired_in_flight_orders {
510
2
                let maybe_in_flight_order = InFlightOrders::<T>::get(para_id);
511
2
                if let Some(in_flight_order) = maybe_in_flight_order {
512
2
                    if in_flight_order.ttl < now {
513
1
                        InFlightOrders::<T>::remove(para_id);
514
1
                        QueryIdToParaId::<T>::remove(in_flight_order.query_id);
515
1
                        cleaned_up_para_ids.push(para_id);
516
1
                    } else {
517
1
                        // Ignore if not expired
518
1
                    }
519
                }
520
            }
521

            
522
2
            Self::deposit_event(Event::CleanedUpExpiredInFlightOrderEntries {
523
2
                para_ids: cleaned_up_para_ids,
524
2
            });
525

            
526
2
            Ok(())
527
        }
528
    }
529

            
530
    impl<T: Config> Pallet<T> {
531
        /// Returns the interior multilocation for this container chain para id. This is a relative
532
        /// multilocation that can be used in the `descend_origin` XCM opcode.
533
57
        pub fn interior_multilocation(para_id: ParaId) -> InteriorLocation {
534
57
            let container_chain_account = T::GetParathreadAccountId::convert(para_id);
535
57
            let account_junction = Junction::AccountId32 {
536
57
                id: container_chain_account,
537
57
                network: None,
538
57
            };
539

            
540
57
            [account_junction].into()
541
57
        }
542

            
543
        /// Returns a multilocation that can be used in the `deposit_asset` XCM opcode.
544
        /// The `interior_multilocation` can be obtained using `Self::interior_multilocation`.
545
57
        pub fn relay_relative_multilocation(
546
57
            interior_multilocation: InteriorLocation,
547
57
        ) -> Result<Location, Error<T>> {
548
57
            let relay_chain = Location::parent();
549
57
            let context: InteriorLocation = [Parachain(T::SelfParaId::get().into())].into();
550
57
            let mut reanchored: Location = interior_multilocation.into();
551
57
            reanchored
552
57
                .reanchor(&relay_chain, &context)
553
57
                .map_err(|_| Error::<T>::ReanchorFailed)?;
554

            
555
57
            Ok(reanchored)
556
57
        }
557

            
558
43
        pub fn is_core_buying_allowed(
559
43
            para_id: ParaId,
560
43
            _maybe_collator_public_key: Option<<T as Config>::CollatorPublicKey>,
561
43
        ) -> Result<(), BuyingError<BlockNumberFor<T>>> {
562
            // If an in flight order is pending (i.e we did not receive the notification yet) and our
563
            // record is not expired yet, we should not allow the collator to buy another core.
564
43
            let maybe_in_flight_order = InFlightOrders::<T>::get(para_id);
565
43
            if let Some(in_flight_order) = maybe_in_flight_order {
566
6
                if in_flight_order.ttl < <frame_system::Pallet<T>>::block_number() {
567
1
                    InFlightOrders::<T>::remove(para_id);
568
1
                } else {
569
5
                    return Err(BuyingError::OrderAlreadyExists {
570
5
                        ttl: in_flight_order.ttl,
571
5
                        current_block_number: <frame_system::Pallet<T>>::block_number(),
572
5
                    });
573
                }
574
37
            }
575

            
576
            // If a block production is pending and our record is not expired yet, we should not allow
577
            // the collator to buy another core yet.
578
38
            let maybe_pending_blocks_ttl = PendingBlocks::<T>::get(para_id);
579
38
            if let Some(pending_blocks_ttl) = maybe_pending_blocks_ttl {
580
3
                if pending_blocks_ttl < <frame_system::Pallet<T>>::block_number() {
581
1
                    PendingBlocks::<T>::remove(para_id);
582
1
                } else {
583
2
                    return Err(BuyingError::BlockProductionPending {
584
2
                        ttl: pending_blocks_ttl,
585
2
                        current_block_number: <frame_system::Pallet<T>>::block_number(),
586
2
                    });
587
                }
588
35
            }
589

            
590
            // Check that the para id is a parathread
591
36
            let parathread_params = T::GetParathreadParams::get_parathread_params(para_id)
592
36
                .ok_or(BuyingError::NotAParathread)?;
593

            
594
35
            let maybe_latest_author_info =
595
35
                T::LatestAuthorInfoFetcher::get_latest_author_info(para_id);
596
35
            if let Some(latest_author_info) = maybe_latest_author_info {
597
21
                let current_slot = T::SlotBeacon::slot();
598
21
                if !parathread_params.slot_frequency.should_parathread_buy_core(
599
21
                    Slot::from(u64::from(current_slot)),
600
21
                    T::BuyCoreSlotDrift::get(),
601
21
                    latest_author_info.latest_slot_number,
602
21
                ) {
603
                    // TODO: Take max slots to produce a block from config
604
2
                    return Err(BuyingError::NotAllowedToProduceBlockRightNow {
605
2
                        slot_frequency: parathread_params.slot_frequency,
606
2
                        max_slot_earlier_core_buying_permitted: Slot::from(2u64),
607
2
                        last_block_production_slot: latest_author_info.latest_slot_number,
608
2
                    });
609
19
                }
610
14
            }
611

            
612
33
            Ok(())
613
43
        }
614

            
615
        /// Send an XCM message to the relay chain to try to buy a core for this para_id.
616
43
        fn on_collator_instantaneous_core_requested(
617
43
            para_id: ParaId,
618
43
            maybe_collator_public_key: Option<<T as Config>::CollatorPublicKey>,
619
43
        ) -> DispatchResult {
620
43
            Self::is_core_buying_allowed(para_id, maybe_collator_public_key)
621
43
                .map_err(Into::<Error<T>>::into)?;
622

            
623
32
            let xcm_weights_storage =
624
33
                RelayXcmWeightConfig::<T>::get().ok_or(Error::<T>::XcmWeightStorageNotSet)?;
625

            
626
32
            let withdraw_amount = xcm_weights_storage.buy_execution_cost;
627

            
628
            // Use the account derived from the multilocation composed with DescendOrigin
629
            // Buy on-demand cores
630
            // Any failure should return everything to the derivative account
631

            
632
            // Don't use utility::as_derivative because that will make the tanssi sovereign account
633
            // pay for fees, instead use `DescendOrigin` to make the parathread tank account
634
            // pay for fees.
635
            // TODO: when coretime is implemented, use coretime instantaneous credits instead of
636
            // buying on-demand cores at the price defined by the relay
637
32
            let origin = OriginKind::SovereignAccount;
638
            // TODO: max_amount is the max price of a core that this parathread is willing to pay
639
            // It should be defined in a storage item somewhere, controllable by the container chain
640
            // manager.
641
32
            let max_amount =
642
32
                T::GetParathreadMaxCorePrice::get_max_core_price(para_id).unwrap_or(u128::MAX);
643
32
            let call =
644
32
                T::GetPurchaseCoreCall::get_encoded(RelayChain::<T>::get(), max_amount, para_id);
645
32
            let weight_at_most = xcm_weights_storage.weight_at_most;
646

            
647
            // Assumption: derived account already has DOT
648
            // The balance should be enough to cover the `Withdraw` needed to `BuyExecution`, plus
649
            // the price of the core, which can change based on demand.
650
32
            let relay_asset_total: Asset = (Here, withdraw_amount).into();
651
32
            let refund_asset_filter: AssetFilter = AssetFilter::Wild(WildAsset::AllCounted(1));
652

            
653
32
            let interior_multilocation = Self::interior_multilocation(para_id);
654
            // The parathread tank account is derived from the tanssi sovereign account and the
655
            // parathread para id.
656
32
            let derived_account =
657
32
                Self::relay_relative_multilocation(interior_multilocation.clone())?;
658

            
659
            // Need to use `builder_unsafe` because safe `builder` does not allow `descend_origin` as first instruction.
660
            // We use `descend_origin` instead of wrapping the transact call in `utility.as_derivative`
661
            // because with `descend_origin` the parathread tank account will pay for fees, while
662
            // `utility.as_derivative` will make the tanssi sovereign account pay for fees.
663

            
664
32
            let notify_call = <T as Config>::RuntimeCall::from(Call::<T>::query_response {
665
32
                query_id: 0,
666
32
                response: Default::default(),
667
32
            });
668
32
            let notify_call_weight = notify_call.get_dispatch_info().call_weight;
669

            
670
32
            let notify_query_ttl = <frame_system::Pallet<T>>::block_number()
671
32
                .saturating_add(T::CoreBuyingXCMQueryTtl::get());
672

            
673
            // Send XCM to relay chain
674
32
            let relay_chain = Location::parent();
675
32
            let query_id = T::XCMNotifier::new_notify_query(
676
32
                relay_chain.clone(),
677
32
                notify_call,
678
32
                notify_query_ttl,
679
32
                interior_multilocation.clone(),
680
            );
681

            
682
32
            let message: Xcm<()> = Xcm::builder_unsafe()
683
32
                .descend_origin(interior_multilocation.clone())
684
32
                .withdraw_asset(Assets::from(vec![relay_asset_total.clone()]))
685
32
                .buy_execution(relay_asset_total, Unlimited)
686
                // Both in case of error and in case of success, we want to refund the unused weight
687
32
                .set_appendix(
688
32
                    Xcm::builder_unsafe()
689
32
                        .report_transact_status(QueryResponseInfo {
690
                            // This location from the point of view of destination
691
32
                            destination: T::UniversalLocation::get()
692
32
                                .invert_target(&relay_chain)
693
32
                                .map_err(|e| {
694
                                    log::error!("invert_target: {:?}", e);
695

            
696
                                    Error::<T>::LocationInversionFailed
697
                                })?,
698
32
                            query_id,
699
32
                            max_weight: notify_call_weight,
700
                        })
701
32
                        .refund_surplus()
702
32
                        .deposit_asset(refund_asset_filter, derived_account)
703
32
                        .build(),
704
                )
705
32
                .transact(origin, weight_at_most, call)
706
32
                .build();
707

            
708
            // We intentionally do not charge any fees
709
32
            let (ticket, _price) =
710
32
                T::XcmSender::validate(&mut Some(relay_chain), &mut Some(message)).map_err(
711
                    |e| {
712
                        log::error!("XcmSender::validate: {:?}", e);
713
                        Error::<T>::ErrorValidatingXCM
714
                    },
715
                )?;
716
32
            T::XcmSender::deliver(ticket).map_err(|e| {
717
                log::error!("XcmSender::deliver: {:?}", e);
718
                Error::<T>::ErrorDeliveringXCM
719
            })?;
720
32
            Self::deposit_event(Event::BuyCoreXcmSent {
721
32
                para_id,
722
32
                transaction_status_query_id: query_id,
723
32
            });
724

            
725
32
            let in_flight_order_ttl =
726
32
                notify_query_ttl.saturating_add(T::AdditionalTtlForInflightOrders::get());
727
32
            InFlightOrders::<T>::insert(
728
32
                para_id,
729
32
                InFlightCoreBuyingOrder {
730
32
                    para_id,
731
32
                    query_id,
732
32
                    ttl: in_flight_order_ttl,
733
32
                },
734
            );
735

            
736
32
            QueryIdToParaId::<T>::insert(query_id, para_id);
737

            
738
32
            Ok(())
739
43
        }
740

            
741
63
        pub fn para_deregistered(para_id: ParaId) {
742
            // If para is deregistered we need to clean up in flight order, query id mapping
743
63
            if let Some(in_flight_order) = InFlightOrders::<T>::take(para_id) {
744
1
                InFlightOrders::<T>::remove(para_id);
745
1
                QueryIdToParaId::<T>::remove(in_flight_order.query_id);
746
62
            }
747

            
748
            // We need to clean the pending block entry if any
749
63
            PendingBlocks::<T>::remove(para_id);
750
63
        }
751
    }
752

            
753
    #[pallet::validate_unsigned]
754
    impl<T: Config> ValidateUnsigned for Pallet<T> {
755
        type Call = Call<T>;
756

            
757
20
        fn validate_unsigned(_source: TransactionSource, call: &Self::Call) -> TransactionValidity {
758
20
            if let Call::buy_core { para_id, proof } = call {
759
20
                let block_number = <frame_system::Pallet<T>>::block_number();
760

            
761
20
                let current_nonce = CollatorSignatureNonce::<T>::get(para_id);
762
20
                if proof.nonce != current_nonce {
763
2
                    return InvalidTransaction::Call.into();
764
18
                }
765

            
766
18
                let is_valid_collator =
767
18
                    T::CheckCollatorValidity::is_valid_collator(*para_id, proof.public_key.clone());
768
18
                if !is_valid_collator {
769
3
                    return InvalidTransaction::Call.into();
770
15
                }
771

            
772
15
                if !proof.verify_signature(*para_id) {
773
2
                    return InvalidTransaction::Call.into();
774
13
                }
775

            
776
13
                ValidTransaction::with_tag_prefix("XcmCoreBuyer")
777
13
                    .priority(T::UnsignedPriority::get())
778
                    // TODO: tags
779
13
                    .and_provides((block_number, para_id))
780
                    //.and_provides((current_session, authority_id))
781
                    //.longevity(
782
                    //    TryInto::<u64>::try_into(
783
                    //       T::NextSessionRotation::average_session_length() / 2u32.into(),
784
                    //    )
785
                    //        .unwrap_or(64_u64),
786
                    //)
787
13
                    .longevity(64)
788
13
                    .propagate(true)
789
13
                    .build()
790
            } else {
791
                InvalidTransaction::Call.into()
792
            }
793
20
        }
794
    }
795
}
796

            
797
pub trait GetPurchaseCoreCall<RelayChain> {
798
    /// Get the encoded call to buy a core for this `para_id`, with this `max_amount`.
799
    /// Returns the encoded call and its estimated weight.
800
    fn get_encoded(relay_chain: RelayChain, max_amount: u128, para_id: ParaId) -> Vec<u8>;
801
}
802

            
803
pub trait CheckCollatorValidity<AccountId, PublicKey> {
804
    fn is_valid_collator(para_id: ParaId, public_key: PublicKey) -> bool;
805

            
806
    #[cfg(feature = "runtime-benchmarks")]
807
    fn set_valid_collator(para_id: ParaId, account_id: AccountId, public_key: PublicKey);
808
}
809

            
810
pub trait GetParathreadMaxCorePrice {
811
    fn get_max_core_price(para_id: ParaId) -> Option<u128>;
812
}
813

            
814
impl GetParathreadMaxCorePrice for () {
815
20
    fn get_max_core_price(_para_id: ParaId) -> Option<u128> {
816
20
        None
817
20
    }
818
}
819

            
820
pub trait GetParathreadParams {
821
    fn get_parathread_params(para_id: ParaId) -> Option<ParathreadParams>;
822

            
823
    #[cfg(feature = "runtime-benchmarks")]
824
    fn set_parathread_params(para_id: ParaId, parathread_params: Option<ParathreadParams>);
825
}
826

            
827
/// Use `into_account_truncating` to convert a `ParaId` into a `[u8; 32]`.
828
pub struct ParaIdIntoAccountTruncating;
829

            
830
impl Convert<ParaId, [u8; 32]> for ParaIdIntoAccountTruncating {
831
525
    fn convert(para_id: ParaId) -> [u8; 32] {
832
        // Derive a 32 byte account id for a parathread. Note that this is not the address of
833
        // the relay chain parathread tank, but that address is derived from this.
834
525
        let account: dp_core::AccountId = para_id.into_account_truncating();
835

            
836
525
        account.into()
837
525
    }
838
}