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
1872
    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
4272
    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
22650
    fn on_container_authors_noted(info: &[AuthorNotingInfo<T::AccountId>]) -> Weight {
125
22650
        let writes = info.len().saturated_into();
126

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

            
132
22650
        T::DbWeight::get().writes(writes)
133
22650
    }
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
23088
#[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
69110
    #[pallet::pallet]
157
    pub struct Pallet<T>(PhantomData<T>);
158

            
159
    #[pallet::config]
160
    pub trait Config: frame_system::Config {
161
        /// Overarching event type.
162
        type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
163
        type Currency: Inspect<Self::AccountId> + Balanced<Self::AccountId>;
164

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

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

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

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

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

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

            
219
        #[pallet::constant]
220
        type UniversalLocation: Get<InteriorLocation>;
221

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

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

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

            
231
        type LatestAuthorInfoFetcher: LatestAuthorInfoFetcher<Self::AccountId>;
232

            
233
        type SlotBeacon: SlotBeacon;
234

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

            
244
        type WeightInfo: WeightInfo;
245
    }
246

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

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

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

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

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

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

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

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

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

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

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

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

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

            
385
20
            let current_nonce = CollatorSignatureNonce::<T>::get(para_id);
386
20
            CollatorSignatureNonce::<T>::set(para_id, current_nonce.saturating_add(1));
387
20

            
388
20
            Self::on_collator_instantaneous_core_requested(para_id, Some(proof.public_key))
389
        }
390

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

            
397
35
            Self::on_collator_instantaneous_core_requested(para_id, None)
398
        }
399

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

            
408
36
            if let Some(xcm_weights) = xcm_weights {
409
35
                RelayXcmWeightConfig::<T>::put(xcm_weights);
410
35
            } else {
411
1
                RelayXcmWeightConfig::<T>::kill();
412
1
            }
413

            
414
36
            Ok(())
415
        }
416

            
417
        #[pallet::call_index(3)]
418
        #[pallet::weight(T::WeightInfo::set_relay_chain())]
419
        pub fn set_relay_chain(
420
            origin: OriginFor<T>,
421
            relay_chain: Option<T::RelayChain>,
422
12
        ) -> DispatchResult {
423
12
            ensure_root(origin)?;
424

            
425
12
            if let Some(relay_chain) = relay_chain {
426
12
                RelayChain::<T>::put(relay_chain);
427
12
            } else {
428
                RelayChain::<T>::kill();
429
            }
430

            
431
12
            Ok(())
432
        }
433

            
434
        #[pallet::call_index(4)]
435
        #[pallet::weight(T::WeightInfo::query_response())]
436
        pub fn query_response(
437
            origin: OriginFor<T>,
438
            query_id: QueryId,
439
            response: Response,
440
76
        ) -> DispatchResult {
441
76
            let _responder = ensure_response(<T as Config>::RuntimeOrigin::from(origin))?;
442

            
443
76
            let maybe_para_id = QueryIdToParaId::<T>::get(query_id);
444

            
445
76
            let para_id = if let Some(para_id) = maybe_para_id {
446
76
                para_id
447
            } else {
448
                // Most probably entry was expired or removed in some other way. Let's return early.
449
                return Ok(());
450
            };
451

            
452
76
            QueryIdToParaId::<T>::remove(query_id);
453
76
            InFlightOrders::<T>::remove(para_id);
454

            
455
76
            match response {
456
32
                Response::DispatchResult(MaybeErrorCode::Success) => {
457
32
                    // Success. Add para id to pending block
458
32
                    let now = <frame_system::Pallet<T>>::block_number();
459
32
                    let ttl = T::PendingBlocksTtl::get();
460
32
                    PendingBlocks::<T>::insert(para_id, now.saturating_add(ttl));
461
32
                }
462
44
                Response::DispatchResult(_) => {
463
44
                    // We do not add paraid to pending block on failure
464
44
                }
465
                _ => {
466
                    // Unexpected.
467
                    return Err(Error::<T>::UnexpectedXCMResponse.into());
468
                }
469
            }
470

            
471
76
            Self::deposit_event(Event::ReceivedBuyCoreXCMResult { para_id, response });
472
76

            
473
76
            Ok(())
474
        }
475

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

            
486
4
            for para_id in expired_pending_blocks_para_id {
487
2
                let maybe_pending_block_ttl = PendingBlocks::<T>::get(para_id);
488
2
                if let Some(pending_block_ttl) = maybe_pending_block_ttl {
489
2
                    if pending_block_ttl < now {
490
1
                        PendingBlocks::<T>::remove(para_id);
491
1
                        cleaned_up_para_ids.push(para_id);
492
1
                    } else {
493
1
                        // Ignore if not expired
494
1
                    }
495
                }
496
            }
497

            
498
2
            Self::deposit_event(Event::CleanedUpExpiredPendingBlocksEntries {
499
2
                para_ids: cleaned_up_para_ids,
500
2
            });
501
2

            
502
2
            Ok(())
503
        }
504

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

            
515
4
            for para_id in expired_in_flight_orders {
516
2
                let maybe_in_flight_order = InFlightOrders::<T>::get(para_id);
517
2
                if let Some(in_flight_order) = maybe_in_flight_order {
518
2
                    if in_flight_order.ttl < now {
519
1
                        InFlightOrders::<T>::remove(para_id);
520
1
                        QueryIdToParaId::<T>::remove(in_flight_order.query_id);
521
1
                        cleaned_up_para_ids.push(para_id);
522
1
                    } else {
523
1
                        // Ignore if not expired
524
1
                    }
525
                }
526
            }
527

            
528
2
            Self::deposit_event(Event::CleanedUpExpiredInFlightOrderEntries {
529
2
                para_ids: cleaned_up_para_ids,
530
2
            });
531
2

            
532
2
            Ok(())
533
        }
534
    }
535

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

            
546
69
            [account_junction].into()
547
69
        }
548

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

            
561
69
            Ok(reanchored)
562
69
        }
563

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

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

            
596
            // Check that the para id is a parathread
597
48
            let parathread_params = T::GetParathreadParams::get_parathread_params(para_id)
598
48
                .ok_or(BuyingError::NotAParathread)?;
599

            
600
47
            let maybe_latest_author_info =
601
47
                T::LatestAuthorInfoFetcher::get_latest_author_info(para_id);
602
47
            if let Some(latest_author_info) = maybe_latest_author_info {
603
33
                let current_slot = T::SlotBeacon::slot();
604
33
                if !parathread_params.slot_frequency.should_parathread_buy_core(
605
33
                    Slot::from(u64::from(current_slot)),
606
33
                    T::BuyCoreSlotDrift::get(),
607
33
                    latest_author_info.latest_slot_number,
608
33
                ) {
609
                    // TODO: Take max slots to produce a block from config
610
2
                    return Err(BuyingError::NotAllowedToProduceBlockRightNow {
611
2
                        slot_frequency: parathread_params.slot_frequency,
612
2
                        max_slot_earlier_core_buying_permitted: Slot::from(2u64),
613
2
                        last_block_production_slot: latest_author_info.latest_slot_number,
614
2
                    });
615
31
                }
616
14
            }
617

            
618
45
            Ok(())
619
55
        }
620

            
621
        /// Send an XCM message to the relay chain to try to buy a core for this para_id.
622
55
        fn on_collator_instantaneous_core_requested(
623
55
            para_id: ParaId,
624
55
            maybe_collator_public_key: Option<<T as Config>::CollatorPublicKey>,
625
55
        ) -> DispatchResult {
626
55
            Self::is_core_buying_allowed(para_id, maybe_collator_public_key)
627
55
                .map_err(Into::<Error<T>>::into)?;
628

            
629
44
            let xcm_weights_storage =
630
45
                RelayXcmWeightConfig::<T>::get().ok_or(Error::<T>::XcmWeightStorageNotSet)?;
631

            
632
44
            let withdraw_amount = xcm_weights_storage.buy_execution_cost;
633
44

            
634
44
            // Use the account derived from the multilocation composed with DescendOrigin
635
44
            // Buy on-demand cores
636
44
            // Any failure should return everything to the derivative account
637
44

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

            
653
44
            // Assumption: derived account already has DOT
654
44
            // The balance should be enough to cover the `Withdraw` needed to `BuyExecution`, plus
655
44
            // the price of the core, which can change based on demand.
656
44
            let relay_asset_total: Asset = (Here, withdraw_amount).into();
657
44
            let refund_asset_filter: AssetFilter = AssetFilter::Wild(WildAsset::AllCounted(1));
658
44

            
659
44
            let interior_multilocation = Self::interior_multilocation(para_id);
660
            // The parathread tank account is derived from the tanssi sovereign account and the
661
            // parathread para id.
662
44
            let derived_account =
663
44
                Self::relay_relative_multilocation(interior_multilocation.clone())?;
664

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

            
670
44
            let notify_call = <T as Config>::RuntimeCall::from(Call::<T>::query_response {
671
44
                query_id: 0,
672
44
                response: Default::default(),
673
44
            });
674
44
            let notify_call_weight = notify_call.get_dispatch_info().call_weight;
675
44

            
676
44
            let notify_query_ttl = <frame_system::Pallet<T>>::block_number()
677
44
                .saturating_add(T::CoreBuyingXCMQueryTtl::get());
678
44

            
679
44
            // Send XCM to relay chain
680
44
            let relay_chain = Location::parent();
681
44
            let query_id = T::XCMNotifier::new_notify_query(
682
44
                relay_chain.clone(),
683
44
                notify_call,
684
44
                notify_query_ttl,
685
44
                interior_multilocation.clone(),
686
44
            );
687

            
688
44
            let message: Xcm<()> = Xcm::builder_unsafe()
689
44
                .descend_origin(interior_multilocation.clone())
690
44
                .withdraw_asset(Assets::from(vec![relay_asset_total.clone()]))
691
44
                .buy_execution(relay_asset_total, Unlimited)
692
44
                // Both in case of error and in case of success, we want to refund the unused weight
693
44
                .set_appendix(
694
44
                    Xcm::builder_unsafe()
695
44
                        .report_transact_status(QueryResponseInfo {
696
44
                            destination: T::UniversalLocation::get()
697
44
                                .invert_target(&relay_chain)
698
44
                                .map_err(|_| Error::<T>::LocationInversionFailed)?, // This location from the point of view of destination
699
44
                            query_id,
700
44
                            max_weight: notify_call_weight,
701
44
                        })
702
44
                        .refund_surplus()
703
44
                        .deposit_asset(refund_asset_filter, derived_account)
704
44
                        .build(),
705
44
                )
706
44
                .transact(origin, weight_at_most, call)
707
44
                .build();
708

            
709
            // We intentionally do not charge any fees
710
44
            let (ticket, _price) =
711
44
                T::XcmSender::validate(&mut Some(relay_chain), &mut Some(message))
712
44
                    .map_err(|_| Error::<T>::ErrorValidatingXCM)?;
713
44
            T::XcmSender::deliver(ticket).map_err(|_| Error::<T>::ErrorDeliveringXCM)?;
714
44
            Self::deposit_event(Event::BuyCoreXcmSent {
715
44
                para_id,
716
44
                transaction_status_query_id: query_id,
717
44
            });
718
44

            
719
44
            let in_flight_order_ttl =
720
44
                notify_query_ttl.saturating_add(T::AdditionalTtlForInflightOrders::get());
721
44
            InFlightOrders::<T>::insert(
722
44
                para_id,
723
44
                InFlightCoreBuyingOrder {
724
44
                    para_id,
725
44
                    query_id,
726
44
                    ttl: in_flight_order_ttl,
727
44
                },
728
44
            );
729
44

            
730
44
            QueryIdToParaId::<T>::insert(query_id, para_id);
731
44

            
732
44
            Ok(())
733
55
        }
734

            
735
75
        pub fn para_deregistered(para_id: ParaId) {
736
            // If para is deregistered we need to clean up in flight order, query id mapping
737
75
            if let Some(in_flight_order) = InFlightOrders::<T>::take(para_id) {
738
1
                InFlightOrders::<T>::remove(para_id);
739
1
                QueryIdToParaId::<T>::remove(in_flight_order.query_id);
740
74
            }
741

            
742
            // We need to clean the pending block entry if any
743
75
            PendingBlocks::<T>::remove(para_id);
744
75
        }
745
    }
746

            
747
    #[pallet::validate_unsigned]
748
    impl<T: Config> ValidateUnsigned for Pallet<T> {
749
        type Call = Call<T>;
750

            
751
56
        fn validate_unsigned(_source: TransactionSource, call: &Self::Call) -> TransactionValidity {
752
56
            if let Call::buy_core { para_id, proof } = call {
753
56
                let block_number = <frame_system::Pallet<T>>::block_number();
754
56

            
755
56
                let current_nonce = CollatorSignatureNonce::<T>::get(para_id);
756
56
                if proof.nonce != current_nonce {
757
14
                    return InvalidTransaction::Call.into();
758
42
                }
759
42

            
760
42
                let is_valid_collator =
761
42
                    T::CheckCollatorValidity::is_valid_collator(*para_id, proof.public_key.clone());
762
42
                if !is_valid_collator {
763
3
                    return InvalidTransaction::Call.into();
764
39
                }
765
39

            
766
39
                if !proof.verify_signature(*para_id) {
767
8
                    return InvalidTransaction::Call.into();
768
31
                }
769
31

            
770
31
                ValidTransaction::with_tag_prefix("XcmCoreBuyer")
771
31
                    .priority(T::UnsignedPriority::get())
772
31
                    // TODO: tags
773
31
                    .and_provides((block_number, para_id))
774
31
                    //.and_provides((current_session, authority_id))
775
31
                    //.longevity(
776
31
                    //    TryInto::<u64>::try_into(
777
31
                    //       T::NextSessionRotation::average_session_length() / 2u32.into(),
778
31
                    //    )
779
31
                    //        .unwrap_or(64_u64),
780
31
                    //)
781
31
                    .longevity(64)
782
31
                    .propagate(true)
783
31
                    .build()
784
            } else {
785
                InvalidTransaction::Call.into()
786
            }
787
56
        }
788
    }
789
}
790

            
791
pub trait GetPurchaseCoreCall<RelayChain> {
792
    /// Get the encoded call to buy a core for this `para_id`, with this `max_amount`.
793
    /// Returns the encoded call and its estimated weight.
794
    fn get_encoded(relay_chain: RelayChain, max_amount: u128, para_id: ParaId) -> Vec<u8>;
795
}
796

            
797
pub trait CheckCollatorValidity<AccountId, PublicKey> {
798
    fn is_valid_collator(para_id: ParaId, public_key: PublicKey) -> bool;
799

            
800
    #[cfg(feature = "runtime-benchmarks")]
801
    fn set_valid_collator(para_id: ParaId, account_id: AccountId, public_key: PublicKey);
802
}
803

            
804
pub trait GetParathreadMaxCorePrice {
805
    fn get_max_core_price(para_id: ParaId) -> Option<u128>;
806
}
807

            
808
impl GetParathreadMaxCorePrice for () {
809
20
    fn get_max_core_price(_para_id: ParaId) -> Option<u128> {
810
20
        None
811
20
    }
812
}
813

            
814
pub trait GetParathreadParams {
815
    fn get_parathread_params(para_id: ParaId) -> Option<ParathreadParams>;
816

            
817
    #[cfg(feature = "runtime-benchmarks")]
818
    fn set_parathread_params(para_id: ParaId, parathread_params: Option<ParathreadParams>);
819
}
820

            
821
/// Use `into_account_truncating` to convert a `ParaId` into a `[u8; 32]`.
822
pub struct ParaIdIntoAccountTruncating;
823

            
824
impl Convert<ParaId, [u8; 32]> for ParaIdIntoAccountTruncating {
825
357
    fn convert(para_id: ParaId) -> [u8; 32] {
826
357
        // Derive a 32 byte account id for a parathread. Note that this is not the address of
827
357
        // the relay chain parathread tank, but that address is derived from this.
828
357
        let account: dp_core::AccountId = para_id.into_account_truncating();
829
357

            
830
357
        account.into()
831
357
    }
832
}