referrerpolicy=no-referrer-when-downgrade

frame_system/extensions/
check_genesis.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18use crate::{pallet_prelude::BlockNumberFor, Config, Pallet};
19use codec::{Decode, DecodeWithMemTracking, Encode};
20use scale_info::TypeInfo;
21use sp_runtime::{
22	impl_tx_ext_default,
23	traits::{TransactionExtension, Zero},
24	transaction_validity::TransactionValidityError,
25};
26
27/// Genesis hash check to provide replay protection between different networks.
28///
29/// # Transaction Validity
30///
31/// Note that while a transaction with invalid `genesis_hash` will fail to be decoded,
32/// the extension does not affect any other fields of `TransactionValidity` directly.
33#[derive(Encode, Decode, DecodeWithMemTracking, Clone, Eq, PartialEq, TypeInfo)]
34#[scale_info(skip_type_params(T))]
35pub struct CheckGenesis<T: Config + Send + Sync>(core::marker::PhantomData<T>);
36
37impl<T: Config + Send + Sync> core::fmt::Debug for CheckGenesis<T> {
38	#[cfg(feature = "std")]
39	fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
40		write!(f, "CheckGenesis")
41	}
42
43	#[cfg(not(feature = "std"))]
44	fn fmt(&self, _: &mut core::fmt::Formatter) -> core::fmt::Result {
45		Ok(())
46	}
47}
48
49impl<T: Config + Send + Sync> CheckGenesis<T> {
50	/// Creates new `TransactionExtension` to check genesis hash.
51	pub fn new() -> Self {
52		Self(core::marker::PhantomData)
53	}
54}
55
56impl<T: Config + Send + Sync> TransactionExtension<T::RuntimeCall> for CheckGenesis<T> {
57	const IDENTIFIER: &'static str = "CheckGenesis";
58	type Implicit = T::Hash;
59	fn implicit(&self) -> Result<Self::Implicit, TransactionValidityError> {
60		Ok(<Pallet<T>>::block_hash(BlockNumberFor::<T>::zero()))
61	}
62	type Val = ();
63	type Pre = ();
64	fn weight(&self, _: &T::RuntimeCall) -> sp_weights::Weight {
65		// All transactions will always read the hash of the genesis block, so to avoid
66		// charging this multiple times in a block we manually set the proof size to 0.
67		<T::ExtensionsWeightInfo as super::WeightInfo>::check_genesis().set_proof_size(0)
68	}
69	impl_tx_ext_default!(T::RuntimeCall; validate prepare);
70}