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
            RelayXcmWeightConfig::<T>::set(xcm_weights);
409
36

            
410
36
            Ok(())
411
        }
412

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

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

            
427
12
            Ok(())
428
        }
429

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

            
439
76
            let maybe_para_id = QueryIdToParaId::<T>::get(query_id);
440

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

            
448
76
            QueryIdToParaId::<T>::remove(query_id);
449
76
            InFlightOrders::<T>::remove(para_id);
450

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

            
467
76
            Self::deposit_event(Event::ReceivedBuyCoreXCMResult { para_id, response });
468
76

            
469
76
            Ok(())
470
        }
471

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

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

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

            
498
2
            Ok(())
499
        }
500

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

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

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

            
528
2
            Ok(())
529
        }
530
    }
531

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

            
542
69
            [account_junction].into()
543
69
        }
544

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

            
557
69
            Ok(reanchored)
558
69
        }
559

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

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

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

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

            
614
45
            Ok(())
615
55
        }
616

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

            
625
44
            let xcm_weights_storage =
626
45
                RelayXcmWeightConfig::<T>::get().ok_or(Error::<T>::XcmWeightStorageNotSet)?;
627

            
628
44
            let withdraw_amount = xcm_weights_storage.buy_execution_cost;
629
44

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

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

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

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

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

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

            
672
44
            let notify_query_ttl = <frame_system::Pallet<T>>::block_number()
673
44
                .saturating_add(T::CoreBuyingXCMQueryTtl::get());
674
44

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

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

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

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

            
726
44
            QueryIdToParaId::<T>::insert(query_id, para_id);
727
44

            
728
44
            Ok(())
729
55
        }
730

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

            
738
            // We need to clean the pending block entry if any
739
75
            PendingBlocks::<T>::remove(para_id);
740
75
        }
741
    }
742

            
743
    #[pallet::validate_unsigned]
744
    impl<T: Config> ValidateUnsigned for Pallet<T> {
745
        type Call = Call<T>;
746

            
747
56
        fn validate_unsigned(_source: TransactionSource, call: &Self::Call) -> TransactionValidity {
748
56
            if let Call::buy_core { para_id, proof } = call {
749
56
                let block_number = <frame_system::Pallet<T>>::block_number();
750
56

            
751
56
                let current_nonce = CollatorSignatureNonce::<T>::get(para_id);
752
56
                if proof.nonce != current_nonce {
753
14
                    return InvalidTransaction::Call.into();
754
42
                }
755
42

            
756
42
                let is_valid_collator =
757
42
                    T::CheckCollatorValidity::is_valid_collator(*para_id, proof.public_key.clone());
758
42
                if !is_valid_collator {
759
3
                    return InvalidTransaction::Call.into();
760
39
                }
761
39

            
762
39
                if !proof.verify_signature(*para_id) {
763
8
                    return InvalidTransaction::Call.into();
764
31
                }
765
31

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

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

            
793
pub trait CheckCollatorValidity<AccountId, PublicKey> {
794
    fn is_valid_collator(para_id: ParaId, public_key: PublicKey) -> bool;
795

            
796
    #[cfg(feature = "runtime-benchmarks")]
797
    fn set_valid_collator(para_id: ParaId, account_id: AccountId, public_key: PublicKey);
798
}
799

            
800
pub trait GetParathreadMaxCorePrice {
801
    fn get_max_core_price(para_id: ParaId) -> Option<u128>;
802
}
803

            
804
impl GetParathreadMaxCorePrice for () {
805
20
    fn get_max_core_price(_para_id: ParaId) -> Option<u128> {
806
20
        None
807
20
    }
808
}
809

            
810
pub trait GetParathreadParams {
811
    fn get_parathread_params(para_id: ParaId) -> Option<ParathreadParams>;
812

            
813
    #[cfg(feature = "runtime-benchmarks")]
814
    fn set_parathread_params(para_id: ParaId, parathread_params: Option<ParathreadParams>);
815
}
816

            
817
/// Use `into_account_truncating` to convert a `ParaId` into a `[u8; 32]`.
818
pub struct ParaIdIntoAccountTruncating;
819

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

            
826
357
        account.into()
827
357
    }
828
}