referrerpolicy=no-referrer-when-downgrade

cumulus_pallet_weight_reclaim/
lib.rs

1// Copyright (C) Parity Technologies (UK) Ltd.
2// This file is part of Cumulus.
3// SPDX-License-Identifier: Apache-2.0
4
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// 	http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17//! Pallet and transaction extensions to reclaim PoV proof size weight after an extrinsic has been
18//! applied.
19//!
20//! This crate provides:
21//! * [`StorageWeightReclaim`] transaction extension: it must wrap the whole transaction extension
22//!   pipeline.
23//! * The pallet required for the transaction extensions weight information and benchmarks.
24
25#![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/// Pallet to use alongside the transaction extension [`StorageWeightReclaim`], the pallet provides
57/// weight information and benchmarks.
58#[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/// Storage weight reclaim mechanism.
72///
73/// This extension must wrap all the transaction extensions:
74#[doc = docify::embed!("./src/tests.rs", Tx)]
75/// This extension checks the size of the node-side storage proof before and after executing a given
76/// extrinsic using the proof size host function. The difference between benchmarked and used weight
77/// is reclaimed.
78///
79/// If the benchmark was underestimating the proof size, then it is added to the block weight.
80///
81/// For the time part of the weight, it does same as system `WeightReclaim` extension, it
82/// calculates the unused weight using the post information and reclaim the unused weight.
83/// So this extension can be used as a drop-in replacement for `WeightReclaim` extension for
84/// parachains.
85#[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	/// Create a new `StorageWeightReclaim` instance.
92	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	// Initial proof size and inner extension value.
125	type Val = (Option<u64>, S::Val);
126
127	// Initial proof size and inner extension pre.
128	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			// We have no proof size information, there is nothing we can do.
199			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		// The consumed proof size as measured by the host.
209		let measured_proof_size =
210			proof_size_after_dispatch.saturating_sub(proof_size_before_dispatch);
211
212		// The consumed weight as benchmarked. Calculated from post info and info.
213		// NOTE: `calc_actual_weight` will take the minimum of `post_info` and `info` weights.
214		// This means any underestimation of compute time in the pre dispatch info will not be
215		// taken into account.
216		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			// If we encounter a situation where the node-side proof size is already higher than
242			// what we have in the runtime bookkeeping, we add the difference to the `BlockWeight`.
243			// This prevents that the proof size grows faster than the runtime proof size.
244			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		// The saturation will happen if the pre-dispatch weight is underestimating the proof
265		// size or if the node-side proof size is higher than expected.
266		// In this case the extrinsic proof size weight reclaimed is 0 and not a negative reclaim.
267		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		// Call have already returned their unspent amount.
274		// (also transaction extension prior in the pipeline, but there shouldn't be any.)
275		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}