1#![cfg_attr(not(feature = "std"), no_std)]
26
27#[cfg(feature = "runtime-benchmarks")]
28mod benchmarking;
29#[cfg(test)]
30mod mock;
31#[cfg(test)]
32mod tests;
33pub mod weights;
34
35#[cfg(not(feature = "std"))]
36extern crate alloc;
37
38use frame_support::defensive_assert;
39use frame_support::dispatch::{
40 DispatchClass, DispatchErrorWithPostInfo, DispatchInfo, GetDispatchInfo, Pays, PostDispatchInfo,
41};
42use frame_support::storage::with_storage_layer;
43use frame_support::traits::fungible::{Inspect, Mutate};
44use frame_support::traits::tokens::{Fortitude, Precision, Preservation};
45use frame_support::traits::{
46 BeforeAllRuntimeMigrations, EnsureInherentsAreFirst, ExecuteBlock, Get, OffchainWorker,
47 OnFinalize, OnIdle, OnInitialize, OnPoll, OnRuntimeUpgrade, PostTransactions,
48};
49use frame_support::weights::{Weight, WeightToFee};
50use frame_system::pallet_prelude::*;
51pub use pallet::*;
52use parity_scale_codec::{Codec, Encode};
53use sp_runtime::traits::{
54 Applyable, Block as BlockT, CheckEqual, Checkable, Dispatchable, Header, NumberFor, One,
55 ValidateUnsigned, Zero,
56};
57use sp_runtime::transaction_validity::{
58 InvalidTransaction, TransactionSource, TransactionValidity, TransactionValidityError,
59};
60use sp_runtime::{ApplyExtrinsicResult, DispatchError, ExtrinsicInclusionMode};
61use sp_std::marker::PhantomData;
62use sp_std::prelude::*;
63
64pub type CheckedOf<E, C> = <E as Checkable<C>>::Checked;
65pub type CallOf<E, C> = <CheckedOf<E, C> as Applyable>::Call;
66pub type OriginOf<E, C> = <CallOf<E, C> as Dispatchable>::RuntimeOrigin;
67
68pub trait ExtrinsicStorageFees<T: Config> {
70 fn extract_signer(xt: ExtrinsicOf<T>) -> (Option<AccountIdOf<T>>, DispatchInfo);
72 fn on_storage_fees_charged(
74 charged_fees: BalanceOf<T>,
75 tx_size: u32,
76 ) -> Result<(), TransactionValidityError>;
77}
78
79type AccountIdOf<T> = <T as frame_system::Config>::AccountId;
80type BalanceOf<T> = <<T as Config>::Currency as Inspect<AccountIdOf<T>>>::Balance;
81type ExtrinsicOf<T> = <BlockOf<T> as BlockT>::Extrinsic;
82type BlockOf<T> = <T as frame_system::Config>::Block;
83type BlockHashOf<T> = <BlockOf<T> as BlockT>::Hash;
84
85#[frame_support::pallet]
88mod pallet {
89 use crate::weights::WeightInfo;
90 use crate::{BalanceOf, ExtrinsicStorageFees};
91 #[cfg(not(feature = "std"))]
92 use alloc::vec::Vec;
93 use frame_support::pallet_prelude::*;
94 use frame_support::traits::fungible::Mutate;
95 use frame_support::weights::WeightToFee;
96 use frame_system::SetCode;
97 use frame_system::pallet_prelude::*;
98 use sp_executive::{INHERENT_IDENTIFIER, InherentError, InherentType};
99
100 #[pallet::config]
101 pub trait Config: frame_system::Config {
102 type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
103 type WeightInfo: WeightInfo;
104 type Currency: Mutate<Self::AccountId>;
105 type LengthToFee: WeightToFee<Balance = BalanceOf<Self>>;
106 type ExtrinsicStorageFees: ExtrinsicStorageFees<Self>;
107 }
108
109 #[pallet::pallet]
110 #[pallet::without_storage_info]
111 pub struct Pallet<T>(_);
112
113 #[pallet::call]
114 impl<T: Config> Pallet<T> {
115 #[pallet::call_index(0)]
118 #[pallet::weight((T::WeightInfo::set_code(), DispatchClass::Mandatory))]
119 pub fn set_code(origin: OriginFor<T>, code: Vec<u8>) -> DispatchResult {
120 ensure_none(origin)?;
121 <frame_system::pallet::Pallet<T>>::can_set_code(&code)?;
122 <T as frame_system::Config>::OnSetCode::set_code(code)?;
123 Ok(())
124 }
125 }
126
127 #[pallet::inherent]
128 impl<T: Config> ProvideInherent for Pallet<T> {
129 type Call = Call<T>;
130 type Error = InherentError;
131 const INHERENT_IDENTIFIER: InherentIdentifier = INHERENT_IDENTIFIER;
132
133 fn create_inherent(data: &InherentData) -> Option<Self::Call> {
134 let inherent_data = data
135 .get_data::<InherentType>(&INHERENT_IDENTIFIER)
136 .expect("Executive inherent data not correctly encoded")
137 .expect("Executive inherent data must be provided");
138
139 inherent_data.maybe_code.map(|code| Call::set_code { code })
140 }
141
142 fn is_inherent_required(data: &InherentData) -> Result<Option<Self::Error>, Self::Error> {
143 let inherent_data = data
144 .get_data::<InherentType>(&INHERENT_IDENTIFIER)
145 .expect("Executive inherent data not correctly encoded")
146 .expect("Executive inherent data must be provided");
147
148 Ok(if inherent_data.maybe_code.is_none() {
149 None
150 } else {
151 Some(InherentError::MissingRuntimeCode)
152 })
153 }
154
155 fn check_inherent(call: &Self::Call, data: &InherentData) -> Result<(), Self::Error> {
156 let inherent_data = data
157 .get_data::<InherentType>(&INHERENT_IDENTIFIER)
158 .expect("Executive inherent data not correctly encoded")
159 .expect("Executive inherent data must be provided");
160
161 if let Some(provided_code) = inherent_data.maybe_code {
162 if let Call::set_code { code } = call
163 && code != &provided_code
164 {
165 return Err(InherentError::IncorrectRuntimeCode);
166 }
167 } else {
168 return Err(InherentError::MissingRuntimeCode);
169 }
170
171 Ok(())
172 }
173
174 fn is_inherent(call: &Self::Call) -> bool {
175 matches!(call, Call::set_code { .. })
176 }
177 }
178
179 #[pallet::event]
180 pub enum Event<T: Config> {}
181
182 #[pallet::hooks]
183 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
184 fn on_initialize(_block_number: BlockNumberFor<T>) -> Weight {
185 Weight::from_parts(1, 0)
187 }
188 }
189}
190
191pub struct Executive<
196 ExecutiveConfig,
197 Context,
198 UnsignedValidator,
199 AllPalletsWithSystem,
200 OnRuntimeUpgrade = (),
201>(
202 PhantomData<(
203 ExecutiveConfig,
204 Context,
205 UnsignedValidator,
206 AllPalletsWithSystem,
207 OnRuntimeUpgrade,
208 )>,
209);
210
211impl<
212 ExecutiveConfig: Config + frame_system::Config + EnsureInherentsAreFirst<BlockOf<ExecutiveConfig>>,
213 Context: Default,
214 UnsignedValidator,
215 AllPalletsWithSystem: OnRuntimeUpgrade
216 + BeforeAllRuntimeMigrations
217 + OnInitialize<BlockNumberFor<ExecutiveConfig>>
218 + OnIdle<BlockNumberFor<ExecutiveConfig>>
219 + OnFinalize<BlockNumberFor<ExecutiveConfig>>
220 + OffchainWorker<BlockNumberFor<ExecutiveConfig>>
221 + OnPoll<BlockNumberFor<ExecutiveConfig>>,
222 COnRuntimeUpgrade: OnRuntimeUpgrade,
223> ExecuteBlock<BlockOf<ExecutiveConfig>>
224 for Executive<
225 ExecutiveConfig,
226 Context,
227 UnsignedValidator,
228 AllPalletsWithSystem,
229 COnRuntimeUpgrade,
230 >
231where
232 ExtrinsicOf<ExecutiveConfig>: Checkable<Context> + Codec,
233 CheckedOf<ExtrinsicOf<ExecutiveConfig>, Context>: Applyable + GetDispatchInfo,
234 CallOf<ExtrinsicOf<ExecutiveConfig>, Context>:
235 Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo>,
236 OriginOf<ExtrinsicOf<ExecutiveConfig>, Context>: From<Option<AccountIdOf<ExecutiveConfig>>>,
237 UnsignedValidator: ValidateUnsigned<Call = CallOf<ExtrinsicOf<ExecutiveConfig>, Context>>,
238{
239 fn execute_block(block: BlockOf<ExecutiveConfig>) {
240 Executive::<
241 ExecutiveConfig,
242 Context,
243 UnsignedValidator,
244 AllPalletsWithSystem,
245 COnRuntimeUpgrade,
246 >::execute_block(block);
247 }
248}
249
250impl<
251 ExecutiveConfig: Config + frame_system::Config + EnsureInherentsAreFirst<BlockOf<ExecutiveConfig>>,
252 Context: Default,
253 UnsignedValidator,
254 AllPalletsWithSystem: OnRuntimeUpgrade
255 + BeforeAllRuntimeMigrations
256 + OnInitialize<BlockNumberFor<ExecutiveConfig>>
257 + OnIdle<BlockNumberFor<ExecutiveConfig>>
258 + OnFinalize<BlockNumberFor<ExecutiveConfig>>
259 + OffchainWorker<BlockNumberFor<ExecutiveConfig>>
260 + OnPoll<BlockNumberFor<ExecutiveConfig>>,
261 COnRuntimeUpgrade: OnRuntimeUpgrade,
262> Executive<ExecutiveConfig, Context, UnsignedValidator, AllPalletsWithSystem, COnRuntimeUpgrade>
263where
264 ExtrinsicOf<ExecutiveConfig>: Checkable<Context> + Codec,
265 CheckedOf<ExtrinsicOf<ExecutiveConfig>, Context>: Applyable + GetDispatchInfo,
266 CallOf<ExtrinsicOf<ExecutiveConfig>, Context>:
267 Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo>,
268 OriginOf<ExtrinsicOf<ExecutiveConfig>, Context>: From<Option<AccountIdOf<ExecutiveConfig>>>,
269 UnsignedValidator: ValidateUnsigned<Call = CallOf<ExtrinsicOf<ExecutiveConfig>, Context>>,
270{
271 pub fn storage_root() -> Vec<u8> {
273 let version = <ExecutiveConfig as frame_system::Config>::Version::get().state_version();
274 sp_io::storage::root(version)
275 }
276
277 pub fn execute_on_runtime_upgrade() -> Weight {
279 frame_executive::Executive::<
280 ExecutiveConfig,
281 BlockOf<ExecutiveConfig>,
282 Context,
283 UnsignedValidator,
284 AllPalletsWithSystem,
285 COnRuntimeUpgrade,
286 >::execute_on_runtime_upgrade()
287 }
288
289 pub fn initialize_block(header: &HeaderFor<ExecutiveConfig>) -> ExtrinsicInclusionMode {
293 frame_executive::Executive::<
294 ExecutiveConfig,
295 BlockOf<ExecutiveConfig>,
296 Context,
297 UnsignedValidator,
298 AllPalletsWithSystem,
299 COnRuntimeUpgrade,
300 >::initialize_block(header)
301 }
302
303 fn initial_checks(block: &BlockOf<ExecutiveConfig>) -> u32 {
305 sp_tracing::enter_span!(sp_tracing::Level::TRACE, "initial_checks");
306 let header = block.header();
307
308 let n = *header.number();
310 assert!(
311 n > BlockNumberFor::<ExecutiveConfig>::zero()
312 && <frame_system::Pallet<ExecutiveConfig>>::block_hash(
313 n - BlockNumberFor::<ExecutiveConfig>::one()
314 ) == *header.parent_hash(),
315 "Parent hash should be valid.",
316 );
317
318 match ExecutiveConfig::ensure_inherents_are_first(block) {
319 Ok(num) => num,
320 Err(i) => panic!("Invalid inherent position for extrinsic at index {i}"),
321 }
322 }
323
324 pub fn execute_block(block: BlockOf<ExecutiveConfig>) {
329 sp_io::init_tracing();
330 sp_tracing::within_span! {
331 sp_tracing::info_span!("execute_block", ?block);
332 let mode = Self::initialize_block(block.header());
334 let num_inherents = Self::initial_checks(&block) as usize;
335 let (header, extrinsics) = block.deconstruct();
336 let num_extrinsics = extrinsics.len();
337
338 if mode == ExtrinsicInclusionMode::OnlyInherents && num_extrinsics > num_inherents {
339 panic!("Only inherents are allowed in this block")
341 }
342
343 Self::apply_extrinsics(extrinsics.into_iter());
344
345 if !<frame_system::Pallet<ExecutiveConfig>>::inherents_applied() {
347 defensive_assert!(num_inherents == num_extrinsics);
348 frame_executive::Executive::<
349 ExecutiveConfig,
350 BlockOf<ExecutiveConfig>,
351 Context,
352 UnsignedValidator,
353 AllPalletsWithSystem,
354 COnRuntimeUpgrade,
355 >::inherents_applied();
356 }
357
358 <frame_system::Pallet<ExecutiveConfig>>::note_finished_extrinsics();
359 <ExecutiveConfig as frame_system::Config>::PostTransactions::post_transactions();
360
361 Self::idle_and_finalize_hook(*header.number());
362 Self::final_checks(&header);
363 }
364 }
365
366 fn apply_extrinsics(extrinsics: impl Iterator<Item = ExtrinsicOf<ExecutiveConfig>>) {
368 extrinsics.into_iter().for_each(|e| {
369 if let Err(e) = Self::apply_extrinsic(e) {
370 let err: &'static str = e.into();
371 panic!("{}", err)
372 }
373 });
374 }
375
376 pub fn finalize_block() -> HeaderFor<ExecutiveConfig> {
378 frame_executive::Executive::<
379 ExecutiveConfig,
380 BlockOf<ExecutiveConfig>,
381 Context,
382 UnsignedValidator,
383 AllPalletsWithSystem,
384 COnRuntimeUpgrade,
385 >::finalize_block()
386 }
387
388 fn idle_and_finalize_hook(block_number: NumberFor<BlockOf<ExecutiveConfig>>) {
390 let weight = <frame_system::Pallet<ExecutiveConfig>>::block_weight();
391 let max_weight = <<ExecutiveConfig as frame_system::Config>::BlockWeights as frame_support::traits::Get<_>>::get().max_block;
392 let remaining_weight = max_weight.saturating_sub(weight.total());
393
394 if remaining_weight.all_gt(Weight::zero()) {
395 let used_weight = AllPalletsWithSystem::on_idle(block_number, remaining_weight);
396 <frame_system::Pallet<ExecutiveConfig>>::register_extra_weight_unchecked(
397 used_weight,
398 DispatchClass::Mandatory,
399 );
400 }
401
402 AllPalletsWithSystem::on_finalize(block_number);
403 }
404
405 pub fn apply_extrinsic(uxt: ExtrinsicOf<ExecutiveConfig>) -> ApplyExtrinsicResult {
409 let res = with_storage_layer(|| {
411 frame_executive::Executive::<
412 ExecutiveConfig,
413 BlockOf<ExecutiveConfig>,
414 Context,
415 UnsignedValidator,
416 AllPalletsWithSystem,
417 COnRuntimeUpgrade,
418 >::apply_extrinsic(uxt.clone())
419 .map_err(|err| DispatchError::Other(err.into()))
420 });
421
422 match res {
434 Ok(dispatch_outcome) => Ok(dispatch_outcome),
435 Err(err) => {
436 let encoded = uxt.encode();
437 let (maybe_signer, dispatch_info) =
438 ExecutiveConfig::ExtrinsicStorageFees::extract_signer(uxt);
439 if dispatch_info.class == DispatchClass::Mandatory {
442 return Err(TransactionValidityError::Invalid(
443 InvalidTransaction::MandatoryValidation,
444 ));
445 }
446
447 if let Some(signer) = maybe_signer {
449 let storage_fees = ExecutiveConfig::LengthToFee::weight_to_fee(
450 &Weight::from_parts(encoded.len() as u64, 0),
451 );
452
453 let maybe_charged_fees = ExecutiveConfig::Currency::burn_from(
456 &signer,
457 storage_fees,
458 Preservation::Expendable,
459 Precision::BestEffort,
460 Fortitude::Force,
461 );
462
463 if let Ok(charged_fees) = maybe_charged_fees {
464 ExecutiveConfig::ExtrinsicStorageFees::on_storage_fees_charged(
465 charged_fees,
466 encoded.len() as u32,
467 )?;
468 }
469 }
470
471 <frame_system::Pallet<ExecutiveConfig>>::note_extrinsic(encoded);
473
474 let r = Err(DispatchErrorWithPostInfo {
477 post_info: PostDispatchInfo {
478 actual_weight: None,
479 pays_fee: Pays::No,
480 },
481 error: err,
482 });
483
484 <frame_system::Pallet<ExecutiveConfig>>::note_applied_extrinsic(&r, dispatch_info);
485 Ok(Err(err))
486 }
487 }
488 }
489
490 fn final_checks(header: &HeaderFor<ExecutiveConfig>) {
492 sp_tracing::enter_span!(sp_tracing::Level::TRACE, "final_checks");
493 let new_header = <frame_system::Pallet<ExecutiveConfig>>::finalize();
495
496 assert_eq!(
498 header.digest().logs().len(),
499 new_header.digest().logs().len(),
500 "Number of digest items must match that calculated."
501 );
502 let items_zip = header
503 .digest()
504 .logs()
505 .iter()
506 .zip(new_header.digest().logs().iter());
507 for (header_item, computed_item) in items_zip {
508 header_item.check_equal(computed_item);
509 assert_eq!(
510 header_item, computed_item,
511 "Digest item must match that calculated."
512 );
513 }
514
515 let storage_root = new_header.state_root();
517 header.state_root().check_equal(storage_root);
518 assert!(
519 header.state_root() == storage_root,
520 "Storage root must match that calculated."
521 );
522
523 assert!(
524 header.extrinsics_root() == new_header.extrinsics_root(),
525 "Transaction trie root must be valid.",
526 );
527 }
528
529 pub fn validate_transaction(
531 source: TransactionSource,
532 uxt: ExtrinsicOf<ExecutiveConfig>,
533 block_hash: BlockHashOf<ExecutiveConfig>,
534 ) -> TransactionValidity {
535 frame_executive::Executive::<
536 ExecutiveConfig,
537 BlockOf<ExecutiveConfig>,
538 Context,
539 UnsignedValidator,
540 AllPalletsWithSystem,
541 COnRuntimeUpgrade,
542 >::validate_transaction(source, uxt, block_hash)
543 }
544
545 pub fn offchain_worker(header: &HeaderFor<ExecutiveConfig>) {
547 frame_executive::Executive::<
548 ExecutiveConfig,
549 BlockOf<ExecutiveConfig>,
550 Context,
551 UnsignedValidator,
552 AllPalletsWithSystem,
553 COnRuntimeUpgrade,
554 >::offchain_worker(header)
555 }
556}