Skip to content

Commit

Permalink
Backport paritytech#7381
Browse files Browse the repository at this point in the history
This is a cherry-pick of e4783a6 commit
from 2.0.1 branch that resolves the arithmetic errors.

The bump of version to 2.0.1 has been omitted.
This backport can be dropped on upgrades to 2.0.1 or newer.
  • Loading branch information
thadouk committed Jan 20, 2021
1 parent 060c420 commit 996769a
Show file tree
Hide file tree
Showing 27 changed files with 62 additions and 56 deletions.
2 changes: 1 addition & 1 deletion client/cli/src/commands/export_blocks_cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ impl ExportBlocksCmd {
info!("DB path: {}", path.display());
}

let from = self.from.as_ref().and_then(|f| f.parse().ok()).unwrap_or(1);
let from = self.from.as_ref().and_then(|f| f.parse().ok()).unwrap_or(1u32);
let to = self.to.as_ref().and_then(|t| t.parse().ok());

let binary = self.binary;
Expand Down
2 changes: 1 addition & 1 deletion client/finality-grandpa/src/voting_rule.rs
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ impl<Block, B> Default for VotingRulesBuilder<Block, B> where
{
fn default() -> Self {
VotingRulesBuilder::new()
.add(BeforeBestBlockBy(2.into()))
.add(BeforeBestBlockBy(2u32.into()))
.add(ThreeQuartersOfTheUnfinalizedChain)
}
}
Expand Down
2 changes: 1 addition & 1 deletion client/informant/src/display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ fn speed<B: BlockT>(
} else {
// If the number of blocks can't be converted to a regular integer, then we need a more
// algebraic approach and we stay within the realm of integers.
let one_thousand = NumberFor::<B>::from(1_000);
let one_thousand = NumberFor::<B>::from(1_000u32);
let elapsed = NumberFor::<B>::from(
<u32 as TryFrom<_>>::try_from(elapsed_ms).unwrap_or(u32::max_value())
);
Expand Down
2 changes: 1 addition & 1 deletion client/network/src/light_client_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1429,7 +1429,7 @@ mod tests {
_: ChangesProof<B::Header>
) -> Result<Vec<(NumberFor<B>, u32)>, ClientError> {
match self.ok {
true => Ok(vec![(100.into(), 2)]),
true => Ok(vec![(100u32.into(), 2)]),
false => Err(ClientError::Backend("Test error".into())),
}
}
Expand Down
2 changes: 1 addition & 1 deletion client/service/src/chain_ops/export_blocks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ where
// Reached end of the chain.
None => return Poll::Ready(Ok(())),
}
if (block % 10000.into()).is_zero() {
if (block % 10000u32.into()).is_zero() {
info!("#{}", block);
}
if block == last {
Expand Down
4 changes: 2 additions & 2 deletions client/service/src/chain_ops/import_blocks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ impl<B: BlockT> Speedometer<B> {
/// Creates a fresh Speedometer.
fn new() -> Self {
Self {
best_number: NumberFor::<B>::from(0),
best_number: NumberFor::<B>::from(0u32),
last_number: None,
last_update: Instant::now(),
}
Expand Down Expand Up @@ -232,7 +232,7 @@ impl<B: BlockT> Speedometer<B> {
} else {
// If the number of blocks can't be converted to a regular integer, then we need a more
// algebraic approach and we stay within the realm of integers.
let one_thousand = NumberFor::<B>::from(1_000);
let one_thousand = NumberFor::<B>::from(1_000u32);
let elapsed = NumberFor::<B>::from(
<u32 as TryFrom<_>>::try_from(elapsed_ms).unwrap_or(u32::max_value())
);
Expand Down
4 changes: 2 additions & 2 deletions client/service/src/client/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ use sp_runtime::{
generic::{BlockId, SignedBlock, DigestItem},
traits::{
Block as BlockT, Header as HeaderT, Zero, NumberFor,
HashFor, SaturatedConversion, One, DigestFor,
HashFor, SaturatedConversion, One, DigestFor, UniqueSaturatedInto,
},
};
use sp_state_machine::{
Expand Down Expand Up @@ -1139,7 +1139,7 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
let mut ancestor = load_header(ancestor_hash)?;
let mut uncles = Vec::new();

for _generation in 0..max_generation.saturated_into() {
for _generation in 0u32..UniqueSaturatedInto::<u32>::unique_saturated_into(max_generation) {
let children = self.backend.blockchain().children(ancestor_hash)?;
uncles.extend(children.into_iter().filter(|h| h != &current_hash));
current_hash = ancestor_hash;
Expand Down
4 changes: 2 additions & 2 deletions client/service/src/metrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -316,9 +316,9 @@ impl MetricsService {
);

if let Some(metrics) = self.metrics.as_ref() {
let best_seen_block = net_status
let best_seen_block: Option<u64> = net_status
.best_seen_block
.map(|num: NumberFor<T>| num.unique_saturated_into() as u64);
.map(|num: NumberFor<T>| UniqueSaturatedInto::<u64>::unique_saturated_into(num));

if let Some(best_seen_block) = best_seen_block {
metrics.block_height.with_label_values(&["sync_target"]).set(best_seen_block);
Expand Down
2 changes: 1 addition & 1 deletion client/transaction-pool/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -569,7 +569,7 @@ impl<PoolApi, Block> MaintainedTransactionPool for BasicPool<PoolApi, Block>
let next_action = self.revalidation_strategy.lock().next(
block_number,
Some(std::time::Duration::from_secs(60)),
Some(20.into()),
Some(20u32.into()),
);
let revalidation_strategy = self.revalidation_strategy.clone();
let revalidation_queue = self.revalidation_queue.clone();
Expand Down
4 changes: 2 additions & 2 deletions frame/aura/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ pub trait Trait: pallet_timestamp::Trait {
decl_storage! {
trait Store for Module<T: Trait> as Aura {
/// The last timestamp.
LastTimestamp get(fn last) build(|_| 0.into()): T::Moment;
LastTimestamp get(fn last): T::Moment;

/// The current authorities
pub Authorities get(fn authorities): Vec<T::AuthorityId>;
Expand Down Expand Up @@ -196,7 +196,7 @@ impl<T: Trait> Module<T> {
pub fn slot_duration() -> T::Moment {
// we double the minimum block-period so each author can always propose within
// the majority of its slot.
<T as pallet_timestamp::Trait>::MinimumPeriod::get().saturating_mul(2.into())
<T as pallet_timestamp::Trait>::MinimumPeriod::get().saturating_mul(2u32.into())
}

fn on_timestamp_set(now: T::Moment, slot_duration: T::Moment) {
Expand Down
2 changes: 1 addition & 1 deletion frame/babe/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -371,7 +371,7 @@ impl<T: Trait> Module<T> {
pub fn slot_duration() -> T::Moment {
// we double the minimum block-period so each author can always propose within
// the majority of their slot.
<T as pallet_timestamp::Trait>::MinimumPeriod::get().saturating_mul(2.into())
<T as pallet_timestamp::Trait>::MinimumPeriod::get().saturating_mul(2u32.into())
}

/// Determine whether an epoch change should take place at this block.
Expand Down
4 changes: 2 additions & 2 deletions frame/benchmarking/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -820,7 +820,7 @@ macro_rules! impl_benchmark {

// Set the block number to at least 1 so events are deposited.
if $crate::Zero::is_zero(&frame_system::Module::<T>::block_number()) {
frame_system::Module::<T>::set_block_number(1.into());
frame_system::Module::<T>::set_block_number(1u32.into());
}

// Commit the externalities to the database, flushing the DB cache.
Expand Down Expand Up @@ -966,7 +966,7 @@ macro_rules! impl_benchmark_test {

// Set the block number to at least 1 so events are deposited.
if $crate::Zero::is_zero(&frame_system::Module::<T>::block_number()) {
frame_system::Module::<T>::set_block_number(1.into());
frame_system::Module::<T>::set_block_number(1u32.into());
}

// Run execution + verification
Expand Down
8 changes: 4 additions & 4 deletions frame/example-offchain-worker/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ decl_module! {
// to the storage and other included pallets.
//
// We can easily import `frame_system` and retrieve a block hash of the parent block.
let parent_hash = <system::Module<T>>::block_hash(block_number - 1.into());
let parent_hash = <system::Module<T>>::block_hash(block_number - 1u32.into());
debug::debug!("Current block: {:?} (parent hash: {:?})", block_number, parent_hash);

// It's a good practice to keep `fn offchain_worker()` function minimal, and move most
Expand Down Expand Up @@ -364,10 +364,10 @@ impl<T: Trait> Module<T> {
// transactions in a row. If a strict order is desired, it's better to use
// the storage entry for that. (for instance store both block number and a flag
// indicating the type of next transaction to send).
let transaction_type = block_number % 3.into();
let transaction_type = block_number % 3u32.into();
if transaction_type == Zero::zero() { TransactionType::Signed }
else if transaction_type == T::BlockNumber::from(1) { TransactionType::UnsignedForAny }
else if transaction_type == T::BlockNumber::from(2) { TransactionType::UnsignedForAll }
else if transaction_type == T::BlockNumber::from(1u32) { TransactionType::UnsignedForAny }
else if transaction_type == T::BlockNumber::from(2u32) { TransactionType::UnsignedForAll }
else { TransactionType::Raw }
},
// We are in the grace period, we should not send a transaction this time.
Expand Down
2 changes: 1 addition & 1 deletion frame/executive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -468,7 +468,7 @@ where
<AllModules as OffchainWorker<System::BlockNumber>>::offchain_worker(
// to maintain backward compatibility we call module offchain workers
// with parent block number.
header.number().saturating_sub(1.into())
header.number().saturating_sub(1u32.into())
)
}
}
Expand Down
4 changes: 2 additions & 2 deletions frame/grandpa/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,8 @@ benchmarks! {
}

note_stalled {
let delay = 1000.into();
let best_finalized_block_number = 1.into();
let delay = 1000u32.into();
let best_finalized_block_number = 1u32.into();

}: _(RawOrigin::Root, delay, best_finalized_block_number)
verify {
Expand Down
2 changes: 1 addition & 1 deletion frame/grandpa/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -447,7 +447,7 @@ impl<T: Trait> Module<T> {

// only allow the next forced change when twice the window has passed since
// this one.
<NextForced<T>>::put(scheduled_at + in_blocks * 2.into());
<NextForced<T>>::put(scheduled_at + in_blocks * 2u32.into());
}

<PendingChange<T>>::put(StoredPendingChange {
Expand Down
6 changes: 3 additions & 3 deletions frame/im-online/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -594,7 +594,7 @@ impl<T: Trait> Module<T> {

// clear the lock in case we have failed to send transaction.
if res.is_err() {
new_status.sent_at = 0.into();
new_status.sent_at = 0u32.into();
storage.set(&new_status);
}

Expand Down Expand Up @@ -635,7 +635,7 @@ impl<T: Trait> pallet_session::OneSessionHandler<T::AccountId> for Module<T> {
// Since we consider producing blocks as being online,
// the heartbeat is deferred a bit to prevent spamming.
let block_number = <frame_system::Module<T>>::block_number();
let half_session = T::SessionDuration::get() / 2.into();
let half_session = T::SessionDuration::get() / 2u32.into();
<HeartbeatAfter<T>>::put(block_number + half_session);

// Remember who the authorities are for the new session.
Expand Down Expand Up @@ -723,7 +723,7 @@ impl<T: Trait> frame_support::unsigned::ValidateUnsigned for Module<T> {
.priority(T::UnsignedPriority::get())
.and_provides((current_session, authority_id))
.longevity(TryInto::<u64>::try_into(
T::SessionDuration::get() / 2.into()
T::SessionDuration::get() / 2u32.into()
).unwrap_or(64_u64))
.propagate(true)
.build()
Expand Down
9 changes: 5 additions & 4 deletions frame/offences/benchmarking/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ struct Offender<T: Trait> {
}

fn bond_amount<T: Trait>() -> BalanceOf<T> {
T::Currency::minimum_balance().saturating_mul(10_000.into())
T::Currency::minimum_balance().saturating_mul(10_000u32.into())
}

fn create_offender<T: Trait>(n: u32, nominators: u32) -> Result<Offender<T>, &'static str> {
Expand All @@ -97,7 +97,7 @@ fn create_offender<T: Trait>(n: u32, nominators: u32) -> Result<Offender<T>, &'s
let reward_destination = RewardDestination::Staked;
let raw_amount = bond_amount::<T>();
// add twice as much balance to prevent the account from being killed.
let free_amount = raw_amount.saturating_mul(2.into());
let free_amount = raw_amount.saturating_mul(2u32.into());
T::Currency::make_free_balance_be(&stash, free_amount);
let amount: BalanceOf<T> = raw_amount.into();
Staking::<T>::bond(
Expand Down Expand Up @@ -243,7 +243,8 @@ benchmarks! {
verify {
// make sure the report was not deferred
assert!(Offences::<T>::deferred_offences().is_empty());
let slash_amount = slash_fraction * bond_amount::<T>().unique_saturated_into() as u32;
let bond_amount: u32 = UniqueSaturatedInto::<u32>::unique_saturated_into(bond_amount::<T>());
let slash_amount = slash_fraction * bond_amount;
let reward_amount = slash_amount * (1 + n) / 2;
let mut slash_events = raw_offenders.into_iter()
.flat_map(|offender| {
Expand Down Expand Up @@ -379,7 +380,7 @@ benchmarks! {
Offences::<T>::set_deferred_offences(deferred_offences);
assert!(!Offences::<T>::deferred_offences().is_empty());
}: {
Offences::<T>::on_initialize(0.into());
Offences::<T>::on_initialize(0u32.into());
}
verify {
// make sure that all deferred offences were reported with Ok status.
Expand Down
2 changes: 1 addition & 1 deletion frame/randomness-collective-flip/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ const RANDOM_MATERIAL_LEN: u32 = 81;

fn block_number_to_index<T: Trait>(block_number: T::BlockNumber) -> usize {
// on_initialize is called on the first block after genesis
let index = (block_number - 1.into()) % RANDOM_MATERIAL_LEN.into();
let index = (block_number - 1u32.into()) % RANDOM_MATERIAL_LEN.into();
index.try_into().ok().expect("Something % 81 is always smaller than usize; qed")
}

Expand Down
22 changes: 11 additions & 11 deletions frame/staking/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ pub fn create_validator_with_nominators<T: Trait>(
ErasRewardPoints::<T>::insert(current_era, reward);

// Create reward pool
let total_payout = T::Currency::minimum_balance() * 1000.into();
let total_payout = T::Currency::minimum_balance() * 1000u32.into();
<ErasValidatorReward<T>>::insert(current_era, total_payout);

Ok(v_stash)
Expand All @@ -119,7 +119,7 @@ benchmarks! {
let controller = create_funded_user::<T>("controller", USER_SEED, 100);
let controller_lookup: <T::Lookup as StaticLookup>::Source = T::Lookup::unlookup(controller.clone());
let reward_destination = RewardDestination::Staked;
let amount = T::Currency::minimum_balance() * 10.into();
let amount = T::Currency::minimum_balance() * 10u32.into();
do_whitelist!(stash);
}: _(RawOrigin::Signed(stash.clone()), controller_lookup, amount, reward_destination)
verify {
Expand All @@ -129,7 +129,7 @@ benchmarks! {

bond_extra {
let (stash, controller) = create_stash_controller::<T>(USER_SEED, 100, Default::default())?;
let max_additional = T::Currency::minimum_balance() * 10.into();
let max_additional = T::Currency::minimum_balance() * 10u32.into();
let ledger = Ledger::<T>::get(&controller).ok_or("ledger not created before")?;
let original_bonded: BalanceOf<T> = ledger.active;
do_whitelist!(stash);
Expand All @@ -142,7 +142,7 @@ benchmarks! {

unbond {
let (_, controller) = create_stash_controller::<T>(USER_SEED, 100, Default::default())?;
let amount = T::Currency::minimum_balance() * 10.into();
let amount = T::Currency::minimum_balance() * 10u32.into();
let ledger = Ledger::<T>::get(&controller).ok_or("ledger not created before")?;
let original_bonded: BalanceOf<T> = ledger.active;
do_whitelist!(controller);
Expand All @@ -159,7 +159,7 @@ benchmarks! {
let s in 0 .. MAX_SPANS;
let (stash, controller) = create_stash_controller::<T>(0, 100, Default::default())?;
add_slashing_spans::<T>(&stash, s);
let amount = T::Currency::minimum_balance() * 5.into(); // Half of total
let amount = T::Currency::minimum_balance() * 5u32.into(); // Half of total
Staking::<T>::unbond(RawOrigin::Signed(controller.clone()).into(), amount)?;
CurrentEra::put(EraIndex::max_value());
let ledger = Ledger::<T>::get(&controller).ok_or("ledger not created before")?;
Expand All @@ -178,7 +178,7 @@ benchmarks! {
let s in 0 .. MAX_SPANS;
let (stash, controller) = create_stash_controller::<T>(0, 100, Default::default())?;
add_slashing_spans::<T>(&stash, s);
let amount = T::Currency::minimum_balance() * 10.into();
let amount = T::Currency::minimum_balance() * 10u32.into();
Staking::<T>::unbond(RawOrigin::Signed(controller.clone()).into(), amount)?;
CurrentEra::put(EraIndex::max_value());
let ledger = Ledger::<T>::get(&controller).ok_or("ledger not created before")?;
Expand Down Expand Up @@ -342,7 +342,7 @@ benchmarks! {
let (_, controller) = create_stash_controller::<T>(USER_SEED, 100, Default::default())?;
let mut staking_ledger = Ledger::<T>::get(controller.clone()).unwrap();
let unlock_chunk = UnlockChunk::<BalanceOf<T>> {
value: 1.into(),
value: 1u32.into(),
era: EraIndex::zero(),
};
for _ in 0 .. l {
Expand Down Expand Up @@ -380,7 +380,7 @@ benchmarks! {
let s in 1 .. MAX_SPANS;
let (stash, controller) = create_stash_controller::<T>(0, 100, Default::default())?;
add_slashing_spans::<T>(&stash, s);
T::Currency::make_free_balance_be(&stash, 0.into());
T::Currency::make_free_balance_be(&stash, 0u32.into());
do_whitelist!(controller);
}: _(RawOrigin::Signed(controller), stash.clone(), s)
verify {
Expand Down Expand Up @@ -427,7 +427,7 @@ benchmarks! {
ErasRewardPoints::<T>::insert(current_era, reward);

// Create reward pool
let total_payout = T::Currency::minimum_balance() * 1000.into();
let total_payout = T::Currency::minimum_balance() * 1000u32.into();
<ErasValidatorReward<T>>::insert(current_era, total_payout);

let caller: T::AccountId = whitelisted_caller();
Expand All @@ -443,14 +443,14 @@ benchmarks! {
let (stash, controller) = create_stash_controller::<T>(0, 100, Default::default())?;
let mut staking_ledger = Ledger::<T>::get(controller.clone()).unwrap();
let unlock_chunk = UnlockChunk::<BalanceOf<T>> {
value: 1.into(),
value: 1u32.into(),
era: EraIndex::zero(),
};
for _ in 0 .. l {
staking_ledger.unlocking.push(unlock_chunk.clone())
}
Ledger::<T>::insert(controller, staking_ledger);
let slash_amount = T::Currency::minimum_balance() * 10.into();
let slash_amount = T::Currency::minimum_balance() * 10u32.into();
let balance_before = T::Currency::free_balance(&stash);
}: {
crate::slashing::do_slash::<T>(
Expand Down
6 changes: 3 additions & 3 deletions frame/system/benchmarking/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,17 +139,17 @@ benchmarks! {
suicide {
let caller: T::AccountId = whitelisted_caller();
let account_info = AccountInfo::<T::Index, T::AccountData> {
nonce: 1337.into(),
nonce: 1337u32.into(),
refcount: 0,
data: T::AccountData::default()
};
frame_system::Account::<T>::insert(&caller, account_info);
let new_account_info = System::<T>::account(caller.clone());
assert_eq!(new_account_info.nonce, 1337.into());
assert_eq!(new_account_info.nonce, 1337u32.into());
}: _(RawOrigin::Signed(caller.clone()))
verify {
let account_info = System::<T>::account(&caller);
assert_eq!(account_info.nonce, 0.into());
assert_eq!(account_info.nonce, 0u32.into());
}
}

Expand Down
2 changes: 1 addition & 1 deletion frame/system/src/offchain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ impl<T: SigningTypes, C: AppCrypto<T::Public, T::Signature>, X> Signer<T, C, X>
.enumerate()
.map(|(index, key)| {
let generic_public = C::GenericPublic::from(key);
let public = generic_public.into();
let public: T::Public = generic_public.into();
let account_id = public.clone().into_account();
Account::new(index, account_id, public)
})
Expand Down
Loading

0 comments on commit 996769a

Please sign in to comment.