pallet_revive/metering/
storage.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
18//! This module contains functions to meter the storage deposit.
19
20#[cfg(test)]
21mod tests;
22
23use super::{Nested, Root, State};
24use crate::{
25	storage::ContractInfo, BalanceOf, Config, ExecConfig, ExecOrigin as Origin, HoldReason, Pallet,
26	StorageDeposit as Deposit,
27};
28use alloc::vec::Vec;
29use core::{marker::PhantomData, mem};
30use frame_support::{traits::Get, DefaultNoBound, RuntimeDebugNoBound};
31use sp_runtime::{
32	traits::{Saturating, Zero},
33	DispatchError, FixedPointNumber, FixedU128,
34};
35
36#[cfg(test)]
37use num_traits::Bounded;
38
39/// Deposit that uses the native fungible's balance type.
40pub type DepositOf<T> = Deposit<BalanceOf<T>>;
41
42/// A production root storage meter that actually charges from its origin.
43pub type Meter<T> = RawMeter<T, ReservingExt, Root>;
44
45/// A production storage meter that actually charges from its origin.
46///
47/// This can be used where we want to be generic over the state (Root vs. Nested).
48pub type GenericMeter<T, S> = RawMeter<T, ReservingExt, S>;
49
50/// A trait that allows to decouple the metering from the charging of balance.
51///
52/// This mostly exists for testing so that the charging can be mocked.
53pub trait Ext<T: Config> {
54	/// This is called to inform the implementer that some balance should be charged due to
55	/// some interaction of the `origin` with a `contract`.
56	///
57	/// The balance transfer can either flow from `origin` to `contract` or the other way
58	/// around depending on whether `amount` constitutes a `Charge` or a `Refund`.
59	/// It will fail in case the `origin` has not enough balance to cover all storage deposits.
60	fn charge(
61		origin: &T::AccountId,
62		contract: &T::AccountId,
63		amount: &DepositOf<T>,
64		exec_config: &ExecConfig<T>,
65	) -> Result<(), DispatchError>;
66}
67
68/// This [`Ext`] is used for actual on-chain execution when balance needs to be charged.
69///
70/// It uses [`frame_support::traits::fungible::Mutate`] in order to do accomplish the reserves.
71pub enum ReservingExt {}
72
73/// A type that allows the metering of consumed or freed storage of a single contract call stack.
74#[derive(DefaultNoBound, RuntimeDebugNoBound)]
75pub struct RawMeter<T: Config, E, S: State> {
76	/// The limit of how much balance this meter is allowed to consume.
77	pub(crate) limit: Option<BalanceOf<T>>,
78	/// The amount of balance that was used in this meter and all of its already absorbed children.
79	total_deposit: DepositOf<T>,
80	/// The amount of storage changes that were recorded in this meter alone.
81	/// This has no meaning for Root meters and will always be Contribution::Checked(0)
82	own_contribution: Contribution<T>,
83	/// List of charges that should be applied at the end of a contract stack execution.
84	///
85	/// We only have one charge per contract hence the size of this vector is
86	/// limited by the maximum call depth.
87	charges: Vec<Charge<T>>,
88	/// The maximal consumed deposit that occurred at any point during the execution of this
89	/// storage deposit meter
90	max_charged: BalanceOf<T>,
91	/// True if this is the root meter.
92	///
93	/// Sometimes we cannot know at compile time.
94	pub(crate) is_root: bool,
95	/// Type parameter only used in impls.
96	_phantom: PhantomData<(E, S)>,
97}
98
99/// This type is used to describe a storage change when charging from the meter.
100#[derive(Default, RuntimeDebugNoBound)]
101pub struct Diff {
102	/// How many bytes were added to storage.
103	pub bytes_added: u32,
104	/// How many bytes were removed from storage.
105	pub bytes_removed: u32,
106	/// How many storage items were added to storage.
107	pub items_added: u32,
108	/// How many storage items were removed from storage.
109	pub items_removed: u32,
110}
111
112impl Diff {
113	/// Calculate how much of a charge or refund results from applying the diff and store it
114	/// in the passed `info` if any.
115	///
116	/// # Note
117	///
118	/// In case `None` is passed for `info` only charges are calculated. This is because refunds
119	/// are calculated pro rata of the existing storage within a contract and hence need extract
120	/// this information from the passed `info`.
121	pub fn update_contract<T: Config>(&self, info: Option<&mut ContractInfo<T>>) -> DepositOf<T> {
122		let per_byte = T::DepositPerByte::get();
123		let per_item = T::DepositPerChildTrieItem::get();
124		let bytes_added = self.bytes_added.saturating_sub(self.bytes_removed);
125		let items_added = self.items_added.saturating_sub(self.items_removed);
126		let mut bytes_deposit = Deposit::Charge(per_byte.saturating_mul((bytes_added).into()));
127		let mut items_deposit = Deposit::Charge(per_item.saturating_mul((items_added).into()));
128
129		// Without any contract info we can only calculate diffs which add storage
130		let info = if let Some(info) = info {
131			info
132		} else {
133			return bytes_deposit.saturating_add(&items_deposit)
134		};
135
136		// Refunds are calculated pro rata based on the accumulated storage within the contract
137		let bytes_removed = self.bytes_removed.saturating_sub(self.bytes_added);
138		let items_removed = self.items_removed.saturating_sub(self.items_added);
139		let ratio = FixedU128::checked_from_rational(bytes_removed, info.storage_bytes)
140			.unwrap_or_default()
141			.min(FixedU128::from_u32(1));
142		bytes_deposit = bytes_deposit
143			.saturating_add(&Deposit::Refund(ratio.saturating_mul_int(info.storage_byte_deposit)));
144		let ratio = FixedU128::checked_from_rational(items_removed, info.storage_items)
145			.unwrap_or_default()
146			.min(FixedU128::from_u32(1));
147		items_deposit = items_deposit
148			.saturating_add(&Deposit::Refund(ratio.saturating_mul_int(info.storage_item_deposit)));
149
150		// We need to update the contract info structure with the new deposits
151		info.storage_bytes =
152			info.storage_bytes.saturating_add(bytes_added).saturating_sub(bytes_removed);
153		info.storage_items =
154			info.storage_items.saturating_add(items_added).saturating_sub(items_removed);
155		match &bytes_deposit {
156			Deposit::Charge(amount) =>
157				info.storage_byte_deposit = info.storage_byte_deposit.saturating_add(*amount),
158			Deposit::Refund(amount) =>
159				info.storage_byte_deposit = info.storage_byte_deposit.saturating_sub(*amount),
160		}
161		match &items_deposit {
162			Deposit::Charge(amount) =>
163				info.storage_item_deposit = info.storage_item_deposit.saturating_add(*amount),
164			Deposit::Refund(amount) =>
165				info.storage_item_deposit = info.storage_item_deposit.saturating_sub(*amount),
166		}
167
168		bytes_deposit.saturating_add(&items_deposit)
169	}
170}
171
172impl Diff {
173	fn saturating_add(&self, rhs: &Self) -> Self {
174		Self {
175			bytes_added: self.bytes_added.saturating_add(rhs.bytes_added),
176			bytes_removed: self.bytes_removed.saturating_add(rhs.bytes_removed),
177			items_added: self.items_added.saturating_add(rhs.items_added),
178			items_removed: self.items_removed.saturating_add(rhs.items_removed),
179		}
180	}
181}
182
183/// The state of a contract.
184#[derive(RuntimeDebugNoBound, Clone, PartialEq, Eq)]
185pub enum ContractState<T: Config> {
186	Alive { amount: DepositOf<T> },
187	Terminated,
188}
189
190/// Records information to charge or refund a plain account.
191///
192/// All the charges are deferred to the end of a whole call stack. Reason is that by doing
193/// this we can do all the refunds before doing any charge. This way a plain account can use
194/// more deposit than it has balance as along as it is covered by a refund. This
195/// essentially makes the order of storage changes irrelevant with regard to the deposit system.
196/// The only exception is when a special (tougher) deposit limit is specified for a cross-contract
197/// call. In that case the limit is enforced once the call is returned, rolling it back if
198/// exhausted.
199#[derive(RuntimeDebugNoBound, Clone)]
200struct Charge<T: Config> {
201	contract: T::AccountId,
202	state: ContractState<T>,
203}
204
205/// Records the storage changes of a storage meter.
206#[derive(RuntimeDebugNoBound)]
207enum Contribution<T: Config> {
208	/// The contract the meter belongs to is alive and accumulates changes using a [`Diff`].
209	Alive(Diff),
210	/// The meter was checked against its limit using [`RawMeter::enforce_limit`] at the end of
211	/// its execution. In this process the [`Diff`] was converted into a [`Deposit`].
212	Checked(DepositOf<T>),
213}
214
215impl<T: Config> Contribution<T> {
216	/// See [`Diff::update_contract`].
217	fn update_contract(&self, info: Option<&mut ContractInfo<T>>) -> DepositOf<T> {
218		match self {
219			Self::Alive(diff) => diff.update_contract::<T>(info),
220			Self::Checked(deposit) => deposit.clone(),
221		}
222	}
223}
224
225impl<T: Config> Default for Contribution<T> {
226	fn default() -> Self {
227		Self::Alive(Default::default())
228	}
229}
230
231/// Functions that apply to all states.
232impl<T, E, S> RawMeter<T, E, S>
233where
234	T: Config,
235	E: Ext<T>,
236	S: State,
237{
238	/// Create a new child that has its `limit`.
239	///
240	/// This is called whenever a new subcall is initiated in order to track the storage
241	/// usage for this sub call separately. This is necessary because we want to exchange balance
242	/// with the current contract we are interacting with.
243	pub fn nested(&self, mut limit: Option<BalanceOf<T>>) -> RawMeter<T, E, Nested> {
244		if let (Some(new_limit), Some(old_limit)) = (limit, self.limit) {
245			limit = Some(new_limit.min(old_limit));
246		}
247
248		RawMeter { limit, ..Default::default() }
249	}
250
251	/// Reset this meter to its original setting.
252	pub fn reset(&mut self) {
253		self.own_contribution = Default::default();
254		self.total_deposit = Default::default();
255		self.charges = Default::default();
256		self.max_charged = Default::default();
257	}
258
259	/// Absorb a child that was spawned to handle a sub call.
260	///
261	/// This should be called whenever a sub call comes to its end and it is **not** reverted.
262	/// This does the actual balance transfer from/to `origin` and `contract` based on the
263	/// overall storage consumption of the call. It also updates the supplied contract info.
264	///
265	/// In case a contract reverted the child meter should just be dropped in order to revert
266	/// any changes it recorded.
267	///
268	/// # Parameters
269	///
270	/// - `absorbed`: The child storage meter that should be absorbed.
271	/// - `origin`: The origin that spawned the original root meter.
272	/// - `contract`: The contract's account that this sub call belongs to.
273	/// - `info`: The info of the contract in question. `None` if the contract was terminated.
274	pub fn absorb(
275		&mut self,
276		absorbed: RawMeter<T, E, Nested>,
277		contract: &T::AccountId,
278		info: Option<&mut ContractInfo<T>>,
279	) {
280		// We are now at the position to calculate the actual final net charge of `absorbed` as we
281		// now have the contract information `info`. Before that we only took net charges related to
282		// the contract storage into account but ignored net refunds.
283		// However, with this complete information there is no need to recalculate `max_charged` for
284		// `absorbed` here before we absorb it because the actual final net charge will not be more
285		// than the net charge we observed before (as we only ignored net refunds but not net
286		// charges).
287		self.max_charged = self
288			.max_charged
289			.max(self.consumed().saturating_add(&absorbed.max_charged()).charge_or_zero());
290
291		let own_deposit = absorbed.own_contribution.update_contract(info);
292		self.total_deposit = self
293			.total_deposit
294			.saturating_add(&absorbed.total_deposit)
295			.saturating_add(&own_deposit);
296		self.charges.extend_from_slice(&absorbed.charges);
297
298		self.recalulculate_max_charged();
299
300		if !own_deposit.is_zero() {
301			self.charges.push(Charge {
302				contract: contract.clone(),
303				state: ContractState::Alive { amount: own_deposit },
304			});
305		}
306	}
307
308	/// Absorb only the maximum charge of the child meter.
309	///
310	/// This should be called whenever a sub call ends and reverts.
311	///
312	/// # Parameters
313	///
314	/// - `absorbed`: The child storage meter
315	pub fn absorb_only_max_charged(&mut self, absorbed: RawMeter<T, E, Nested>) {
316		self.max_charged = self
317			.max_charged
318			.max(self.consumed().saturating_add(&absorbed.max_charged()).charge_or_zero());
319	}
320
321	/// Record a charge that has taken place externally.
322	///
323	/// This will not perform a charge. It just records it to reflect it in the
324	/// total amount of storage required for a transaction.
325	pub fn record_charge(&mut self, amount: &DepositOf<T>) {
326		self.total_deposit = self.total_deposit.saturating_add(amount);
327		self.recalulculate_max_charged();
328	}
329
330	/// The amount of balance that this meter has consumed.
331	///
332	/// This disregards any refunds pending in the current frame. This
333	/// is because we can calculate refunds only at the end of each frame.
334	pub fn consumed(&self) -> DepositOf<T> {
335		self.total_deposit.saturating_add(&self.own_contribution.update_contract(None))
336	}
337
338	/// Return the maximum consumed deposit at any point in the previous execution
339	pub fn max_charged(&self) -> DepositOf<T> {
340		Deposit::Charge(self.max_charged)
341	}
342
343	/// Recaluclate the max deposit value
344	fn recalulculate_max_charged(&mut self) {
345		self.max_charged = self.max_charged.max(self.consumed().charge_or_zero());
346	}
347
348	/// The amount of balance still available from the current meter.
349	///
350	/// This includes charges from the current frame but no refunds.
351	#[cfg(test)]
352	pub fn available(&self) -> BalanceOf<T> {
353		self.consumed()
354			.available(&self.limit.unwrap_or(BalanceOf::<T>::max_value()))
355			.unwrap_or_default()
356	}
357}
358
359/// Functions that only apply to the root state.
360impl<T, E> RawMeter<T, E, Root>
361where
362	T: Config,
363	E: Ext<T>,
364{
365	/// Create new storage limiting storage deposits to the passed `limit`.
366	///
367	/// If the limit is larger than what the origin can afford we will just fail
368	/// when collecting the deposits in `execute_postponed_deposits`.
369	pub fn new(limit: Option<BalanceOf<T>>) -> Self {
370		Self {
371			limit,
372			is_root: true,
373			own_contribution: Contribution::Checked(Default::default()),
374			..Default::default()
375		}
376	}
377
378	/// The total amount of deposit that should change hands as result of the execution
379	/// that this meter was passed into. This will also perform all the charges accumulated
380	/// in the whole contract stack.
381	pub fn execute_postponed_deposits(
382		&mut self,
383		origin: &Origin<T>,
384		exec_config: &ExecConfig<T>,
385	) -> Result<DepositOf<T>, DispatchError> {
386		// Only refund or charge deposit if the origin is not root.
387		let origin = match origin {
388			Origin::Root => return Ok(Deposit::Charge(Zero::zero())),
389			Origin::Signed(o) => o,
390		};
391
392		// Coalesce charges of the same contract
393		self.charges.sort_by(|a, b| a.contract.cmp(&b.contract));
394		self.charges = {
395			let mut coalesced: Vec<Charge<T>> = Vec::with_capacity(self.charges.len());
396			for mut ch in mem::take(&mut self.charges) {
397				if let Some(last) = coalesced.last_mut() {
398					if last.contract == ch.contract {
399						match (&mut last.state, &mut ch.state) {
400							(
401								ContractState::Alive { amount: last_amount },
402								ContractState::Alive { amount: ch_amount },
403							) => {
404								*last_amount = last_amount.saturating_add(&ch_amount);
405							},
406							(ContractState::Alive { amount }, ContractState::Terminated) |
407							(ContractState::Terminated, ContractState::Alive { amount }) => {
408								// undo all deposits made by a terminated contract
409								self.total_deposit = self.total_deposit.saturating_sub(&amount);
410								last.state = ContractState::Terminated;
411							},
412							(ContractState::Terminated, ContractState::Terminated) =>
413								debug_assert!(
414									false,
415									"We never emit two terminates for the same contract."
416								),
417						}
418						continue;
419					}
420				}
421				coalesced.push(ch);
422			}
423			coalesced
424		};
425
426		// refunds first so origin is able to pay for the charges using the refunds
427		for charge in self.charges.iter() {
428			if let ContractState::Alive { amount: amount @ Deposit::Refund(_) } = &charge.state {
429				E::charge(origin, &charge.contract, amount, exec_config)?;
430			}
431		}
432		for charge in self.charges.iter() {
433			if let ContractState::Alive { amount: amount @ Deposit::Charge(_) } = &charge.state {
434				E::charge(origin, &charge.contract, amount, exec_config)?;
435			}
436		}
437
438		Ok(self.total_deposit.clone())
439	}
440
441	/// Flag a `contract` as terminated.
442	///
443	/// This will signal to the meter to discard all charged and refunds incured by this
444	/// contract.
445	pub fn terminate(&mut self, contract: T::AccountId, refunded: BalanceOf<T>) {
446		self.total_deposit = self.total_deposit.saturating_add(&Deposit::Refund(refunded));
447		self.charges.push(Charge { contract, state: ContractState::Terminated });
448
449		// no need to recalculate max_charged here as the total consumed amount will just decrease
450		// with this extra refund
451	}
452}
453
454/// Functions that only apply to the nested state.
455impl<T: Config, E: Ext<T>> RawMeter<T, E, Nested> {
456	/// Charges `diff` from the meter.
457	pub fn charge(&mut self, diff: &Diff) {
458		match &mut self.own_contribution {
459			Contribution::Alive(own) => {
460				*own = own.saturating_add(diff);
461				self.recalulculate_max_charged();
462			},
463			_ => panic!("Charge is never called after termination; qed"),
464		};
465	}
466
467	/// Adds a charge without recording it in the contract info.
468	///
469	/// Use this method instead of [`Self::charge`] when the charge is not the result of a storage
470	/// change within the contract's child trie. This is the case when when the `code_hash` is
471	/// updated. [`Self::charge`] cannot be used here because we keep track of the deposit charge
472	/// separately from the storage charge.
473	///
474	/// If this functions is used the amount of the charge has to be stored by the caller somewhere
475	/// alese in order to be able to refund it.
476	pub fn charge_deposit(&mut self, contract: T::AccountId, amount: DepositOf<T>) {
477		// will not fail in a nested meter
478		self.record_charge(&amount);
479		self.charges.push(Charge { contract, state: ContractState::Alive { amount } });
480	}
481
482	/// Determine the actual final charge from the own contributions
483	pub fn finalize_own_contributions(&mut self, info: Option<&mut ContractInfo<T>>) {
484		let deposit = self.own_contribution.update_contract(info);
485		self.own_contribution = Contribution::Checked(deposit);
486
487		// no need to recalculate max_charged here as the consumed amount cannot increase
488		// when taking removed bytes/items into account
489	}
490}
491
492impl<T: Config> Ext<T> for ReservingExt {
493	fn charge(
494		origin: &T::AccountId,
495		contract: &T::AccountId,
496		amount: &DepositOf<T>,
497		exec_config: &ExecConfig<T>,
498	) -> Result<(), DispatchError> {
499		match amount {
500			Deposit::Charge(amount) | Deposit::Refund(amount) if amount.is_zero() => (),
501			Deposit::Charge(amount) => {
502				<Pallet<T>>::charge_deposit(
503					Some(HoldReason::StorageDepositReserve),
504					origin,
505					contract,
506					*amount,
507					exec_config,
508				)?;
509			},
510			Deposit::Refund(amount) => {
511				<Pallet<T>>::refund_deposit(
512					HoldReason::StorageDepositReserve,
513					contract,
514					origin,
515					*amount,
516					Some(exec_config),
517				)?;
518			},
519		}
520		Ok(())
521	}
522}