1// This file is part of Substrate.
23// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
56// 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.
1718use 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};
2627/// 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>);
3637impl<T: Config + Send + Sync> core::fmt::Debug for CheckGenesis<T> {
38#[cfg(feature = "std")]
39fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
40write!(f, "CheckGenesis")
41 }
4243#[cfg(not(feature = "std"))]
44fn fmt(&self, _: &mut core::fmt::Formatter) -> core::fmt::Result {
45Ok(())
46 }
47}
4849impl<T: Config + Send + Sync> CheckGenesis<T> {
50/// Creates new `TransactionExtension` to check genesis hash.
51pub fn new() -> Self {
52Self(core::marker::PhantomData)
53 }
54}
5556impl<T: Config + Send + Sync> TransactionExtension<T::RuntimeCall> for CheckGenesis<T> {
57const IDENTIFIER: &'static str = "CheckGenesis";
58type Implicit = T::Hash;
59fn implicit(&self) -> Result<Self::Implicit, TransactionValidityError> {
60Ok(<Pallet<T>>::block_hash(BlockNumberFor::<T>::zero()))
61 }
62type Val = ();
63type Pre = ();
64fn 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 }
69impl_tx_ext_default!(T::RuntimeCall; validate prepare);
70}