cumulus_pallet_weight_reclaim/
lib.rs1#![cfg_attr(not(feature = "std"), no_std)]
26
27extern crate alloc;
28#[cfg(not(feature = "std"))]
29use alloc::vec::Vec;
30use codec::{Decode, DecodeWithMemTracking, Encode};
31use cumulus_primitives_storage_weight_reclaim::get_proof_size;
32use derive_where::derive_where;
33use frame_support::{
34 dispatch::{DispatchInfo, PostDispatchInfo},
35 pallet_prelude::Weight,
36 traits::Defensive,
37};
38use scale_info::TypeInfo;
39use sp_runtime::{
40 traits::{DispatchInfoOf, Dispatchable, Implication, PostDispatchInfoOf, TransactionExtension},
41 transaction_validity::{TransactionSource, TransactionValidityError, ValidTransaction},
42 DispatchResult,
43};
44
45#[cfg(feature = "runtime-benchmarks")]
46pub mod benchmarks;
47#[cfg(test)]
48mod tests;
49mod weights;
50
51pub use pallet::*;
52pub use weights::WeightInfo;
53
54const LOG_TARGET: &'static str = "runtime::storage_reclaim_pallet";
55
56#[frame_support::pallet]
59pub mod pallet {
60 use super::*;
61
62 #[pallet::pallet]
63 pub struct Pallet<T>(_);
64
65 #[pallet::config]
66 pub trait Config: frame_system::Config {
67 type WeightInfo: WeightInfo;
68 }
69}
70
71#[doc = docify::embed!("./src/tests.rs", Tx)]
75#[derive(Encode, Decode, DecodeWithMemTracking, TypeInfo)]
86#[derive_where(Clone, Eq, PartialEq, Default; S)]
87#[scale_info(skip_type_params(T))]
88pub struct StorageWeightReclaim<T, S>(pub S, core::marker::PhantomData<T>);
89
90impl<T, S> StorageWeightReclaim<T, S> {
91 pub fn new(s: S) -> Self {
93 Self(s, Default::default())
94 }
95}
96
97impl<T, S> From<S> for StorageWeightReclaim<T, S> {
98 fn from(s: S) -> Self {
99 Self::new(s)
100 }
101}
102
103impl<T, S: core::fmt::Debug> core::fmt::Debug for StorageWeightReclaim<T, S> {
104 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
105 #[cfg(feature = "std")]
106 let _ = write!(f, "StorageWeightReclaim<{:?}>", self.0);
107
108 #[cfg(not(feature = "std"))]
109 let _ = write!(f, "StorageWeightReclaim<wasm-stripped>");
110
111 Ok(())
112 }
113}
114
115impl<T: Config + Send + Sync, S: TransactionExtension<T::RuntimeCall>>
116 TransactionExtension<T::RuntimeCall> for StorageWeightReclaim<T, S>
117where
118 T::RuntimeCall: Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo>,
119{
120 const IDENTIFIER: &'static str = "StorageWeightReclaim<Use `metadata()`!>";
121
122 type Implicit = S::Implicit;
123
124 type Val = (Option<u64>, S::Val);
126
127 type Pre = (Option<u64>, S::Pre);
129
130 fn implicit(&self) -> Result<Self::Implicit, TransactionValidityError> {
131 self.0.implicit()
132 }
133
134 fn metadata() -> Vec<sp_runtime::traits::TransactionExtensionMetadata> {
135 let mut inner = S::metadata();
136 inner.push(sp_runtime::traits::TransactionExtensionMetadata {
137 identifier: "StorageWeightReclaim",
138 ty: scale_info::meta_type::<()>(),
139 implicit: scale_info::meta_type::<()>(),
140 });
141 inner
142 }
143
144 fn weight(&self, call: &T::RuntimeCall) -> Weight {
145 T::WeightInfo::storage_weight_reclaim().saturating_add(self.0.weight(call))
146 }
147
148 fn validate(
149 &self,
150 origin: T::RuntimeOrigin,
151 call: &T::RuntimeCall,
152 info: &DispatchInfoOf<T::RuntimeCall>,
153 len: usize,
154 self_implicit: Self::Implicit,
155 inherited_implication: &impl Implication,
156 source: TransactionSource,
157 ) -> Result<(ValidTransaction, Self::Val, T::RuntimeOrigin), TransactionValidityError> {
158 let proof_size = get_proof_size();
159
160 self.0
161 .validate(origin, call, info, len, self_implicit, inherited_implication, source)
162 .map(|(validity, val, origin)| (validity, (proof_size, val), origin))
163 }
164
165 fn prepare(
166 self,
167 val: Self::Val,
168 origin: &T::RuntimeOrigin,
169 call: &T::RuntimeCall,
170 info: &DispatchInfoOf<T::RuntimeCall>,
171 len: usize,
172 ) -> Result<Self::Pre, TransactionValidityError> {
173 let (proof_size, inner_val) = val;
174 self.0.prepare(inner_val, origin, call, info, len).map(|pre| (proof_size, pre))
175 }
176
177 fn post_dispatch_details(
178 pre: Self::Pre,
179 info: &DispatchInfoOf<T::RuntimeCall>,
180 post_info: &PostDispatchInfoOf<T::RuntimeCall>,
181 len: usize,
182 result: &DispatchResult,
183 ) -> Result<Weight, TransactionValidityError> {
184 let (proof_size_before_dispatch, inner_pre) = pre;
185
186 let mut post_info_with_inner = *post_info;
187 S::post_dispatch(inner_pre, info, &mut post_info_with_inner, len, result)?;
188
189 let inner_refund = if let (Some(before_weight), Some(after_weight)) =
190 (post_info.actual_weight, post_info_with_inner.actual_weight)
191 {
192 before_weight.saturating_sub(after_weight)
193 } else {
194 Weight::zero()
195 };
196
197 let Some(proof_size_before_dispatch) = proof_size_before_dispatch else {
198 return Ok(inner_refund);
200 };
201
202 let Some(proof_size_after_dispatch) = get_proof_size().defensive_proof(
203 "Proof recording enabled during prepare, now disabled. This should not happen.",
204 ) else {
205 return Ok(inner_refund);
206 };
207
208 let measured_proof_size =
210 proof_size_after_dispatch.saturating_sub(proof_size_before_dispatch);
211
212 let benchmarked_actual_weight = post_info_with_inner.calc_actual_weight(info);
217
218 let benchmarked_actual_proof_size = benchmarked_actual_weight.proof_size();
219 if benchmarked_actual_proof_size < measured_proof_size {
220 log::error!(
221 target: LOG_TARGET,
222 "Benchmarked storage weight smaller than consumed storage weight. \
223 benchmarked: {benchmarked_actual_proof_size} consumed: {measured_proof_size}"
224 );
225 } else {
226 log::trace!(
227 target: LOG_TARGET,
228 "Reclaiming storage weight. benchmarked: {benchmarked_actual_proof_size},
229 consumed: {measured_proof_size}"
230 );
231 }
232
233 let accurate_weight = benchmarked_actual_weight.set_proof_size(measured_proof_size);
234
235 let pov_size_missing_from_node = frame_system::BlockWeight::<T>::mutate(|current_weight| {
236 let already_reclaimed = frame_system::ExtrinsicWeightReclaimed::<T>::get();
237 current_weight.accrue(already_reclaimed, info.class);
238 current_weight.reduce(info.total_weight(), info.class);
239 current_weight.accrue(accurate_weight, info.class);
240
241 let block_size = frame_system::BlockSize::<T>::get().unwrap_or(0);
245 let node_side_pov_size = proof_size_after_dispatch.saturating_add(block_size.into());
246 let block_weight_proof_size = current_weight.total().proof_size();
247 let pov_size_missing_from_node =
248 node_side_pov_size.saturating_sub(block_weight_proof_size);
249 if pov_size_missing_from_node > 0 {
250 log::warn!(
251 target: LOG_TARGET,
252 "Node-side PoV size higher than runtime proof size weight. node-side: \
253 {node_side_pov_size} block_size: {block_size} runtime: \
254 {block_weight_proof_size}, missing: {pov_size_missing_from_node}. Setting to \
255 node-side proof size."
256 );
257 current_weight
258 .accrue(Weight::from_parts(0, pov_size_missing_from_node), info.class);
259 }
260
261 pov_size_missing_from_node
262 });
263
264 let accurate_unspent = info
268 .total_weight()
269 .saturating_sub(accurate_weight)
270 .saturating_sub(Weight::from_parts(0, pov_size_missing_from_node));
271 frame_system::ExtrinsicWeightReclaimed::<T>::put(accurate_unspent);
272
273 let already_unspent_in_tx_ext_pipeline = post_info.calc_unspent(info);
276 Ok(accurate_unspent.saturating_sub(already_unspent_in_tx_ext_pipeline))
277 }
278
279 fn bare_validate(
280 call: &T::RuntimeCall,
281 info: &DispatchInfoOf<T::RuntimeCall>,
282 len: usize,
283 ) -> frame_support::pallet_prelude::TransactionValidity {
284 S::bare_validate(call, info, len)
285 }
286
287 fn bare_validate_and_prepare(
288 call: &T::RuntimeCall,
289 info: &DispatchInfoOf<T::RuntimeCall>,
290 len: usize,
291 ) -> Result<(), TransactionValidityError> {
292 S::bare_validate_and_prepare(call, info, len)
293 }
294
295 fn bare_post_dispatch(
296 info: &DispatchInfoOf<T::RuntimeCall>,
297 post_info: &mut PostDispatchInfoOf<T::RuntimeCall>,
298 len: usize,
299 result: &DispatchResult,
300 ) -> Result<(), TransactionValidityError> {
301 S::bare_post_dispatch(info, post_info, len, result)?;
302
303 frame_system::Pallet::<T>::reclaim_weight(info, post_info)
304 }
305}