* 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
+6 -6
View File
@@ -21,7 +21,7 @@ use std::collections::{HashMap, BTreeMap};
use std::collections::hash_map::Entry;
use log::trace;
use network_libp2p::PeerId;
use runtime_primitives::traits::{Block as BlockT, NumberFor, As};
use runtime_primitives::traits::{Block as BlockT, NumberFor, One};
use crate::message;
const MAX_PARALLEL_DOWNLOADS: u32 = 1;
@@ -48,7 +48,7 @@ impl<B: BlockT> BlockRangeState<B> {
pub fn len(&self) -> NumberFor<B> {
match *self {
BlockRangeState::Downloading { len, .. } => len,
BlockRangeState::Complete(ref blocks) => As::sa(blocks.len() as u64),
BlockRangeState::Complete(ref blocks) => (blocks.len() as u32).into(),
}
}
}
@@ -102,8 +102,8 @@ impl<B: BlockT> BlockCollection<B> {
/// Returns a set of block hashes that require a header download. The returned set is marked as being downloaded.
pub fn needed_blocks(&mut self, who: PeerId, count: usize, peer_best: NumberFor<B>, common: NumberFor<B>) -> Option<Range<NumberFor<B>>> {
// First block number that we need to download
let first_different = common + As::sa(1);
let count = As::sa(count as u64);
let first_different = common + <NumberFor<B>>::one();
let count = (count as u32).into();
let (mut range, downloading) = {
let mut downloading_iter = self.blocks.iter().peekable();
let mut prev: Option<(&NumberFor<B>, &BlockRangeState<B>)> = None;
@@ -132,7 +132,7 @@ impl<B: BlockT> BlockCollection<B> {
trace!(target: "sync", "Out of range for peer {} ({} vs {})", who, range.start, peer_best);
return None;
}
range.end = cmp::min(peer_best + As::sa(1), range.end);
range.end = cmp::min(peer_best + One::one(), range.end);
self.peer_requests.insert(who, range.start);
self.blocks.insert(range.start, BlockRangeState::Downloading { len: range.end - range.start, downloading: downloading + 1 });
if range.end <= range.start {
@@ -150,7 +150,7 @@ impl<B: BlockT> BlockCollection<B> {
for (start, range_data) in &mut self.blocks {
match range_data {
&mut BlockRangeState::Complete(ref mut blocks) if *start <= prev => {
prev = *start + As::sa(blocks.len() as u64);
prev = *start + (blocks.len() as u32).into();
let mut blocks = mem::replace(blocks, Vec::new());
drained.append(&mut blocks);
ranges.push(*start);
+9 -6
View File
@@ -19,7 +19,10 @@ use network_libp2p::PeerId;
use primitives::storage::StorageKey;
use consensus::{import_queue::IncomingBlock, import_queue::Origin, BlockOrigin};
use runtime_primitives::{generic::BlockId, ConsensusEngineId, Justification};
use runtime_primitives::traits::{As, Block as BlockT, Header as HeaderT, NumberFor, Zero};
use runtime_primitives::traits::{
Block as BlockT, Header as HeaderT, NumberFor, One, Zero,
CheckedSub, SaturatedConversion
};
use consensus::import_queue::SharedFinalityProofRequestBuilder;
use crate::message::{
self, BlockRequest as BlockRequestMessage,
@@ -572,9 +575,9 @@ impl<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> Protocol<B, S, H> {
};
blocks.push(block_data);
match request.direction {
message::Direction::Ascending => id = BlockId::Number(number + As::sa(1)),
message::Direction::Ascending => id = BlockId::Number(number + One::one()),
message::Direction::Descending => {
if number == As::sa(0) {
if number.is_zero() {
break;
}
id = BlockId::Hash(parent_hash)
@@ -716,9 +719,9 @@ impl<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> Protocol<B, S, H> {
.and_then(|info| info.best_queued_number)
.unwrap_or_else(|| Zero::zero());
let blocks_difference = self_best_block
.as_()
.checked_sub(status.best_number.as_())
.unwrap_or(0);
.checked_sub(&status.best_number)
.unwrap_or_else(Zero::zero)
.saturated_into::<u64>();
if blocks_difference > LIGHT_MAXIMAL_BLOCKS_DIFFERENCE {
debug!(target: "sync", "Peer {} is far behind us and will unable to serve light requests", who);
network_out.report_peer(who.clone(), PEER_BEHIND_US_LIGHT_REPUTATION_CHANGE);
+37 -28
View File
@@ -40,7 +40,10 @@ use consensus::{BlockOrigin, import_queue::{IncomingBlock, SharedFinalityProofRe
use client::error::Error as ClientError;
use crate::blocks::BlockCollection;
use crate::sync::extra_requests::ExtraRequestsAggregator;
use runtime_primitives::traits::{Block as BlockT, Header as HeaderT, As, NumberFor, Zero, CheckedSub};
use runtime_primitives::traits::{
Block as BlockT, Header as HeaderT, NumberFor, Zero, One,
CheckedSub, SaturatedConversion
};
use runtime_primitives::{Justification, generic::BlockId};
use crate::message;
use crate::config::Roles;
@@ -204,7 +207,7 @@ impl<B: BlockT> ChainSync<B> {
fn state(&self, best_seen: &Option<NumberFor<B>>) -> SyncState {
match best_seen {
&Some(n) if n > self.best_queued_number && n - self.best_queued_number > As::sa(5) => SyncState::Downloading,
&Some(n) if n > self.best_queued_number && n - self.best_queued_number > 5.into() => SyncState::Downloading,
_ => SyncState::Idle,
}
}
@@ -251,7 +254,7 @@ impl<B: BlockT> ChainSync<B> {
protocol.report_peer(who.clone(), i32::min_value());
protocol.disconnect_peer(who);
},
(Ok(BlockStatus::Unknown), b) if b == As::sa(0) => {
(Ok(BlockStatus::Unknown), b) if b.is_zero() => {
info!("New peer with unknown genesis hash {} ({}).", info.best_hash, info.best_number);
protocol.report_peer(who.clone(), i32::min_value());
protocol.disconnect_peer(who);
@@ -269,28 +272,32 @@ impl<B: BlockT> ChainSync<B> {
}
(Ok(BlockStatus::Unknown), _) => {
let our_best = self.best_queued_number;
if our_best > As::sa(0) {
let common_best = ::std::cmp::min(our_best, info.best_number);
debug!(target:"sync", "New peer with unknown best hash {} ({}), searching for common ancestor.", info.best_hash, info.best_number);
self.peers.insert(who.clone(), PeerSync {
common_number: As::sa(0),
best_hash: info.best_hash,
best_number: info.best_number,
state: PeerSyncState::AncestorSearch(common_best, AncestorSearchState::ExponentialBackoff(As::sa(1))),
recently_announced: Default::default(),
});
Self::request_ancestry(protocol, who, common_best)
} else {
if our_best.is_zero() {
// We are at genesis, just start downloading
debug!(target:"sync", "New peer with best hash {} ({}).", info.best_hash, info.best_number);
self.peers.insert(who.clone(), PeerSync {
common_number: As::sa(0),
common_number: Zero::zero(),
best_hash: info.best_hash,
best_number: info.best_number,
state: PeerSyncState::Available,
recently_announced: Default::default(),
});
self.download_new(protocol, who)
} else {
let common_best = ::std::cmp::min(our_best, info.best_number);
debug!(target:"sync",
"New peer with unknown best hash {} ({}), searching for common ancestor.",
info.best_hash,
info.best_number
);
self.peers.insert(who.clone(), PeerSync {
common_number: Zero::zero(),
best_hash: info.best_hash,
best_number: info.best_number,
state: PeerSyncState::AncestorSearch(common_best, AncestorSearchState::ExponentialBackoff(One::one())),
recently_announced: Default::default(),
});
Self::request_ancestry(protocol, who, common_best)
}
},
(Ok(BlockStatus::Queued), _) | (Ok(BlockStatus::InChainWithState), _) | (Ok(BlockStatus::InChainPruned), _) => {
@@ -312,20 +319,22 @@ impl<B: BlockT> ChainSync<B> {
curr_block_num: NumberFor<B>,
block_hash_match: bool,
) -> Option<(AncestorSearchState<B>, NumberFor<B>)> {
let two = <NumberFor<B>>::one() + <NumberFor<B>>::one();
match state {
AncestorSearchState::ExponentialBackoff(next_distance_to_tip) => {
if block_hash_match && next_distance_to_tip == As::sa(1) {
if block_hash_match && next_distance_to_tip == One::one() {
// We found the ancestor in the first step so there is no need to execute binary search.
return None;
}
if block_hash_match {
let left = curr_block_num;
let right = left + next_distance_to_tip / As::sa(2);
let middle = left + (right - left) / As::sa(2);
let right = left + next_distance_to_tip / two;
let middle = left + (right - left) / two;
Some((AncestorSearchState::BinarySearch(left, right), middle))
} else {
let next_block_num = curr_block_num.checked_sub(&next_distance_to_tip).unwrap_or(As::sa(0));
let next_distance_to_tip = next_distance_to_tip * As::sa(2);
let next_block_num = curr_block_num.checked_sub(&next_distance_to_tip)
.unwrap_or_else(Zero::zero);
let next_distance_to_tip = next_distance_to_tip * two;
Some((AncestorSearchState::ExponentialBackoff(next_distance_to_tip), next_block_num))
}
},
@@ -339,7 +348,7 @@ impl<B: BlockT> ChainSync<B> {
right = curr_block_num;
}
assert!(right >= left);
let middle = left + (right - left) / As::sa(2);
let middle = left + (right - left) / two;
Some((AncestorSearchState::BinarySearch(left, right), middle))
},
}
@@ -372,7 +381,7 @@ impl<B: BlockT> ChainSync<B> {
peer.state = PeerSyncState::Available;
self.blocks.insert(start_block, blocks, who);
self.blocks
.drain(self.best_queued_number + As::sa(1))
.drain(self.best_queued_number + One::one())
.into_iter()
.map(|block_data| {
IncomingBlock {
@@ -418,7 +427,7 @@ impl<B: BlockT> ChainSync<B> {
if block_hash_match && peer.common_number < num {
peer.common_number = num;
}
if !block_hash_match && num == As::sa(0) {
if !block_hash_match && num.is_zero() {
trace!(target:"sync", "Ancestry search: genesis mismatch for peer {}", who);
protocol.report_peer(who.clone(), GENESIS_MISMATCH_REPUTATION_CHANGE);
protocol.disconnect_peer(who);
@@ -675,7 +684,7 @@ impl<B: BlockT> ChainSync<B> {
pub(crate) fn on_block_announce(&mut self, protocol: &mut Context<B>, who: PeerId, hash: B::Hash, header: &B::Header) {
let number = *header.number();
debug!(target: "sync", "Received block announcement with number {:?}", number);
if number <= As::sa(0) {
if number.is_zero() {
warn!(target: "sync", "Ignored invalid block announcement from {}: {}", who, hash);
return;
}
@@ -699,7 +708,7 @@ impl<B: BlockT> ChainSync<B> {
return;
}
if header.parent_hash() == &self.best_queued_hash || known_parent {
peer.common_number = number - As::sa(1);
peer.common_number = number - One::one();
} else if known {
peer.common_number = number
}
@@ -769,7 +778,7 @@ impl<B: BlockT> ChainSync<B> {
Err(e) => {
debug!(target:"sync", "Error reading blockchain: {:?}", e);
self.best_queued_hash = self.genesis_hash;
self.best_queued_number = As::sa(0);
self.best_queued_number = Zero::zero();
}
}
let ids: Vec<PeerId> = self.peers.drain().map(|(id, _)| id).collect();
@@ -839,7 +848,7 @@ impl<B: BlockT> ChainSync<B> {
from: message::FromBlock::Number(range.start),
to: None,
direction: message::Direction::Ascending,
max: Some((range.end - range.start).as_() as u32),
max: Some((range.end - range.start).saturated_into::<u32>()),
};
peer.state = PeerSyncState::DownloadingNew(range.start);
protocol.send_block_request(who, request);