* Start to remove the `As` bound on `SimpleArtithmetic`

This just introduces standard numeric bounds, assuming a minimum of
`u32`. Also included is a saturating from/into trait allowing ergonomic
infallible conversion when you don't care if it saturates.

* Remove As from Balances trait

* Remove As from Aura module

* Remove As from Babe module

* Expunge `As` from contract

* Council module

* Democracy

* Finality tracker

* Grandpa

* First bit of indices

* indices

* Line lengths

* session

* system

* Staking

* Square up all other uses of As.

* RHD update

* Fix build/test

* Remove As trait

* line widths

* Remove final As ref

* Update srml/staking/src/lib.rs

Co-Authored-By: Bastian Köcher <bkchr@users.noreply.github.com>

* Update core/client/src/cht.rs

Co-Authored-By: Bastian Köcher <bkchr@users.noreply.github.com>

* Update core/client/db/src/light.rs

Co-Authored-By: Bastian Köcher <bkchr@users.noreply.github.com>

* Apply suggestions from code review

Co-Authored-By: Bastian Köcher <bkchr@users.noreply.github.com>

* whitespace

* Apply suggestions from code review

Co-Authored-By: Bastian Köcher <bkchr@users.noreply.github.com>
Co-Authored-By: André Silva <andre.beat@gmail.com>

* Bring back u32 check for number on CLI
This commit is contained in:
Gavin Wood
2019-05-22 23:11:38 +01:00
committed by GitHub
parent 36987c0205
commit 3860d7c810
60 changed files with 695 additions and 491 deletions
+2 -2
View File
@@ -140,10 +140,10 @@ impl<T: Trait> AccountDb<T> for DirectAccountDb {
for (k, v) in changed.storage.into_iter() {
if let Some(value) = child::get_raw(&new_info.trie_id[..], &blake2_256(&k)) {
new_info.storage_size -= value.len() as u64;
new_info.storage_size -= value.len() as u32;
}
if let Some(value) = v {
new_info.storage_size += value.len() as u64;
new_info.storage_size += value.len() as u32;
child::put_raw(&new_info.trie_id[..], &blake2_256(&k), &value[..]);
} else {
child::kill(&new_info.trie_id[..], &blake2_256(&k));
+4 -5
View File
@@ -16,7 +16,7 @@
use crate::{GasSpent, Module, Trait, BalanceOf, NegativeImbalanceOf};
use runtime_primitives::BLOCK_FULL;
use runtime_primitives::traits::{As, CheckedMul, CheckedSub, Zero};
use runtime_primitives::traits::{CheckedMul, CheckedSub, Zero, SaturatedConversion};
use srml_support::{StorageValue, traits::{OnUnbalanced, ExistenceRequirement, WithdrawReason, Currency, Imbalance}};
#[cfg(test)]
@@ -212,7 +212,7 @@ pub fn buy_gas<T: Trait>(
// Buy the specified amount of gas.
let gas_price = <Module<T>>::gas_price();
let cost = <T::Gas as As<BalanceOf<T>>>::as_(gas_limit.clone())
let cost = gas_limit.clone().into()
.checked_mul(&gas_price)
.ok_or("overflow multiplying gas limit by price")?;
@@ -248,7 +248,7 @@ pub fn refund_unused_gas<T: Trait>(
<GasSpent<T>>::mutate(|block_gas_spent| *block_gas_spent += gas_spent);
// Refund gas left by the price it was bought at.
let refund = <T::Gas as As<BalanceOf<T>>>::as_(gas_left) * gas_meter.gas_price;
let refund = gas_left.into() * gas_meter.gas_price;
let refund_imbalance = T::Currency::deposit_creating(transactor, refund);
if let Ok(imbalance) = imbalance.offset(refund_imbalance) {
T::GasPayment::on_unbalanced(imbalance);
@@ -258,8 +258,7 @@ pub fn refund_unused_gas<T: Trait>(
/// A little handy utility for converting a value in balance units into approximate value in gas units
/// at the given gas price.
pub fn approx_gas_for_balance<T: Trait>(gas_price: BalanceOf<T>, balance: BalanceOf<T>) -> T::Gas {
let amount_in_gas: BalanceOf<T> = balance / gas_price;
<T::Gas as As<BalanceOf<T>>>::sa(amount_in_gas)
(balance / gas_price).saturated_into::<T::Gas>()
}
/// A simple utility macro that helps to match against a
+26 -26
View File
@@ -94,10 +94,9 @@ use crate::account_db::{AccountDb, DirectAccountDb};
#[cfg(feature = "std")]
use serde::{Serialize, Deserialize};
use substrate_primitives::crypto::UncheckedFrom;
use rstd::prelude::*;
use rstd::marker::PhantomData;
use rstd::{prelude::*, marker::PhantomData, convert::TryFrom};
use parity_codec::{Codec, Encode, Decode};
use runtime_primitives::traits::{Hash, As, SimpleArithmetic, Bounded, StaticLookup, Zero};
use runtime_primitives::traits::{Hash, SimpleArithmetic, Bounded, StaticLookup, Zero};
use srml_support::dispatch::{Result, Dispatchable};
use srml_support::{Parameter, StorageMap, StorageValue, decl_module, decl_event, decl_storage, storage::child};
use srml_support::traits::{OnFreeBalanceZero, OnUnbalanced, Currency};
@@ -188,7 +187,7 @@ pub struct RawAliveContractInfo<CodeHash, Balance, BlockNumber> {
/// Unique ID for the subtree encoded as a bytes vector.
pub trie_id: TrieId,
/// The size of stored value in octet.
pub storage_size: u64,
pub storage_size: u32,
/// The code associated with a given account.
pub code_hash: CodeHash,
pub rent_allowance: Balance,
@@ -199,7 +198,7 @@ pub struct RawAliveContractInfo<CodeHash, Balance, BlockNumber> {
pub struct TombstoneContractInfo<T: Trait>(T::Hash);
impl<T: Trait> TombstoneContractInfo<T> {
fn new(storage_root: Vec<u8>, storage_size: u64, code_hash: CodeHash<T>) -> Self {
fn new(storage_root: Vec<u8>, storage_size: u32, code_hash: CodeHash<T>) -> Self {
let mut buf = Vec::new();
storage_root.using_encoded(|encoded| buf.extend_from_slice(encoded));
storage_size.using_encoded(|encoded| buf.extend_from_slice(encoded));
@@ -252,7 +251,8 @@ where
}
pub type BalanceOf<T> = <<T as Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::Balance;
pub type NegativeImbalanceOf<T> = <<T as Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::NegativeImbalance;
pub type NegativeImbalanceOf<T> =
<<T as Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::NegativeImbalance;
pub trait Trait: timestamp::Trait {
type Currency: Currency<Self::AccountId>;
@@ -263,8 +263,8 @@ pub trait Trait: timestamp::Trait {
/// The overarching event type.
type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
// `As<u32>` is needed for wasm-utils
type Gas: Parameter + Default + Codec + SimpleArithmetic + Bounded + Copy + As<BalanceOf<Self>> + As<u64> + As<u32>;
type Gas: Parameter + Default + Codec + SimpleArithmetic + Bounded + Copy +
Into<BalanceOf<Self>> + TryFrom<BalanceOf<Self>>;
/// A function type to get the contract address given the creator.
type DetermineContractAddress: ContractAddressFor<CodeHash<Self>, Self::AccountId>;
@@ -310,10 +310,10 @@ where
pub struct DefaultDispatchFeeComputor<T: Trait>(PhantomData<T>);
impl<T: Trait> ComputeDispatchFee<T::Call, BalanceOf<T>> for DefaultDispatchFeeComputor<T> {
fn compute_dispatch_fee(call: &T::Call) -> BalanceOf<T> {
let encoded_len = call.using_encoded(|encoded| encoded.len());
let encoded_len = call.using_encoded(|encoded| encoded.len() as u32);
let base_fee = <Module<T>>::transaction_base_fee();
let byte_fee = <Module<T>>::transaction_byte_fee();
base_fee + byte_fee * <BalanceOf<T> as As<u64>>::sa(encoded_len as u64)
base_fee + byte_fee * encoded_len.into()
}
}
@@ -553,7 +553,7 @@ decl_storage! {
TombstoneDeposit get(tombstone_deposit) config(): BalanceOf<T>;
/// Size of a contract at the time of creation. This is a simple way to ensure
/// that empty contracts eventually gets deleted.
StorageSizeOffset get(storage_size_offset) config(): u64;
StorageSizeOffset get(storage_size_offset) config(): u32;
/// Price of a byte of storage per one block interval. Should be greater than 0.
RentByteFee get(rent_byte_price) config(): BalanceOf<T>;
/// The amount of funds a contract should deposit in order to offset
@@ -576,17 +576,17 @@ decl_storage! {
/// The fee to be paid for making a transaction; the per-byte portion.
TransactionByteFee get(transaction_byte_fee) config(): BalanceOf<T>;
/// The fee required to create a contract instance.
ContractFee get(contract_fee) config(): BalanceOf<T> = BalanceOf::<T>::sa(21);
ContractFee get(contract_fee) config(): BalanceOf<T> = 21.into();
/// The base fee charged for calling into a contract.
CallBaseFee get(call_base_fee) config(): T::Gas = T::Gas::sa(135);
CallBaseFee get(call_base_fee) config(): T::Gas = 135.into();
/// The base fee charged for creating a contract.
CreateBaseFee get(create_base_fee) config(): T::Gas = T::Gas::sa(175);
CreateBaseFee get(create_base_fee) config(): T::Gas = 175.into();
/// The price of one unit of gas.
GasPrice get(gas_price) config(): BalanceOf<T> = BalanceOf::<T>::sa(1);
GasPrice get(gas_price) config(): BalanceOf<T> = 1.into();
/// The maximum nesting level of a call/create stack.
MaxDepth get(max_depth) config(): u32 = 100;
/// The maximum amount of gas that could be expended per block.
BlockGasLimit get(block_gas_limit) config(): T::Gas = T::Gas::sa(10_000_000);
BlockGasLimit get(block_gas_limit) config(): T::Gas = 10_000_000.into();
/// Gas spent so far in this block.
GasSpent get(gas_spent): T::Gas;
/// Current cost schedule for contracts.
@@ -692,19 +692,19 @@ pub struct Schedule<Gas> {
pub enable_println: bool,
}
impl<Gas: As<u64>> Default for Schedule<Gas> {
impl<Gas: From<u32>> Default for Schedule<Gas> {
fn default() -> Schedule<Gas> {
Schedule {
version: 0,
put_code_per_byte_cost: Gas::sa(1),
grow_mem_cost: Gas::sa(1),
regular_op_cost: Gas::sa(1),
return_data_per_byte_cost: Gas::sa(1),
event_data_per_byte_cost: Gas::sa(1),
event_per_topic_cost: Gas::sa(1),
event_base_cost: Gas::sa(1),
sandbox_data_read_cost: Gas::sa(1),
sandbox_data_write_cost: Gas::sa(1),
put_code_per_byte_cost: 1.into(),
grow_mem_cost: 1.into(),
regular_op_cost: 1.into(),
return_data_per_byte_cost: 1.into(),
event_data_per_byte_cost: 1.into(),
event_per_topic_cost: 1.into(),
event_base_cost: 1.into(),
sandbox_data_read_cost: 1.into(),
sandbox_data_write_cost: 1.into(),
max_event_topics: 4,
max_stack_height: 64 * 1024,
max_memory_pages: 16,
+5 -4
View File
@@ -15,7 +15,8 @@
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
use crate::{BalanceOf, ContractInfo, ContractInfoOf, Module, TombstoneContractInfo, Trait};
use runtime_primitives::traits::{As, Bounded, CheckedDiv, CheckedMul, Saturating, Zero};
use runtime_primitives::traits::{Bounded, CheckedDiv, CheckedMul, Saturating, Zero,
SaturatedConversion};
use srml_support::traits::{Currency, ExistenceRequirement, Imbalance, WithdrawReason};
use srml_support::StorageMap;
@@ -75,10 +76,10 @@ fn try_evict_or_and_pay_rent<T: Trait>(
let fee_per_block = {
let free_storage = balance
.checked_div(&<Module<T>>::rent_deposit_offset())
.unwrap_or(<BalanceOf<T>>::sa(0));
.unwrap_or_else(Zero::zero);
let effective_storage_size =
<BalanceOf<T>>::sa(contract.storage_size).saturating_sub(free_storage);
<BalanceOf<T>>::from(contract.storage_size).saturating_sub(free_storage);
effective_storage_size
.checked_mul(&<Module<T>>::rent_byte_price())
@@ -95,7 +96,7 @@ fn try_evict_or_and_pay_rent<T: Trait>(
let subsistence_threshold = T::Currency::minimum_balance() + <Module<T>>::tombstone_deposit();
let dues = fee_per_block
.checked_mul(&<BalanceOf<T>>::sa(blocks_passed.as_()))
.checked_mul(&blocks_passed.saturated_into::<u32>().into())
.unwrap_or(<BalanceOf<T>>::max_value());
let dues_limited = dues.min(contract.rent_allowance);
+9 -9
View File
@@ -21,8 +21,8 @@
use crate::account_db::{AccountDb, DirectAccountDb, OverlayAccountDb};
use crate::{
BalanceOf, ComputeDispatchFee, ContractAddressFor, ContractInfo, ContractInfoOf, GenesisConfig, Module,
RawAliveContractInfo, RawEvent, Trait, TrieId, TrieIdFromParentCounter, TrieIdGenerator,
BalanceOf, ComputeDispatchFee, ContractAddressFor, ContractInfo, ContractInfoOf, GenesisConfig,
Module, RawAliveContractInfo, RawEvent, Trait, TrieId, TrieIdFromParentCounter, TrieIdGenerator,
};
use assert_matches::assert_matches;
use hex_literal::*;
@@ -30,7 +30,7 @@ use parity_codec::{Decode, Encode, KeyedVec};
use runtime_io;
use runtime_io::with_externalities;
use runtime_primitives::testing::{Digest, DigestItem, Header, UintAuthorityId, H256};
use runtime_primitives::traits::{As, BlakeTwo256, IdentityLookup};
use runtime_primitives::traits::{BlakeTwo256, IdentityLookup};
use runtime_primitives::BuildStorage;
use srml_support::{
assert_ok, impl_outer_dispatch, impl_outer_event, impl_outer_origin, storage::child,
@@ -689,7 +689,7 @@ fn storage_size() {
Origin::signed(ALICE),
30_000,
100_000, HASH_SET_RENT.into(),
<Test as balances::Trait>::Balance::sa(1_000u64).encode() // rent allowance
<Test as balances::Trait>::Balance::from(1_000u32).encode() // rent allowance
));
let bob_contract = super::ContractInfoOf::<Test>::get(BOB).unwrap().get_alive().unwrap();
assert_eq!(bob_contract.storage_size, Contract::storage_size_offset() + 4);
@@ -719,7 +719,7 @@ fn deduct_blocks() {
Origin::signed(ALICE),
30_000,
100_000, HASH_SET_RENT.into(),
<Test as balances::Trait>::Balance::sa(1_000u64).encode() // rent allowance
<Test as balances::Trait>::Balance::from(1_000u32).encode() // rent allowance
));
// Check creation
@@ -812,7 +812,7 @@ fn claim_surcharge(blocks: u64, trigger_call: impl Fn() -> bool, removes: bool)
Origin::signed(ALICE),
100,
100_000, HASH_SET_RENT.into(),
<Test as balances::Trait>::Balance::sa(1_000u64).encode() // rent allowance
<Test as balances::Trait>::Balance::from(1_000u32).encode() // rent allowance
));
// Advance blocks
@@ -848,7 +848,7 @@ fn removals(trigger_call: impl Fn() -> bool) {
Origin::signed(ALICE),
100,
100_000, HASH_SET_RENT.into(),
<Test as balances::Trait>::Balance::sa(1_000u64).encode() // rent allowance
<Test as balances::Trait>::Balance::from(1_000u32).encode() // rent allowance
));
// Trigger rent must have no effect
@@ -882,7 +882,7 @@ fn removals(trigger_call: impl Fn() -> bool) {
Origin::signed(ALICE),
1_000,
100_000, HASH_SET_RENT.into(),
<Test as balances::Trait>::Balance::sa(100u64).encode() // rent allowance
<Test as balances::Trait>::Balance::from(100u32).encode() // rent allowance
));
// Trigger rent must have no effect
@@ -916,7 +916,7 @@ fn removals(trigger_call: impl Fn() -> bool) {
Origin::signed(ALICE),
50+Balances::minimum_balance(),
100_000, HASH_SET_RENT.into(),
<Test as balances::Trait>::Balance::sa(1_000u64).encode() // rent allowance
<Test as balances::Trait>::Balance::from(1_000u32).encode() // rent allowance
));
// Trigger rent must have no effect
@@ -29,7 +29,7 @@ use crate::gas::{GasMeter, Token};
use crate::wasm::{prepare, runtime::Env, PrefabWasmModule};
use crate::{CodeHash, CodeStorage, PristineCode, Schedule, Trait};
use rstd::prelude::*;
use runtime_primitives::traits::{As, CheckedMul, Hash, Bounded};
use runtime_primitives::traits::{CheckedMul, Hash, Bounded};
use srml_support::StorageMap;
/// Gas metering token that used for charging storing code into the code storage.
@@ -37,16 +37,15 @@ use srml_support::StorageMap;
/// Specifies the code length in bytes.
#[cfg_attr(test, derive(Debug, PartialEq, Eq))]
#[derive(Copy, Clone)]
pub struct PutCodeToken(u64);
pub struct PutCodeToken(u32);
impl<T: Trait> Token<T> for PutCodeToken {
type Metadata = Schedule<T::Gas>;
fn calculate_amount(&self, metadata: &Schedule<T::Gas>) -> T::Gas {
let code_len_in_gas = <T::Gas as As<u64>>::sa(self.0);
metadata
.put_code_per_byte_cost
.checked_mul(&code_len_in_gas)
.checked_mul(&self.0.into())
.unwrap_or_else(|| Bounded::max_value())
}
}
@@ -63,7 +62,7 @@ pub fn save<T: Trait>(
// The first time instrumentation is on the user. However, consequent reinstrumentation
// due to the schedule changes is on governance system.
if gas_meter
.charge(schedule, PutCodeToken(original_code.len() as u64))
.charge(schedule, PutCodeToken(original_code.len() as u32))
.is_out_of_gas()
{
return Err("there is not enough gas for storing the code");
@@ -195,7 +195,7 @@ macro_rules! define_env {
mod tests {
use parity_wasm::elements::FunctionType;
use parity_wasm::elements::ValueType;
use runtime_primitives::traits::{As, Zero};
use runtime_primitives::traits::Zero;
use sandbox::{self, ReturnValue, TypedValue};
use crate::wasm::tests::MockExt;
use crate::wasm::Runtime;
@@ -256,7 +256,7 @@ mod tests {
#[test]
fn macro_define_func() {
define_func!( <E: Ext> ext_gas (_ctx, amount: u32) => {
let amount = <<E::T as Trait>::Gas as As<u32>>::sa(amount);
let amount = <E::T as Trait>::Gas::from(amount);
if !amount.is_zero() {
Ok(())
} else {
@@ -308,7 +308,7 @@ mod tests {
define_env!(Env, <E: Ext>,
ext_gas( _ctx, amount: u32 ) => {
let amount = <<E::T as Trait>::Gas as As<u32>>::sa(amount);
let amount = <E::T as Trait>::Gas::from(amount);
if !amount.is_zero() {
Ok(())
} else {
+4 -4
View File
@@ -26,7 +26,7 @@ use parity_wasm::elements::{self, Internal, External, MemoryType, Type};
use pwasm_utils;
use pwasm_utils::rules;
use rstd::prelude::*;
use runtime_primitives::traits::As;
use runtime_primitives::traits::{UniqueSaturatedInto, SaturatedConversion};
struct ContractModule<'a, Gas: 'a> {
/// A deserialized module. The module is valid (this is Guaranteed by `new` method).
@@ -38,7 +38,7 @@ struct ContractModule<'a, Gas: 'a> {
schedule: &'a Schedule<Gas>,
}
impl<'a, Gas: 'a + As<u32> + Clone> ContractModule<'a, Gas> {
impl<'a, Gas: 'a + From<u32> + UniqueSaturatedInto<u32> + Clone> ContractModule<'a, Gas> {
/// Creates a new instance of `ContractModule`.
///
/// Returns `Err` if the `original_code` couldn't be decoded or
@@ -85,10 +85,10 @@ impl<'a, Gas: 'a + As<u32> + Clone> ContractModule<'a, Gas> {
fn inject_gas_metering(&mut self) -> Result<(), &'static str> {
let gas_rules =
rules::Set::new(
self.schedule.regular_op_cost.clone().as_(),
self.schedule.regular_op_cost.clone().saturated_into(),
Default::default(),
)
.with_grow_cost(self.schedule.grow_mem_cost.clone().as_())
.with_grow_cost(self.schedule.grow_mem_cost.clone().saturated_into())
.with_forbidden_floats();
let module = self
+10 -11
View File
@@ -27,7 +27,7 @@ use system;
use rstd::prelude::*;
use rstd::mem;
use parity_codec::{Decode, Encode};
use runtime_primitives::traits::{As, CheckedMul, CheckedAdd, Bounded};
use runtime_primitives::traits::{CheckedMul, CheckedAdd, Bounded, SaturatedConversion};
/// Enumerates all possible *special* trap conditions.
///
@@ -122,24 +122,24 @@ impl<T: Trait> Token<T> for RuntimeToken<T::Gas> {
fn calculate_amount(&self, metadata: &Schedule<T::Gas>) -> T::Gas {
use self::RuntimeToken::*;
let value = match *self {
Explicit(amount) => Some(<T::Gas as As<u32>>::sa(amount)),
Explicit(amount) => Some(amount.into()),
ReadMemory(byte_count) => metadata
.sandbox_data_read_cost
.checked_mul(&<T::Gas as As<u32>>::sa(byte_count)),
.checked_mul(&byte_count.into()),
WriteMemory(byte_count) => metadata
.sandbox_data_write_cost
.checked_mul(&<T::Gas as As<u32>>::sa(byte_count)),
.checked_mul(&byte_count.into()),
ReturnData(byte_count) => metadata
.return_data_per_byte_cost
.checked_mul(&<T::Gas as As<u32>>::sa(byte_count)),
.checked_mul(&byte_count.into()),
DepositEvent(topic_count, data_byte_count) => {
let data_cost = metadata
.event_data_per_byte_cost
.checked_mul(&<T::Gas as As<u32>>::sa(data_byte_count));
.checked_mul(&data_byte_count.into());
let topics_cost = metadata
.event_per_topic_cost
.checked_mul(&<T::Gas as As<u32>>::sa(topic_count));
.checked_mul(&topic_count.into());
data_cost
.and_then(|data_cost| {
@@ -340,7 +340,7 @@ define_env!(Env, <E: Ext>,
let nested_gas_limit = if gas == 0 {
ctx.gas_meter.gas_left()
} else {
<<E::T as Trait>::Gas as As<u64>>::sa(gas)
gas.saturated_into()
};
let ext = &mut ctx.ext;
let call_outcome = ctx.gas_meter.with_nested(nested_gas_limit, |nested_meter| {
@@ -413,7 +413,7 @@ define_env!(Env, <E: Ext>,
let nested_gas_limit = if gas == 0 {
ctx.gas_meter.gas_left()
} else {
<<E::T as Trait>::Gas as As<u64>>::sa(gas)
gas.saturated_into()
};
let ext = &mut ctx.ext;
let instantiate_outcome = ctx.gas_meter.with_nested(nested_gas_limit, |nested_meter| {
@@ -535,8 +535,7 @@ define_env!(Env, <E: Ext>,
// Load the latest block timestamp into the scratch buffer
ext_now(ctx) => {
let now: u64 = As::as_(ctx.ext.now().clone());
ctx.scratch_buf = now.encode();
ctx.scratch_buf = ctx.ext.now().encode();
Ok(())
},