pallet_subspace/
extensions.rs1#[cfg(feature = "runtime-benchmarks")]
4pub mod benchmarking;
5pub mod weights;
6
7pub use crate::extensions::weights::WeightInfo;
8use crate::pallet::Call as SubspaceCall;
9use crate::{Config, Origin, Pallet as Subspace};
10use frame_support::pallet_prelude::{PhantomData, TypeInfo, Weight};
11use frame_system::pallet_prelude::{BlockNumberFor, RuntimeCallFor};
12use parity_scale_codec::{Decode, DecodeWithMemTracking, Encode};
13use scale_info::prelude::fmt;
14use sp_consensus_subspace::SignedVote;
15use sp_runtime::DispatchResult;
16use sp_runtime::traits::{
17 AsSystemOriginSigner, DispatchInfoOf, DispatchOriginOf, Dispatchable, Implication,
18 PostDispatchInfoOf, TransactionExtension, ValidateResult,
19};
20use sp_runtime::transaction_validity::{
21 InvalidTransaction, TransactionSource, TransactionValidityError, ValidTransaction,
22};
23
24pub trait MaybeSubspaceCall<Runtime>
26where
27 Runtime: Config,
28{
29 fn maybe_subspace_call(&self) -> Option<&SubspaceCall<Runtime>>;
30}
31
32#[derive(Debug)]
34pub enum ExtensionWeightData {
35 Validated(Weight),
37 Skipped,
39}
40
41#[derive(Encode, Decode, Clone, Eq, PartialEq, TypeInfo, DecodeWithMemTracking)]
43pub struct SubspaceExtension<Runtime>(PhantomData<Runtime>);
44
45impl<Runtime> SubspaceExtension<Runtime> {
46 pub fn new() -> Self {
47 Self(PhantomData)
48 }
49}
50
51impl<Runtime> Default for SubspaceExtension<Runtime> {
52 fn default() -> Self {
53 Self::new()
54 }
55}
56
57impl<T: Config> fmt::Debug for SubspaceExtension<T> {
58 #[cfg(feature = "std")]
59 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60 write!(f, "SubspaceExtension",)
61 }
62
63 #[cfg(not(feature = "std"))]
64 fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result {
65 Ok(())
66 }
67}
68
69impl<Runtime> SubspaceExtension<Runtime>
70where
71 Runtime: Config + scale_info::TypeInfo + fmt::Debug + Send + Sync,
72{
73 fn do_check_vote(
74 signed_vote: &SignedVote<BlockNumberFor<Runtime>, Runtime::Hash, Runtime::AccountId>,
75 source: TransactionSource,
76 ) -> Result<(ValidTransaction, Weight), TransactionValidityError> {
77 let pre_dispatch = source == TransactionSource::InBlock;
78 if pre_dispatch {
79 Subspace::<Runtime>::pre_dispatch_vote(signed_vote)
80 .map(|weight| (ValidTransaction::default(), weight))
81 } else {
82 Subspace::<Runtime>::validate_vote(signed_vote)
83 }
84 }
85
86 fn max_weight() -> Weight {
87 <Runtime as Config>::ExtensionWeightInfo::vote()
88 .max(<Runtime as Config>::ExtensionWeightInfo::vote_with_equivocation())
89 }
90}
91
92impl<Runtime> TransactionExtension<RuntimeCallFor<Runtime>> for SubspaceExtension<Runtime>
93where
94 Runtime: Config + scale_info::TypeInfo + fmt::Debug + Send + Sync,
95 <RuntimeCallFor<Runtime> as Dispatchable>::RuntimeOrigin:
96 AsSystemOriginSigner<<Runtime as frame_system::Config>::AccountId> + From<Origin> + Clone,
97 RuntimeCallFor<Runtime>: MaybeSubspaceCall<Runtime>,
98{
99 const IDENTIFIER: &'static str = "SubspaceExtension";
100 type Implicit = ();
101 type Val = ExtensionWeightData;
102 type Pre = ExtensionWeightData;
103
104 fn weight(&self, call: &RuntimeCallFor<Runtime>) -> Weight {
105 match call.maybe_subspace_call() {
106 Some(SubspaceCall::vote { .. }) => Self::max_weight(),
107 _ => Weight::zero(),
108 }
109 }
110
111 fn validate(
112 &self,
113 origin: DispatchOriginOf<RuntimeCallFor<Runtime>>,
114 call: &RuntimeCallFor<Runtime>,
115 _info: &DispatchInfoOf<RuntimeCallFor<Runtime>>,
116 _len: usize,
117 _self_implicit: Self::Implicit,
118 _inherited_implication: &impl Implication,
119 source: TransactionSource,
120 ) -> ValidateResult<Self::Val, RuntimeCallFor<Runtime>> {
121 if origin.as_system_origin_signer().is_some() {
123 return Ok((
124 ValidTransaction::default(),
125 ExtensionWeightData::Skipped,
126 origin,
127 ));
128 };
129
130 let subspace_call = match call.maybe_subspace_call() {
131 Some(subspace_call) => subspace_call,
132 None => {
133 return Ok((
134 ValidTransaction::default(),
135 ExtensionWeightData::Skipped,
136 origin,
137 ));
138 }
139 };
140
141 let (validity, weight_used) = match subspace_call {
142 SubspaceCall::vote { signed_vote } => Self::do_check_vote(signed_vote, source)?,
143 _ => return Err(InvalidTransaction::Call.into()),
144 };
145
146 Ok((
147 validity,
148 ExtensionWeightData::Validated(weight_used),
149 Origin::ValidatedUnsigned.into(),
150 ))
151 }
152
153 fn prepare(
154 self,
155 val: Self::Val,
156 _origin: &DispatchOriginOf<RuntimeCallFor<Runtime>>,
157 _call: &RuntimeCallFor<Runtime>,
158 _info: &DispatchInfoOf<RuntimeCallFor<Runtime>>,
159 _len: usize,
160 ) -> Result<Self::Pre, TransactionValidityError> {
161 Ok(val)
162 }
163
164 fn post_dispatch_details(
165 pre: Self::Pre,
166 _info: &DispatchInfoOf<RuntimeCallFor<Runtime>>,
167 _post_info: &PostDispatchInfoOf<RuntimeCallFor<Runtime>>,
168 _len: usize,
169 _result: &DispatchResult,
170 ) -> Result<Weight, TransactionValidityError> {
171 match pre {
172 ExtensionWeightData::Validated(used_weight) => {
174 Ok(Self::max_weight().saturating_sub(used_weight))
175 }
176 ExtensionWeightData::Skipped => Ok(Weight::zero()),
178 }
179 }
180}