Skip to content
This repository has been archived by the owner on Nov 15, 2023. It is now read-only.

Commit

Permalink
s/OwnerInfo/CodeInfo/g;
Browse files Browse the repository at this point in the history
  • Loading branch information
agryaznov committed Jun 12, 2023
1 parent e6e3563 commit f4ffcf2
Show file tree
Hide file tree
Showing 5 changed files with 52 additions and 52 deletions.
6 changes: 3 additions & 3 deletions frame/contracts/src/benchmarking/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,12 +159,12 @@ where

/// Returns `true` iff all storage entries related to code storage exist.
fn code_exists(hash: &CodeHash<T>) -> bool {
<PristineCode<T>>::contains_key(hash) && <OwnerInfoOf<T>>::contains_key(&hash)
<PristineCode<T>>::contains_key(hash) && <CodeInfoOf<T>>::contains_key(&hash)
}

/// Returns `true` iff no storage entry related to code storage exist.
fn code_removed(hash: &CodeHash<T>) -> bool {
!<PristineCode<T>>::contains_key(hash) && !<OwnerInfoOf<T>>::contains_key(&hash)
!<PristineCode<T>>::contains_key(hash) && !<CodeInfoOf<T>>::contains_key(&hash)
}
}

Expand Down Expand Up @@ -434,7 +434,7 @@ benchmarks! {

// Removing code does not depend on the size of the contract because all the information
// needed to verify the removal claim (refcount, owner) is stored in a separate storage
// item (`OwnerInfoOf`).
// item (`CodeInfoOf`).
#[pov_mode = Measured]
remove_code {
let caller = whitelisted_caller();
Expand Down
10 changes: 5 additions & 5 deletions frame/contracts/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ use crate::{
exec::{AccountIdOf, ErrorOrigin, ExecError, Executable, Key, Stack as ExecStack},
gas::GasMeter,
storage::{meter::Meter as StorageMeter, ContractInfo, DeletionQueueManager},
wasm::{OwnerInfo, TryInstantiate, WasmBlob},
wasm::{CodeInfo, TryInstantiate, WasmBlob},
weights::WeightInfo,
};
use codec::{Codec, Decode, Encode, HasCompact};
Expand Down Expand Up @@ -931,7 +931,7 @@ pub mod pallet {

/// A mapping between an original code hash and its owner information.
#[pallet::storage]
pub(crate) type OwnerInfoOf<T: Config> = StorageMap<_, Identity, CodeHash<T>, OwnerInfo<T>>;
pub(crate) type CodeInfoOf<T: Config> = StorageMap<_, Identity, CodeHash<T>, CodeInfo<T>>;

/// This is a **monotonic** counter incremented on contract instantiation.
///
Expand Down Expand Up @@ -1225,12 +1225,12 @@ impl<T: Config> Invokable<T> for InstantiateInput<T> {
.map(|buffer| buffer.try_extend(&mut msg.bytes()));
err
})?;
let owner_info = executable.owner_info.clone();
let code_info = executable.code_info.clone();
// The open deposit will be charged during execution when the
// uploaded module does not already exist. This deposit is not part of the
// storage meter because it is not transferred to the contract but
// reserved on the uploading account.
(executable.open_deposit(owner_info), executable)
(executable.open_deposit(code_info), executable)
},
Code::Existing(hash) =>
(Default::default(), WasmBlob::from_storage(*hash, &schedule, &mut gas_meter)?),
Expand Down Expand Up @@ -1417,7 +1417,7 @@ impl<T: Config> Pallet<T> {
let module =
WasmBlob::from_code(code, &schedule, origin, determinism, TryInstantiate::Instantiate)
.map_err(|(err, _)| err)?;
let deposit = module.open_deposit(module.owner_info.clone());
let deposit = module.open_deposit(module.code_info.clone());
if let Some(storage_deposit_limit) = storage_deposit_limit {
ensure!(storage_deposit_limit >= deposit, <Error<T>>::StorageDepositLimitExhausted);
}
Expand Down
16 changes: 8 additions & 8 deletions frame/contracts/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,16 +83,16 @@ macro_rules! assert_return_code {

macro_rules! assert_refcount {
( $code_hash:expr , $should:expr $(,)? ) => {{
let is = crate::OwnerInfoOf::<Test>::get($code_hash).map(|m| m.refcount()).unwrap();
let is = crate::CodeInfoOf::<Test>::get($code_hash).map(|m| m.refcount()).unwrap();
assert_eq!(is, $should);
}};
}

pub mod test_utils {
use super::{Balances, DepositPerByte, DepositPerItem, Hash, SysConfig, Test};
use crate::{
exec::AccountIdOf, CodeHash, Config, ContractInfo, ContractInfoOf, Nonce, OwnerInfo,
OwnerInfoOf, PristineCode,
exec::AccountIdOf, CodeHash, CodeInfo, CodeInfoOf, Config, ContractInfo, ContractInfoOf,
Nonce, PristineCode,
};
use codec::{Encode, MaxEncodedLen};
use frame_support::traits::Currency;
Expand Down Expand Up @@ -124,15 +124,15 @@ pub mod test_utils {
}
pub fn expected_deposit(code_len: usize) -> u64 {
// For onwer info, the deposit for max_encoded_len is taken.
let owner_info_len = OwnerInfo::<Test>::max_encoded_len() as u64;
let code_info_len = CodeInfo::<Test>::max_encoded_len() as u64;
// Calculate deposit to be reserved.
// We add 2 storage items: one for code, other for owner_info
DepositPerByte::get().saturating_mul(code_len as u64 + owner_info_len) +
// We add 2 storage items: one for code, other for code_info
DepositPerByte::get().saturating_mul(code_len as u64 + code_info_len) +
DepositPerItem::get().saturating_mul(2)
}
pub fn ensure_stored(code_hash: CodeHash<Test>) -> usize {
// Assert that owner_info is stored
assert!(OwnerInfoOf::<Test>::contains_key(&code_hash));
// Assert that code_info is stored
assert!(CodeInfoOf::<Test>::contains_key(&code_hash));
// Assert that contract code is stored, and get its size.
PristineCode::<Test>::try_get(&code_hash).unwrap().len()
}
Expand Down
56 changes: 28 additions & 28 deletions frame/contracts/src/wasm/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ use crate::{
exec::{ExecResult, Executable, ExportedFunction, Ext},
gas::{GasMeter, Token},
weights::WeightInfo,
AccountIdOf, BadOrigin, BalanceOf, CodeHash, CodeVec, Config, Error, Event, OwnerInfoOf,
Pallet, PristineCode, Schedule, Weight, LOG_TARGET,
AccountIdOf, BadOrigin, BalanceOf, CodeHash, CodeInfoOf, CodeVec, Config, Error, Event, Pallet,
PristineCode, Schedule, Weight, LOG_TARGET,
};
use codec::{Decode, Encode, MaxEncodedLen};
use frame_support::{
Expand All @@ -65,21 +65,21 @@ pub struct WasmBlob<T: Config> {
code: CodeVec<T>,
// This isn't needed for contract execution and is not stored alongside it.
#[codec(skip)]
pub owner_info: OwnerInfo<T>,
pub code_info: CodeInfo<T>,
}

/// Contract code related data, such as:
///
/// - owner of the contract, i.e. account uploaded its code,
/// - storage deposit amount,
/// - reference count,
/// - determinism marker.
/// TODO: rename this struct to `CodeInfo`?
///
/// It is stored in a separate storage entry to avoid loading the code when not necessary.
#[derive(Clone, Encode, Decode, scale_info::TypeInfo, MaxEncodedLen)]
#[codec(mel_bound())]
#[scale_info(skip_type_params(T))]
pub struct OwnerInfo<T: Config> {
pub struct CodeInfo<T: Config> {
/// The account that has uploaded the contract code and hence is allowed to remove it.
owner: AccountIdOf<T>,
/// The amount of balance that was deposited by the owner in order to store it on-chain.
Expand Down Expand Up @@ -188,8 +188,8 @@ impl<T: Config> WasmBlob<T> {
///
/// Returns `0` if the module is already in storage and hence no deposit will
/// be charged when storing it.
pub fn open_deposit(&self, owner_info: OwnerInfo<T>) -> BalanceOf<T> {
<OwnerInfoOf<T>>::try_get(self.code_hash()).map_or(owner_info.deposit, |_| 0u32.into())
pub fn open_deposit(&self, code_info: CodeInfo<T>) -> BalanceOf<T> {
<CodeInfoOf<T>>::try_get(self.code_hash()).map_or(code_info.deposit, |_| 0u32.into())
}

/// Creates and returns an instance of the supplied code.
Expand Down Expand Up @@ -255,11 +255,11 @@ impl<T: Config> WasmBlob<T> {
/// storage.
fn store_code(mut module: Self, instantiated: bool) -> DispatchResult {
let code_hash = &module.code_hash();
<OwnerInfoOf<T>>::mutate(code_hash, |stored_owner_info| {
match stored_owner_info {
<CodeInfoOf<T>>::mutate(code_hash, |stored_code_info| {
match stored_code_info {
// Instantiate existing contract.
Some(stored_owner_info) if instantiated => {
stored_owner_info.refcount = stored_owner_info.refcount.checked_add(1).expect(
Some(stored_code_info) if instantiated => {
stored_code_info.refcount = stored_code_info.refcount.checked_add(1).expect(
"
refcount is 64bit. Generating this overflow would require to store
_at least_ 18 exabyte of data assuming that a contract consumes only
Expand All @@ -274,15 +274,15 @@ impl<T: Config> WasmBlob<T> {
Some(_) => Ok(()),
// Upload a new contract code.
//
// We need to store the code and its owner_info, and collect the deposit.
// We need to store the code and its code_info, and collect the deposit.
None => {
// This `None` case happens only in freshly uploaded modules. This means that
// the `owner` is always the origin of the current transaction.
T::Currency::reserve(&module.owner_info.owner, module.owner_info.deposit)
T::Currency::reserve(&module.code_info.owner, module.code_info.deposit)
.map_err(|_| <Error<T>>::StorageDepositNotEnoughFunds)?;
module.owner_info.refcount = if instantiated { 1 } else { 0 };
module.code_info.refcount = if instantiated { 1 } else { 0 };
<PristineCode<T>>::insert(code_hash, module.code);
*stored_owner_info = Some(module.owner_info);
*stored_code_info = Some(module.code_info);
<Pallet<T>>::deposit_event(
vec![*code_hash],
Event::CodeStored { code_hash: *code_hash },
Expand All @@ -295,11 +295,11 @@ impl<T: Config> WasmBlob<T> {

/// Try to remove code together with all associated information.
fn try_remove_code(origin: &T::AccountId, code_hash: CodeHash<T>) -> DispatchResult {
<OwnerInfoOf<T>>::try_mutate_exists(&code_hash, |existing| {
if let Some(owner_info) = existing {
ensure!(owner_info.refcount == 0, <Error<T>>::CodeInUse);
ensure!(&owner_info.owner == origin, BadOrigin); // TODO: what if origin is root?
T::Currency::unreserve(&owner_info.owner, owner_info.deposit);
<CodeInfoOf<T>>::try_mutate_exists(&code_hash, |existing| {
if let Some(code_info) = existing {
ensure!(code_info.refcount == 0, <Error<T>>::CodeInUse);
ensure!(&code_info.owner == origin, BadOrigin); // TODO: what if origin is root?
T::Currency::unreserve(&code_info.owner, code_info.deposit);
*existing = None;
<PristineCode<T>>::remove(&code_hash);
<Pallet<T>>::deposit_event(vec![code_hash], Event::CodeRemoved { code_hash });
Expand Down Expand Up @@ -332,7 +332,7 @@ impl<T: Config> WasmBlob<T> {
/// A contract whose reference count dropped to zero isn't automatically removed. A
/// `remove_code` transaction must be submitted by the original uploader to do so.
fn decrement_refcount(code_hash: CodeHash<T>) {
<OwnerInfoOf<T>>::mutate(code_hash, |existing| {
<CodeInfoOf<T>>::mutate(code_hash, |existing| {
if let Some(info) = existing {
info.refcount = info.refcount.saturating_sub(1);
}
Expand All @@ -346,7 +346,7 @@ impl<T: Config> WasmBlob<T> {
/// [`Error::CodeNotFound`] is returned if no stored code found having the specified
/// `code_hash`.
fn increment_refcount(code_hash: CodeHash<T>) -> Result<(), DispatchError> {
<OwnerInfoOf<T>>::mutate(code_hash, |existing| -> Result<(), DispatchError> {
<CodeInfoOf<T>>::mutate(code_hash, |existing| -> Result<(), DispatchError> {
if let Some(info) = existing {
info.refcount = info.refcount.saturating_add(1);
Ok(())
Expand Down Expand Up @@ -384,7 +384,7 @@ impl<T: Config> WasmBlob<T> {
}
}

impl<T: Config> OwnerInfo<T> {
impl<T: Config> CodeInfo<T> {
/// Return the refcount of the module.
#[cfg(test)]
pub fn refcount(&self) -> u64 {
Expand All @@ -400,13 +400,13 @@ impl<T: Config> Executable<T> for WasmBlob<T> {
) -> Result<Self, DispatchError> {
let code = Self::load_code(code_hash, gas_meter)?;
let code_hash = T::Hashing::hash(&code);
// We store `owner_info` at the same time as contract code,
// We store `code_info` at the same time as contract code,
// therefore this query shouldn't really fail.
// We consider its failure equal to `CodeNotFound`, as contract code without
// `owner_info` is unusable in this pallet.
let owner_info = <OwnerInfoOf<T>>::get(code_hash).ok_or(Error::<T>::CodeNotFound)?;
// `code_info` is unusable in this pallet.
let code_info = <CodeInfoOf<T>>::get(code_hash).ok_or(Error::<T>::CodeNotFound)?;

Ok(Self { code, owner_info })
Ok(Self { code, code_info })
}

fn add_user(code_hash: CodeHash<T>) -> Result<(), DispatchError> {
Expand Down Expand Up @@ -492,7 +492,7 @@ impl<T: Config> Executable<T> for WasmBlob<T> {
}

fn is_deterministic(&self) -> bool {
matches!(self.owner_info.determinism, Determinism::Enforced)
matches!(self.code_info.determinism, Determinism::Enforced)
}
}

Expand Down
16 changes: 8 additions & 8 deletions frame/contracts/src/wasm/prepare.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use crate::{
chain_extension::ChainExtension,
ensure,
storage::meter::Diff,
wasm::{runtime::AllowDeprecatedInterface, Determinism, Environment, OwnerInfo, WasmBlob},
wasm::{runtime::AllowDeprecatedInterface, CodeInfo, Determinism, Environment, WasmBlob},
AccountIdOf, CodeVec, Config, Error, Schedule, LOG_TARGET,
};
use codec::MaxEncodedLen;
Expand Down Expand Up @@ -409,7 +409,7 @@ where
/// - Imported memory (if any) doesn't reserve more memory than permitted by the `schedule`.
/// - All imported functions from the external environment match defined by `env` module.
///
/// Also constructs contract `owner_info` by calculating the storage deposit.
/// Also constructs contract `code_info` by calculating the storage deposit.
pub fn prepare<E, T>(
code: CodeVec<T>,
schedule: &Schedule<T>,
Expand All @@ -432,15 +432,15 @@ where
(<Error<T>>::CodeTooLarge.into(), "preparation altered the code")
);

// Calculate deposit for storing contract code and `owner_info` in two different storage items.
let bytes_added = code.len().saturating_add(<OwnerInfo<T>>::max_encoded_len()) as u32;
// Calculate deposit for storing contract code and `code_info` in two different storage items.
let bytes_added = code.len().saturating_add(<CodeInfo<T>>::max_encoded_len()) as u32;
let deposit = Diff { bytes_added, items_added: 2, ..Default::default() }
.update_contract::<T>(None)
.charge_or_zero();

let owner_info = OwnerInfo { owner, deposit, determinism, refcount: 0 };
let code_info = CodeInfo { owner, deposit, determinism, refcount: 0 };

Ok(WasmBlob { code, owner_info })
Ok(WasmBlob { code, code_info })
}

/// Alternate (possibly unsafe) preparation functions used only for benchmarking and testing.
Expand All @@ -463,15 +463,15 @@ pub mod benchmarking {
let _memory_limits = get_memory_limits(contract_module.scan_imports::<T>(&[])?, schedule)?;

let code = code.try_into().map_err(|_| "Code too large!")?;
let owner_info = OwnerInfo {
let code_info = CodeInfo {
owner,
// this is a helper function for benchmarking which skips deposit collection
deposit: Default::default(),
refcount: 0,
determinism: Determinism::Enforced,
};

Ok(WasmBlob { code, owner_info })
Ok(WasmBlob { code, code_info })
}
}

Expand Down

0 comments on commit f4ffcf2

Please sign in to comment.