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