Apply some clippy lints (#11154)

* Apply some clippy hints

* Revert clippy ci changes

* Update client/cli/src/commands/generate.rs

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

* Update client/cli/src/commands/inspect_key.rs

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

* Update client/db/src/bench.rs

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

* Update client/db/src/bench.rs

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

* Update client/service/src/client/block_rules.rs

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

* Update client/service/src/client/block_rules.rs

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

* Update client/network/src/transactions.rs

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

* Update client/network/src/protocol.rs

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

* Revert due to missing `or_default` function.

* Fix compilation and simplify code

* Undo change that corrupts benchmark.

* fix clippy

* Update client/service/test/src/lib.rs

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

* Update client/state-db/src/noncanonical.rs

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

* Update client/state-db/src/noncanonical.rs

remove leftovers!

* Update client/tracing/src/logging/directives.rs

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

* Update utils/fork-tree/src/lib.rs

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

* added needed ref

* Update frame/referenda/src/benchmarking.rs

* Simplify byte-vec creation

* let's just not overlap the ranges

* Correction

* cargo fmt

* Update utils/frame/benchmarking-cli/src/shared/stats.rs

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

* Update utils/frame/benchmarking-cli/src/pallet/command.rs

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

* Update utils/frame/benchmarking-cli/src/pallet/command.rs

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

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>
Co-authored-by: Giles Cope <gilescope@gmail.com>
This commit is contained in:
Falco Hirschenberger
2022-04-30 23:28:27 +02:00
committed by GitHub
parent a990473cf9
commit b581604aa7
368 changed files with 1927 additions and 2236 deletions
+1 -1
View File
@@ -43,7 +43,7 @@ where
io.extend_with(SystemApi::to_delegate(FullSystem::new(client.clone(), pool, deny_unsafe)));
io.extend_with(TransactionPaymentApi::to_delegate(TransactionPayment::new(client.clone())));
io.extend_with(TransactionPaymentApi::to_delegate(TransactionPayment::new(client)));
// Extend this RPC with a custom API by using the following syntax.
// `YourRpcStruct` should have a reference to a client, which is needed
@@ -82,7 +82,7 @@ pub fn new_partial(
let (client, backend, keystore_container, task_manager) =
sc_service::new_full_parts::<Block, RuntimeApi, _>(
&config,
config,
telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),
executor,
)?;
@@ -263,7 +263,7 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
let aura = sc_consensus_aura::start_aura::<AuraPair, _, _, _, _, _, _, _, _, _, _, _>(
StartAuraParams {
slot_duration,
client: client.clone(),
client,
select_chain,
block_import,
proposer_factory,
@@ -88,7 +88,7 @@ pub mod pallet {
// Read a value from storage.
match <Something<T>>::get() {
// Return an error if the value has not been set.
None => Err(Error::<T>::NoneValue)?,
None => return Err(Error::<T>::NoneValue.into()),
Some(old) => {
// Increment the value read from storage; will error in the event of overflow.
let new = old.checked_add(1).ok_or(Error::<T>::StorageOverflow)?;
@@ -478,7 +478,7 @@ impl_runtime_apis! {
let storage_info = AllPalletsWithSystem::storage_info();
return (list, storage_info)
(list, storage_info)
}
fn dispatch_benchmark(
+1 -1
View File
@@ -132,7 +132,7 @@ pub fn run_benchmark(benchmark: Box<dyn BenchmarkDescription>, mode: Mode) -> Be
durations.push(duration.as_nanos());
}
durations.sort();
durations.sort_unstable();
let raw_average = (durations.iter().sum::<u128>() / (durations.len() as u128)) as u64;
let average = (durations.iter().skip(10).take(30).sum::<u128>() / 30) as u64;
+9 -20
View File
@@ -85,7 +85,7 @@ fn main() {
let mut import_benchmarks = Vec::new();
for profile in [Profile::Wasm, Profile::Native].iter() {
for profile in [Profile::Wasm, Profile::Native] {
for size in [
SizeType::Empty,
SizeType::Small,
@@ -93,25 +93,14 @@ fn main() {
SizeType::Large,
SizeType::Full,
SizeType::Custom(opt.transactions.unwrap_or(0)),
]
.iter()
{
] {
for block_type in [
BlockType::RandomTransfersKeepAlive,
BlockType::RandomTransfersReaping,
BlockType::Noop,
]
.iter()
{
for database_type in
[BenchDataBaseType::RocksDb, BenchDataBaseType::ParityDb].iter()
{
import_benchmarks.push((
profile,
size.clone(),
block_type.clone(),
database_type,
));
] {
for database_type in [BenchDataBaseType::RocksDb, BenchDataBaseType::ParityDb] {
import_benchmarks.push((profile, size, block_type, database_type));
}
}
}
@@ -120,11 +109,11 @@ fn main() {
let benchmarks = matrix!(
(profile, size, block_type, database_type) in import_benchmarks.into_iter() =>
ImportBenchmarkDescription {
profile: *profile,
profile,
key_types: KeyTypes::Sr25519,
size: size,
block_type: block_type,
database_type: *database_type,
size,
block_type,
database_type,
},
(size, db_type) in
[
+1 -1
View File
@@ -17,7 +17,7 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.
/// Kusama value size distribution
pub const KUSAMA_STATE_DISTRIBUTION: &'static [(u32, u32)] = &[
pub const KUSAMA_STATE_DISTRIBUTION: &[(u32, u32)] = &[
(32, 35),
(33, 20035),
(34, 5369),
+1 -1
View File
@@ -282,7 +282,7 @@ impl core::Benchmark for TrieWriteBenchmark {
let mut db = self.database.clone();
let kvdb = db.open(self.database_type);
let mut new_root = self.root.clone();
let mut new_root = self.root;
let mut overlay = HashMap::new();
let mut trie = SimpleTrie { db: kvdb.clone(), overlay: &mut overlay };
+3 -3
View File
@@ -113,10 +113,10 @@ pub fn create_extrinsic(
let signature = raw_payload.using_encoded(|e| sender.sign(e));
node_runtime::UncheckedExtrinsic::new_signed(
function.clone(),
function,
sp_runtime::AccountId32::from(sender.public()).into(),
node_runtime::Signature::Sr25519(signature.clone()),
extra.clone(),
node_runtime::Signature::Sr25519(signature),
extra,
)
}
+3 -3
View File
@@ -631,7 +631,7 @@ impl Get<Option<(usize, ExtendedBalance)>> for OffchainRandomBalancing {
use sp_runtime::traits::TrailingZeroInput;
let iters = match MINER_MAX_ITERATIONS {
0 => 0,
max @ _ => {
max => {
let seed = sp_io::offchain::random_seed();
let random = <u32>::decode(&mut TrailingZeroInput::new(&seed))
.expect("input is padded with zeroes; qed") %
@@ -1148,7 +1148,7 @@ where
let signature = raw_payload.using_encoded(|payload| C::sign(payload, public))?;
let address = Indices::unlookup(account);
let (call, extra, _) = raw_payload.deconstruct();
Some((call, (address, signature.into(), extra)))
Some((call, (address, signature, extra)))
}
}
@@ -1911,7 +1911,7 @@ impl_runtime_apis! {
let storage_info = AllPalletsWithSystem::storage_info();
return (list, storage_info)
(list, storage_info)
}
fn dispatch_benchmark(
+8 -11
View File
@@ -280,8 +280,7 @@ impl<'a> BlockContentIterator<'a> {
let genesis_hash = client
.block_hash(Zero::zero())
.expect("Database error?")
.expect("Genesis block always exists; qed")
.into();
.expect("Genesis block always exists; qed");
BlockContentIterator { iteration: 0, content, keyring, runtime_version, genesis_hash }
}
@@ -569,15 +568,13 @@ impl BenchKeyring {
genesis_hash,
);
let key = self.accounts.get(&signed).expect("Account id not found in keyring");
let signature = payload
.using_encoded(|b| {
if b.len() > 256 {
key.sign(&sp_io::hashing::blake2_256(b))
} else {
key.sign(b)
}
})
.into();
let signature = payload.using_encoded(|b| {
if b.len() > 256 {
key.sign(&sp_io::hashing::blake2_256(b))
} else {
key.sign(b)
}
});
UncheckedExtrinsic {
signature: Some((sp_runtime::MultiAddress::Id(signed), signature, extra)),
function: payload.0,
@@ -163,7 +163,7 @@ fn generate_chain_spec(
}
fn generate_authority_keys_and_store(seeds: &[String], keystore_path: &Path) -> Result<(), String> {
for (n, seed) in seeds.into_iter().enumerate() {
for (n, seed) in seeds.iter().enumerate() {
let keystore: SyncCryptoStorePtr = Arc::new(
LocalKeystore::open(keystore_path.join(format!("auth-{}", n)), None)
.map_err(|err| err.to_string())?,
@@ -90,7 +90,7 @@ fn error(msg: &'static str) -> Error {
Error::Other(msg)
}
const LOG_TARGET: &'static str = "wasm-heap";
const LOG_TARGET: &str = "wasm-heap";
// The minimum possible allocation size is chosen to be 8 bytes because in that case we would have
// easier time to provide the guaranteed alignment of 8.
+1 -1
View File
@@ -499,7 +499,7 @@ pub trait Backend<Block: BlockT>: AuxStore + Send + Sync {
/// Returns true if state for given block is available.
fn have_state_at(&self, hash: &Block::Hash, _number: NumberFor<Block>) -> bool {
self.state_at(BlockId::Hash(hash.clone())).is_ok()
self.state_at(BlockId::Hash(*hash)).is_ok()
}
/// Returns state backend with post-state of given block.
@@ -151,7 +151,7 @@ impl<Block: traits::Block> ExecutionExtensions<Block> {
where
T: OffchainSubmitTransaction<Block> + 'static,
{
*self.transaction_pool.write() = Some(Arc::downgrade(&pool) as _);
*self.transaction_pool.write() = Some(Arc::downgrade(pool) as _);
}
/// Based on the execution context and capabilities it produces
+13 -21
View File
@@ -166,23 +166,19 @@ impl<Block: BlockT> Blockchain<Block> {
body: Option<Vec<<Block as BlockT>::Extrinsic>>,
new_state: NewBlockState,
) -> sp_blockchain::Result<()> {
let number = header.number().clone();
let number = *header.number();
if new_state.is_best() {
self.apply_head(&header)?;
}
{
let mut storage = self.storage.write();
storage
.leaves
.import(hash.clone(), number.clone(), header.parent_hash().clone());
storage
.blocks
.insert(hash.clone(), StoredBlock::new(header, body, justifications));
storage.leaves.import(hash, number, header.parent_hash().clone());
storage.blocks.insert(hash, StoredBlock::new(header, body, justifications));
if let NewBlockState::Final = new_state {
storage.finalized_hash = hash;
storage.finalized_number = number.clone();
storage.finalized_number = number;
}
if number == Zero::zero() {
@@ -266,9 +262,9 @@ impl<Block: BlockT> Blockchain<Block> {
}
}
storage.best_hash = hash.clone();
storage.best_number = number.clone();
storage.hashes.insert(number.clone(), hash.clone());
storage.best_hash = hash;
storage.best_number = *number;
storage.hashes.insert(*number, hash);
Ok(())
}
@@ -362,7 +358,7 @@ impl<Block: BlockT> HeaderBackend<Block> for Blockchain<Block> {
finalized_hash: storage.finalized_hash,
finalized_number: storage.finalized_number,
finalized_state: if storage.finalized_hash != Default::default() {
Some((storage.finalized_hash.clone(), storage.finalized_number))
Some((storage.finalized_hash, storage.finalized_number))
} else {
None
},
@@ -428,16 +424,12 @@ impl<Block: BlockT> blockchain::Backend<Block> for Blockchain<Block> {
fn justifications(&self, id: BlockId<Block>) -> sp_blockchain::Result<Option<Justifications>> {
Ok(self.id(id).and_then(|hash| {
self.storage
.read()
.blocks
.get(&hash)
.and_then(|b| b.justifications().map(|x| x.clone()))
self.storage.read().blocks.get(&hash).and_then(|b| b.justifications().cloned())
}))
}
fn last_finalized(&self) -> sp_blockchain::Result<Block::Hash> {
Ok(self.storage.read().finalized_hash.clone())
Ok(self.storage.read().finalized_hash)
}
fn leaves(&self) -> sp_blockchain::Result<Vec<Block::Hash>> {
@@ -810,15 +802,15 @@ impl<Block: BlockT> backend::LocalBackend<Block> for Backend<Block> where Block:
/// Check that genesis storage is valid.
pub fn check_genesis_storage(storage: &Storage) -> sp_blockchain::Result<()> {
if storage.top.iter().any(|(k, _)| well_known_keys::is_child_storage_key(k)) {
return Err(sp_blockchain::Error::InvalidState.into())
return Err(sp_blockchain::Error::InvalidState)
}
if storage
.children_default
.keys()
.any(|child_key| !well_known_keys::is_child_storage_key(&child_key))
.any(|child_key| !well_known_keys::is_child_storage_key(child_key))
{
return Err(sp_blockchain::Error::InvalidState.into())
return Err(sp_blockchain::Error::InvalidState)
}
Ok(())
+3 -3
View File
@@ -57,10 +57,10 @@ pub mod utils {
/// represent the current block `hash` and its `parent hash`, if given the
/// function that's returned will assume that `hash` isn't part of the local DB
/// yet, and all searches in the DB will instead reference the parent.
pub fn is_descendent_of<'a, Block: BlockT, T>(
client: &'a T,
pub fn is_descendent_of<Block: BlockT, T>(
client: &T,
current: Option<(Block::Hash, Block::Hash)>,
) -> impl Fn(&Block::Hash, &Block::Hash) -> Result<bool, Error> + 'a
) -> impl Fn(&Block::Hash, &Block::Hash) -> Result<bool, Error> + '_
where
T: HeaderBackend<Block> + HeaderMetadata<Block, Error = Error>,
{
+3 -4
View File
@@ -71,10 +71,9 @@ type ChildKeys = Option<HashMap<StorageKey, Option<HashSet<StorageKey>>>>;
impl StorageChangeSet {
/// Convert the change set into iterator over storage items.
pub fn iter<'a>(
&'a self,
) -> impl Iterator<Item = (Option<&'a StorageKey>, &'a StorageKey, Option<&'a StorageData>)> + 'a
{
pub fn iter(
&self,
) -> impl Iterator<Item = (Option<&StorageKey>, &StorageKey, Option<&StorageData>)> + '_ {
let top = self
.changes
.iter()
@@ -134,7 +134,7 @@ impl<'a> Subscribe<SubscribeOp<'a>> for Registry {
});
if let Some(m) = self.metrics.as_ref() {
m.with_label_values(&[&"added"]).inc();
m.with_label_values(&["added"]).inc();
}
if self
@@ -195,7 +195,7 @@ impl Registry {
let k = StorageKey(k);
let listeners = self.listeners.get(&k);
if let Some(ref listeners) = listeners {
if let Some(listeners) = listeners {
subscribers.extend(listeners.iter());
}
@@ -211,7 +211,7 @@ impl Registry {
let k = StorageKey(k);
let listeners = cl.get(&k);
if let Some(ref listeners) = listeners {
if let Some(listeners) = listeners {
subscribers.extend(listeners.iter());
}
@@ -268,22 +268,22 @@ impl Registry {
);
if let Some(child_filters) = &sink.child_keys {
for (c_key, filters) in child_filters {
if let Some((listeners, wildcards)) = self.child_listeners.get_mut(&c_key) {
if let Some((listeners, wildcards)) = self.child_listeners.get_mut(c_key) {
Self::remove_subscriber_from(
subscriber,
&filters,
filters,
&mut *listeners,
&mut *wildcards,
);
if listeners.is_empty() && wildcards.is_empty() {
self.child_listeners.remove(&c_key);
self.child_listeners.remove(c_key);
}
}
}
}
if let Some(m) = self.metrics.as_ref() {
m.with_label_values(&[&"removed"]).inc();
m.with_label_values(&["removed"]).inc();
}
Some((sink.keys.clone(), sink.child_keys.clone()))
@@ -64,7 +64,7 @@ mod schema {
#[cfg(test)]
pub mod tests;
const LOG_TARGET: &'static str = "sub-authority-discovery";
const LOG_TARGET: &str = "sub-authority-discovery";
/// Maximum number of addresses cached per authority. Additional addresses are discarded.
const MAX_ADDRESSES_PER_AUTHORITY: usize = 10;
@@ -510,7 +510,7 @@ where
// Ignore [`Multiaddr`]s without [`PeerId`] or with own addresses.
let addresses: Vec<Multiaddr> = addresses
.into_iter()
.filter(|a| get_peer_id(&a).filter(|p| *p != local_peer_id).is_some())
.filter(|a| get_peer_id(a).filter(|p| *p != local_peer_id).is_some())
.collect();
let remote_peer_id = single(addresses.iter().map(get_peer_id))
@@ -525,7 +525,7 @@ where
if let Some(peer_signature) = peer_signature {
let public_key =
sc_network::PublicKey::from_protobuf_encoding(&peer_signature.public_key)
.map_err(|e| Error::ParsingLibp2pIdentity(e))?;
.map_err(Error::ParsingLibp2pIdentity)?;
let signature =
sc_network::Signature { public_key, bytes: peer_signature.signature };
@@ -165,10 +165,7 @@ fn peer_id_from_multiaddr(addr: &Multiaddr) -> Option<PeerId> {
}
fn addresses_to_peer_ids(addresses: &HashSet<Multiaddr>) -> HashSet<PeerId> {
addresses
.iter()
.filter_map(|a| peer_id_from_multiaddr(a))
.collect::<HashSet<_>>()
addresses.iter().filter_map(peer_id_from_multiaddr).collect::<HashSet<_>>()
}
#[cfg(test)]
@@ -371,7 +371,7 @@ where
error!(
"❌️ Mandatory inherent extrinsic returned error. Block cannot be produced."
);
Err(ApplyExtrinsicFailed(Validity(e)))?
return Err(ApplyExtrinsicFailed(Validity(e)))
},
Err(e) => {
warn!("❗️ Inherent extrinsic returned unexpected error: {}. Dropping.", e);
+1 -1
View File
@@ -192,7 +192,7 @@ where
.read()
.as_ref()
.cloned()
.ok_or(Error::EndpointNotReady.into());
.ok_or_else(|| Error::EndpointNotReady.into());
let future = async move { result }.boxed();
future.map_err(jsonrpc_core::Error::from).boxed()
}
+2 -2
View File
@@ -51,9 +51,9 @@ pub use beefy_protocol_name::standard_name as protocol_standard_name;
pub(crate) mod beefy_protocol_name {
use sc_chain_spec::ChainSpec;
const NAME: &'static str = "/beefy/1";
const NAME: &str = "/beefy/1";
/// Old names for the notifications protocol, used for backward compatibility.
pub(crate) const LEGACY_NAMES: [&'static str; 1] = ["/paritytech/beefy/1"];
pub(crate) const LEGACY_NAMES: [&str; 1] = ["/paritytech/beefy/1"];
/// Name of the notifications protocol used by BEEFY.
///
+1 -1
View File
@@ -264,7 +264,7 @@ where
let storage_changes = self
.api
.into_storage_changes(&state, parent_hash)
.map_err(|e| sp_blockchain::Error::StorageChanges(e))?;
.map_err(sp_blockchain::Error::StorageChanges)?;
Ok(BuiltBlock {
block: <Block as BlockT>::new(header, self.extrinsics),
@@ -61,16 +61,11 @@ impl GenerateCmd {
};
let mnemonic = Mnemonic::new(words, Language::English);
let password = self.keystore_params.read_password()?;
let output = self.output_scheme.output_type.clone();
let output = self.output_scheme.output_type;
with_crypto_scheme!(
self.crypto_scheme.scheme,
print_from_uri(
mnemonic.phrase(),
password,
self.network_scheme.network.clone(),
output,
)
print_from_uri(mnemonic.phrase(), password, self.network_scheme.network, output)
);
Ok(())
}
@@ -87,15 +87,15 @@ impl InspectKeyCmd {
self.crypto_scheme.scheme,
print_from_public(
&uri,
self.network_scheme.network.clone(),
self.output_scheme.output_type.clone(),
self.network_scheme.network,
self.output_scheme.output_type,
)
)?;
} else {
if let Some(ref expect_public) = self.expect_public {
with_crypto_scheme!(
self.crypto_scheme.scheme,
expect_public_from_phrase(&&expect_public, &uri, password.as_ref(),)
expect_public_from_phrase(expect_public, &uri, password.as_ref())
)?;
}
@@ -104,8 +104,8 @@ impl InspectKeyCmd {
print_from_uri(
&uri,
password,
self.network_scheme.network.clone(),
self.output_scheme.output_type.clone(),
self.network_scheme.network,
self.output_scheme.output_type,
)
);
}
@@ -60,7 +60,7 @@ impl PurgeChainCmd {
io::stdin().read_line(&mut input)?;
let input = input.trim();
match input.chars().nth(0) {
match input.chars().next() {
Some('y') | Some('Y') => {},
_ => {
println!("Aborted");
+2 -2
View File
@@ -74,7 +74,7 @@ pub fn print_from_uri<Pair>(
{
let password = password.as_ref().map(|s| s.expose_secret().as_str());
let network_id = String::from(unwrap_or_default_ss58_version(network_override));
if let Ok((pair, seed)) = Pair::from_phrase(uri, password.clone()) {
if let Ok((pair, seed)) = Pair::from_phrase(uri, password) {
let public_key = pair.public();
let network_override = unwrap_or_default_ss58_version(network_override);
@@ -113,7 +113,7 @@ pub fn print_from_uri<Pair>(
);
},
}
} else if let Ok((pair, seed)) = Pair::from_string_with_seed(uri, password.clone()) {
} else if let Ok((pair, seed)) = Pair::from_string_with_seed(uri, password) {
let public_key = pair.public();
let network_override = unwrap_or_default_ss58_version(network_override);
+10 -10
View File
@@ -64,8 +64,8 @@ impl VanityCmd {
print_from_uri(
&formated_seed,
None,
self.network_scheme.network.clone(),
self.output_scheme.output_type.clone(),
self.network_scheme.network,
self.output_scheme.output_type,
),
);
Ok(())
@@ -98,7 +98,7 @@ where
let p = Pair::from_seed(&seed);
let ss58 = p.public().into_account().to_ss58check_with_version(network_override);
let score = calculate_score(&desired, &ss58);
let score = calculate_score(desired, &ss58);
if score > best || desired.len() < 2 {
best = score;
if best >= top {
@@ -117,20 +117,20 @@ where
fn good_waypoint(done: u64) -> u64 {
match done {
0..=1_000_000 => 100_000,
0..=10_000_000 => 1_000_000,
0..=100_000_000 => 10_000_000,
_ => 100_000_000,
1_000_001..=10_000_000 => 1_000_000,
10_000_001..=100_000_000 => 10_000_000,
100_000_001.. => 100_000_000,
}
}
fn next_seed(seed: &mut [u8]) {
for i in 0..seed.len() {
match seed[i] {
for s in seed {
match s {
255 => {
seed[i] = 0;
*s = 0;
},
_ => {
seed[i] += 1;
*s += 1;
break
},
}
+2 -2
View File
@@ -40,7 +40,7 @@ use std::{net::SocketAddr, path::PathBuf};
pub(crate) const NODE_NAME_MAX_LENGTH: usize = 64;
/// Default sub directory to store network config.
pub(crate) const DEFAULT_NETWORK_CONFIG_PATH: &'static str = "network";
pub(crate) const DEFAULT_NETWORK_CONFIG_PATH: &str = "network";
/// The recommended open file descriptor limit to be configured for the process.
const RECOMMENDED_OPEN_FILE_DESCRIPTOR_LIMIT: u64 = 10_000;
@@ -629,7 +629,7 @@ pub trait CliConfiguration<DCV: DefaultConfigurationValues = ()>: Sized {
}
// Call hook for custom profiling setup.
logger_hook(&mut logger, &config);
logger_hook(&mut logger, config);
logger.init()?;
+2 -2
View File
@@ -122,7 +122,7 @@ pub trait SubstrateCli: Sized {
let app = <Self as CommandFactory>::command();
let mut full_version = Self::impl_version();
full_version.push_str("\n");
full_version.push('\n');
let name = Self::executable_name();
let author = Self::author();
@@ -164,7 +164,7 @@ pub trait SubstrateCli: Sized {
let app = <Self as CommandFactory>::command();
let mut full_version = Self::impl_version();
full_version.push_str("\n");
full_version.push('\n');
let name = Self::executable_name();
let author = Self::author();
@@ -26,7 +26,7 @@ use std::{
};
/// default sub directory for the key store
const DEFAULT_KEYSTORE_CONFIG_PATH: &'static str = "keystore";
const DEFAULT_KEYSTORE_CONFIG_PATH: &str = "keystore";
/// Parameters of the keystore
#[derive(Debug, Clone, Args)]
@@ -112,7 +112,7 @@ fn invalid_node_key(e: impl std::fmt::Display) -> error::Error {
/// Parse a Ed25519 secret key from a hex string into a `sc_network::Secret`.
fn parse_ed25519_secret(hex: &str) -> error::Result<sc_network::config::Ed25519Secret> {
H256::from_str(&hex).map_err(invalid_node_key).and_then(|bytes| {
H256::from_str(hex).map_err(invalid_node_key).and_then(|bytes| {
ed25519::SecretKey::from_bytes(bytes)
.map(sc_network::config::Secret::Input)
.map_err(invalid_node_key)
@@ -126,7 +126,7 @@ impl SharedParams {
/// Receiver to process tracing messages.
pub fn tracing_receiver(&self) -> sc_service::TracingReceiver {
self.tracing_receiver.clone().into()
self.tracing_receiver.into()
}
/// Comma separated list of targets for tracing.
@@ -68,7 +68,7 @@ where
C: sc_client_api::backend::AuxStore,
P::Public: Encode + Decode + PartialEq + Clone,
{
let seal = header.digest_mut().pop().ok_or_else(|| Error::HeaderUnsealed(hash))?;
let seal = header.digest_mut().pop().ok_or(Error::HeaderUnsealed(hash))?;
let sig = seal.as_aura_seal().ok_or_else(|| aura_err(Error::HeaderBadSeal(hash)))?;
@@ -81,7 +81,7 @@ where
// check the signature is valid under the expected authority and
// chain state.
let expected_author =
slot_author::<P>(slot, &authorities).ok_or_else(|| Error::SlotAuthorNotFound)?;
slot_author::<P>(slot, authorities).ok_or(Error::SlotAuthorNotFound)?;
let pre_hash = header.hash();
@@ -360,7 +360,7 @@ pub struct ImportQueueParams<'a, Block, I, C, S, CAW, CIDP> {
}
/// Start an import queue for the Aura consensus algorithm.
pub fn import_queue<'a, P, Block, I, C, S, CAW, CIDP>(
pub fn import_queue<P, Block, I, C, S, CAW, CIDP>(
ImportQueueParams {
block_import,
justification_import,
@@ -371,7 +371,7 @@ pub fn import_queue<'a, P, Block, I, C, S, CAW, CIDP>(
can_author_with,
check_for_equivocation,
telemetry,
}: ImportQueueParams<'a, Block, I, C, S, CAW, CIDP>,
}: ImportQueueParams<Block, I, C, S, CAW, CIDP>,
) -> Result<DefaultImportQueue<Block, C>, sp_consensus::Error>
where
Block: BlockT,
+4 -4
View File
@@ -186,7 +186,7 @@ where
Error: std::error::Error + Send + From<sp_consensus::Error> + 'static,
{
let worker = build_aura_worker::<P, _, _, _, _, _, _, _, _>(BuildAuraWorkerParams {
client: client.clone(),
client,
block_import,
proposer_factory,
keystore,
@@ -459,7 +459,7 @@ where
fn proposer(&mut self, block: &B::Header) -> Self::CreateProposer {
self.env
.init(block)
.map_err(|e| sp_consensus::Error::ClientImport(format!("{:?}", e)).into())
.map_err(|e| sp_consensus::Error::ClientImport(format!("{:?}", e)))
.boxed()
}
@@ -534,7 +534,7 @@ pub fn find_pre_digest<B: BlockT, Signature: Codec>(header: &B::Header) -> Resul
for log in header.digest().logs() {
trace!(target: "aura", "Checking log {:?}", log);
match (CompatibleDigestItem::<Signature>::as_aura_pre_digest(log), pre_digest.is_some()) {
(Some(_), true) => Err(aura_err(Error::MultipleHeaders))?,
(Some(_), true) => return Err(aura_err(Error::MultipleHeaders)),
(None, _) => trace!(target: "aura", "Ignoring digest not meant for us"),
(s, false) => pre_digest = s,
}
@@ -553,7 +553,7 @@ where
.runtime_api()
.authorities(at)
.ok()
.ok_or_else(|| sp_consensus::Error::InvalidAuthoritiesSet.into())
.ok_or(sp_consensus::Error::InvalidAuthoritiesSet)
}
#[cfg(test)]
@@ -142,7 +142,7 @@ where
claims.entry(key).or_default().secondary.push(slot);
},
PreDigest::SecondaryVRF { .. } => {
claims.entry(key).or_default().secondary_vrf.push(slot.into());
claims.entry(key).or_default().secondary_vrf.push(slot);
},
};
}
@@ -205,7 +205,7 @@ where
.epoch_data_for_child_of(
descendent_query(&**client),
&parent.hash(),
parent.number().clone(),
*parent.number(),
slot.into(),
|slot| Epoch::genesis(babe_config.genesis_config(), slot),
)
@@ -202,15 +202,15 @@ pub fn claim_slot_using_keys(
keystore: &SyncCryptoStorePtr,
keys: &[(AuthorityId, usize)],
) -> Option<(PreDigest, AuthorityId)> {
claim_primary_slot(slot, epoch, epoch.config.c, keystore, &keys).or_else(|| {
claim_primary_slot(slot, epoch, epoch.config.c, keystore, keys).or_else(|| {
if epoch.config.allowed_slots.is_secondary_plain_slots_allowed() ||
epoch.config.allowed_slots.is_secondary_vrf_slots_allowed()
{
claim_secondary_slot(
slot,
&epoch,
epoch,
keys,
&keystore,
keystore,
epoch.config.allowed_slots.is_secondary_vrf_slots_allowed(),
)
} else {
+9 -9
View File
@@ -528,7 +528,7 @@ where
let (worker_tx, worker_rx) = channel(HANDLE_BUFFER_SIZE);
let answer_requests =
answer_requests(worker_rx, babe_link.config, client, babe_link.epoch_changes.clone());
answer_requests(worker_rx, babe_link.config, client, babe_link.epoch_changes);
let inner = future::select(Box::pin(slot_worker), Box::pin(answer_requests));
Ok(BabeWorker {
@@ -638,13 +638,13 @@ async fn answer_requests<B: BlockT, C>(
slot_number,
)
.map_err(|e| Error::<B>::ForkTree(Box::new(e)))?
.ok_or_else(|| Error::<B>::FetchEpoch(parent_hash))?;
.ok_or(Error::<B>::FetchEpoch(parent_hash))?;
let viable_epoch = epoch_changes
.viable_epoch(&epoch_descriptor, |slot| {
Epoch::genesis(&config.genesis_config, slot)
})
.ok_or_else(|| Error::<B>::FetchEpoch(parent_hash))?;
.ok_or(Error::<B>::FetchEpoch(parent_hash))?;
Ok(sp_consensus_babe::Epoch {
epoch_index: viable_epoch.as_ref().epoch_index,
@@ -788,7 +788,7 @@ where
.epoch_descriptor_for_child_of(
descendent_query(&*self.client),
&parent.hash(),
parent.number().clone(),
*parent.number(),
slot,
)
.map_err(|e| ConsensusError::ChainLookup(e.to_string()))?
@@ -798,7 +798,7 @@ where
fn authorities_len(&self, epoch_descriptor: &Self::EpochData) -> Option<usize> {
self.epoch_changes
.shared_data()
.viable_epoch(&epoch_descriptor, |slot| {
.viable_epoch(epoch_descriptor, |slot| {
Epoch::genesis(&self.config.genesis_config, slot)
})
.map(|epoch| epoch.as_ref().authorities.len())
@@ -815,7 +815,7 @@ where
slot,
self.epoch_changes
.shared_data()
.viable_epoch(&epoch_descriptor, |slot| {
.viable_epoch(epoch_descriptor, |slot| {
Epoch::genesis(&self.config.genesis_config, slot)
})?
.as_ref(),
@@ -886,7 +886,7 @@ where
.clone()
.try_into()
.map_err(|_| sp_consensus::Error::InvalidSignature(signature, public))?;
let digest_item = <DigestItem as CompatibleDigestItem>::babe_seal(signature.into());
let digest_item = <DigestItem as CompatibleDigestItem>::babe_seal(signature);
let mut import_block = BlockImportParams::new(BlockOrigin::Own, header);
import_block.post_digests.push(digest_item);
@@ -1245,12 +1245,12 @@ where
pre_digest.slot(),
)
.map_err(|e| Error::<Block>::ForkTree(Box::new(e)))?
.ok_or_else(|| Error::<Block>::FetchEpoch(parent_hash))?;
.ok_or(Error::<Block>::FetchEpoch(parent_hash))?;
let viable_epoch = epoch_changes
.viable_epoch(&epoch_descriptor, |slot| {
Epoch::genesis(&self.config.genesis_config, slot)
})
.ok_or_else(|| Error::<Block>::FetchEpoch(parent_hash))?;
.ok_or(Error::<Block>::FetchEpoch(parent_hash))?;
// We add one to the current slot to allow for some small drift.
// FIXME #1019 in the future, alter this queue to allow deferring of headers
@@ -99,7 +99,7 @@ pub(super) fn check_header<B: BlockT + Sized>(
primary.slot,
);
check_primary_header::<B>(pre_hash, primary, sig, &epoch, epoch.config.c)?;
check_primary_header::<B>(pre_hash, primary, sig, epoch, epoch.config.c)?;
},
PreDigest::SecondaryPlain(secondary)
if epoch.config.allowed_slots.is_secondary_plain_slots_allowed() =>
@@ -110,7 +110,7 @@ pub(super) fn check_header<B: BlockT + Sized>(
secondary.slot,
);
check_secondary_plain_header::<B>(pre_hash, secondary, sig, &epoch)?;
check_secondary_plain_header::<B>(pre_hash, secondary, sig, epoch)?;
},
PreDigest::SecondaryVRF(secondary)
if epoch.config.allowed_slots.is_secondary_vrf_slots_allowed() =>
@@ -121,7 +121,7 @@ pub(super) fn check_header<B: BlockT + Sized>(
secondary.slot,
);
check_secondary_vrf_header::<B>(pre_hash, secondary, sig, &epoch)?;
check_secondary_vrf_header::<B>(pre_hash, secondary, sig, epoch)?;
},
_ => return Err(babe_err(Error::SecondarySlotAssignmentsDisabled)),
}
@@ -153,7 +153,7 @@ fn check_primary_header<B: BlockT + Sized>(
) -> Result<(), Error<B>> {
let author = &epoch.authorities[pre_digest.authority_index as usize].0;
if AuthorityPair::verify(&signature, pre_hash, &author) {
if AuthorityPair::verify(&signature, pre_hash, author) {
let (inout, _) = {
let transcript = make_transcript(&epoch.randomness, pre_digest.slot, epoch.epoch_index);
@@ -191,7 +191,7 @@ fn check_secondary_plain_header<B: BlockT>(
// chain state.
let expected_author =
secondary_slot_author(pre_digest.slot, &epoch.authorities, epoch.randomness)
.ok_or_else(|| Error::NoSecondaryAuthorExpected)?;
.ok_or(Error::NoSecondaryAuthorExpected)?;
let author = &epoch.authorities[pre_digest.authority_index as usize].0;
@@ -217,7 +217,7 @@ fn check_secondary_vrf_header<B: BlockT>(
// chain state.
let expected_author =
secondary_slot_author(pre_digest.slot, &epoch.authorities, epoch.randomness)
.ok_or_else(|| Error::NoSecondaryAuthorExpected)?;
.ok_or(Error::NoSecondaryAuthorExpected)?;
let author = &epoch.authorities[pre_digest.authority_index as usize].0;
@@ -62,8 +62,7 @@ impl ImportResult {
/// `clear_justification_requests`, `needs_justification`,
/// `bad_justification` set to false.
pub fn imported(is_new_best: bool) -> ImportResult {
let mut aux = ImportedAux::default();
aux.is_new_best = is_new_best;
let aux = ImportedAux { is_new_best, ..Default::default() };
ImportResult::Imported(aux)
}
@@ -232,17 +232,17 @@ pub(crate) async fn import_single_block_metered<
trace!(target: "sync", "Header {} has {:?} logs", block.hash, header.digest().logs().len());
let number = header.number().clone();
let number = *header.number();
let hash = block.hash;
let parent_hash = header.parent_hash().clone();
let parent_hash = *header.parent_hash();
let import_handler = |import| match import {
Ok(ImportResult::AlreadyInChain) => {
trace!(target: "sync", "Block already in chain {}: {:?}", number, hash);
Ok(BlockImportStatus::ImportedKnown(number, peer.clone()))
Ok(BlockImportStatus::ImportedKnown(number, peer))
},
Ok(ImportResult::Imported(aux)) =>
Ok(BlockImportStatus::ImportedUnknown(number, aux, peer.clone())),
Ok(BlockImportStatus::ImportedUnknown(number, aux, peer)),
Ok(ImportResult::MissingState) => {
debug!(target: "sync", "Parent state is missing for {}: {:?}, parent: {:?}",
number, hash, parent_hash);
@@ -255,7 +255,7 @@ pub(crate) async fn import_single_block_metered<
},
Ok(ImportResult::KnownBad) => {
debug!(target: "sync", "Peer gave us a bad block {}: {:?}", number, hash);
Err(BlockImportError::BadBlock(peer.clone()))
Err(BlockImportError::BadBlock(peer))
},
Err(e) => {
debug!(target: "sync", "Error importing block {}: {:?}: {}", number, hash, e);
@@ -306,7 +306,7 @@ pub(crate) async fn import_single_block_metered<
if let Some(metrics) = metrics.as_ref() {
metrics.report_verification(false, started.elapsed());
}
BlockImportError::VerificationFailed(peer.clone(), msg)
BlockImportError::VerificationFailed(peer, msg)
})?;
if let Some(metrics) = metrics.as_ref() {
@@ -374,7 +374,7 @@ async fn import_many_blocks<B: BlockT, V: Verifier<B>, Transaction: Send + 'stat
},
};
let block_number = block.header.as_ref().map(|h| h.number().clone());
let block_number = block.header.as_ref().map(|h| *h.number());
let block_hash = block.hash;
let import_result = if has_error {
Err(BlockImportError::Cancelled)
@@ -382,7 +382,7 @@ async fn import_many_blocks<B: BlockT, V: Verifier<B>, Transaction: Send + 'stat
// The actual import.
import_single_block_metered(
import_handle,
blocks_origin.clone(),
blocks_origin,
block,
verifier,
metrics.clone(),
@@ -105,14 +105,14 @@ impl<B: BlockT> Link<B> for BufferedLinkSender<B> {
number: NumberFor<B>,
success: bool,
) {
let msg = BlockImportWorkerMsg::JustificationImported(who, hash.clone(), number, success);
let msg = BlockImportWorkerMsg::JustificationImported(who, *hash, number, success);
let _ = self.tx.unbounded_send(msg);
}
fn request_justification(&mut self, hash: &B::Hash, number: NumberFor<B>) {
let _ = self
.tx
.unbounded_send(BlockImportWorkerMsg::RequestJustification(hash.clone(), number));
.unbounded_send(BlockImportWorkerMsg::RequestJustification(*hash, number));
}
}
@@ -79,12 +79,12 @@ where
Block: BlockT,
{
async fn leaves(&self) -> Result<Vec<<Block as BlockT>::Hash>, ConsensusError> {
LongestChain::leaves(self).map_err(|e| ConsensusError::ChainLookup(e.to_string()).into())
LongestChain::leaves(self).map_err(|e| ConsensusError::ChainLookup(e.to_string()))
}
async fn best_chain(&self) -> Result<<Block as BlockT>::Header, ConsensusError> {
LongestChain::best_block_header(&self)
.map_err(|e| ConsensusError::ChainLookup(e.to_string()).into())
LongestChain::best_block_header(self)
.map_err(|e| ConsensusError::ChainLookup(e.to_string()))
}
async fn finality_target(
@@ -97,6 +97,6 @@ where
.blockchain()
.best_containing(target_hash, maybe_max_number, import_lock)
.map(|maybe_hash| maybe_hash.unwrap_or(target_hash))
.map_err(|e| ConsensusError::ChainLookup(e.to_string()).into())
.map_err(|e| ConsensusError::ChainLookup(e.to_string()))
}
}
+4 -4
View File
@@ -566,7 +566,7 @@ where
ViableEpochDescriptor::UnimportedGenesis(slot) =>
Some(ViableEpoch::UnimportedGenesis(make_genesis(*slot))),
ViableEpochDescriptor::Signaled(identifier, _) =>
self.epoch(&identifier).map(ViableEpoch::Signaled),
self.epoch(identifier).map(ViableEpoch::Signaled),
}
}
@@ -599,7 +599,7 @@ where
ViableEpochDescriptor::UnimportedGenesis(slot) =>
Some(ViableEpoch::UnimportedGenesis(make_genesis(*slot))),
ViableEpochDescriptor::Signaled(identifier, _) =>
self.epoch_mut(&identifier).map(ViableEpoch::Signaled),
self.epoch_mut(identifier).map(ViableEpoch::Signaled),
}
}
@@ -618,7 +618,7 @@ where
{
match descriptor {
ViableEpochDescriptor::UnimportedGenesis(slot) => Some(make_genesis(*slot)),
ViableEpochDescriptor::Signaled(identifier, _) => self.epoch(&identifier).cloned(),
ViableEpochDescriptor::Signaled(identifier, _) => self.epoch(identifier).cloned(),
}
}
@@ -750,7 +750,7 @@ where
if let Some(gap) = &mut self.gap {
if let PersistedEpoch::Regular(e) = epoch {
epoch = match gap.import(slot, hash.clone(), number.clone(), e) {
epoch = match gap.import(slot, hash, number, e) {
Ok(()) => return Ok(()),
Err(e) => PersistedEpoch::Regular(e),
}
@@ -114,7 +114,7 @@ where
.epoch_descriptor_for_child_of(
descendent_query(&*self.client),
&parent.hash(),
parent.number().clone(),
*parent.number(),
pre_digest.slot(),
)
.map_err(|e| format!("failed to fetch epoch_descriptor: {}", e))?
@@ -162,11 +162,11 @@ where
.epoch_descriptor_for_child_of(
descendent_query(&*self.client),
&parent.hash(),
parent.number().clone(),
*parent.number(),
slot,
)
.map_err(|e| Error::StringError(format!("failed to fetch epoch_descriptor: {}", e)))?
.ok_or_else(|| sp_consensus::Error::InvalidAuthoritiesSet)?;
.ok_or(sp_consensus::Error::InvalidAuthoritiesSet)?;
let epoch = epoch_changes
.viable_epoch(&epoch_descriptor, |slot| {
@@ -216,19 +216,19 @@ where
.epoch_descriptor_for_child_of(
descendent_query(&*self.client),
&parent.hash(),
parent.number().clone(),
*parent.number(),
slot,
)
.map_err(|e| {
Error::StringError(format!("failed to fetch epoch_descriptor: {}", e))
})?
.ok_or_else(|| sp_consensus::Error::InvalidAuthoritiesSet)?;
.ok_or(sp_consensus::Error::InvalidAuthoritiesSet)?;
match epoch_descriptor {
ViableEpochDescriptor::Signaled(identifier, _epoch_header) => {
let epoch_mut = epoch_changes
.epoch_mut(&identifier)
.ok_or_else(|| sp_consensus::Error::InvalidAuthoritiesSet)?;
.ok_or(sp_consensus::Error::InvalidAuthoritiesSet)?;
// mutate the current epoch
epoch_mut.authorities = self.authorities.clone();
@@ -236,7 +236,7 @@ where
let next_epoch = ConsensusLog::NextEpochData(NextEpochDescriptor {
authorities: self.authorities.clone(),
// copy the old randomness
randomness: epoch_mut.randomness.clone(),
randomness: epoch_mut.randomness,
});
vec![
@@ -268,11 +268,11 @@ where
.epoch_descriptor_for_child_of(
descendent_query(&*self.client),
&parent.hash(),
parent.number().clone(),
*parent.number(),
slot,
)
.map_err(|e| Error::StringError(format!("failed to fetch epoch_descriptor: {}", e)))?
.ok_or_else(|| sp_consensus::Error::InvalidAuthoritiesSet)?;
.ok_or(sp_consensus::Error::InvalidAuthoritiesSet)?;
// drop the lock
drop(epoch_changes);
// a quick check to see if we're in the authorities
+16 -18
View File
@@ -234,7 +234,7 @@ impl<B: BlockT, I: Clone, C, S: Clone, Algorithm: Clone, CAW: Clone, CIDP> Clone
select_chain: self.select_chain.clone(),
client: self.client.clone(),
create_inherent_data_providers: self.create_inherent_data_providers.clone(),
check_inherents_after: self.check_inherents_after.clone(),
check_inherents_after: self.check_inherents_after,
can_author_with: self.can_author_with.clone(),
}
}
@@ -652,21 +652,19 @@ where
},
};
let proposal = match proposer
.propose(inherent_data, inherent_digest, build_time.clone(), None)
.await
{
Ok(x) => x,
Err(err) => {
warn!(
target: "pow",
"Unable to propose new block for authoring. \
Creating proposal failed: {}",
err,
);
continue
},
};
let proposal =
match proposer.propose(inherent_data, inherent_digest, build_time, None).await {
Ok(x) => x,
Err(err) => {
warn!(
target: "pow",
"Unable to propose new block for authoring. \
Creating proposal failed: {}",
err,
);
continue
},
};
let build = MiningBuild::<Block, Algorithm, C, _> {
metadata: MiningMetadata {
@@ -710,8 +708,8 @@ fn fetch_seal<B: BlockT>(digest: Option<&DigestItem>, hash: B::Hash) -> Result<V
if id == &POW_ENGINE_ID {
Ok(seal.clone())
} else {
return Err(Error::<B>::WrongEngine(*id).into())
Err(Error::<B>::WrongEngine(*id))
},
_ => return Err(Error::<B>::HeaderUnsealed(hash).into()),
_ => Err(Error::<B>::HeaderUnsealed(hash)),
}
}
+1 -1
View File
@@ -295,7 +295,7 @@ impl<Block: BlockT> Stream for UntilImportedOrTimeout<Block> {
}
}
let timeout = self.timeout.clone();
let timeout = self.timeout;
let inner_delay = self.inner_delay.get_or_insert_with(|| Delay::new(timeout));
match Future::poll(Pin::new(inner_delay), cx) {
@@ -63,7 +63,7 @@ where
P: Clone + Encode + Decode + PartialEq,
{
// We don't check equivocations for old headers out of our capacity.
if slot_now.saturating_sub(*slot) > Slot::from(MAX_SLOT_CAPACITY) {
if slot_now.saturating_sub(*slot) > MAX_SLOT_CAPACITY {
return Ok(None)
}
+1 -1
View File
@@ -606,7 +606,7 @@ pub fn proposing_remaining_duration<Block: BlockT>(
// if we defined a maximum portion of the slot for proposal then we must make sure the
// lenience doesn't go over it
let lenient_proposing_duration =
if let Some(ref max_block_proposal_slot_portion) = max_block_proposal_slot_portion {
if let Some(max_block_proposal_slot_portion) = max_block_proposal_slot_portion {
std::cmp::min(
lenient_proposing_duration,
slot_info.duration.mul_f32(max_block_proposal_slot_portion.get()),
+19 -24
View File
@@ -57,14 +57,14 @@ impl<Block: BlockT> sp_state_machine::Storage<HashFor<Block>> for StorageDb<Bloc
fn get(&self, key: &Block::Hash, prefix: Prefix) -> Result<Option<DBValue>, String> {
let prefixed_key = prefixed_key::<HashFor<Block>>(key, prefix);
if let Some(recorder) = &self.proof_recorder {
if let Some(v) = recorder.get(&key) {
return Ok(v.clone())
if let Some(v) = recorder.get(key) {
return Ok(v)
}
let backend_value = self
.db
.get(0, &prefixed_key)
.map_err(|e| format!("Database backend error: {:?}", e))?;
recorder.record(key.clone(), backend_value.clone());
recorder.record(*key, backend_value.clone());
Ok(backend_value)
} else {
self.db
@@ -114,7 +114,7 @@ impl<B: BlockT> BenchmarkingState<B> {
let mut state = BenchmarkingState {
state: RefCell::new(None),
db: Cell::new(None),
root: Cell::new(root.clone()),
root: Cell::new(root),
genesis: Default::default(),
genesis_root: Default::default(),
record: Default::default(),
@@ -123,7 +123,7 @@ impl<B: BlockT> BenchmarkingState<B> {
child_key_tracker: Default::default(),
whitelist: Default::default(),
proof_recorder: record_proof.then(Default::default),
proof_recorder_root: Cell::new(root.clone()),
proof_recorder_root: Cell::new(root),
enable_tracking,
};
@@ -143,7 +143,7 @@ impl<B: BlockT> BenchmarkingState<B> {
state_version,
);
state.genesis = transaction.clone().drain();
state.genesis_root = root.clone();
state.genesis_root = root;
state.commit(root, transaction, Vec::new(), Vec::new())?;
state.record.take();
Ok(state)
@@ -201,9 +201,7 @@ impl<B: BlockT> BenchmarkingState<B> {
let mut main_key_tracker = self.main_key_tracker.borrow_mut();
let key_tracker = if let Some(childtrie) = childtrie {
child_key_tracker
.entry(childtrie.to_vec())
.or_insert_with(|| LinkedHashMap::new())
child_key_tracker.entry(childtrie.to_vec()).or_insert_with(LinkedHashMap::new)
} else {
&mut main_key_tracker
};
@@ -244,9 +242,7 @@ impl<B: BlockT> BenchmarkingState<B> {
let mut main_key_tracker = self.main_key_tracker.borrow_mut();
let key_tracker = if let Some(childtrie) = childtrie {
child_key_tracker
.entry(childtrie.to_vec())
.or_insert_with(|| LinkedHashMap::new())
child_key_tracker.entry(childtrie.to_vec()).or_insert_with(LinkedHashMap::new)
} else {
&mut main_key_tracker
};
@@ -517,7 +513,7 @@ impl<B: BlockT> StateBackend<HashFor<B>> for BenchmarkingState<B> {
self.db.set(Some(db));
}
self.root.set(self.genesis_root.clone());
self.root.set(self.genesis_root);
self.reopen()?;
self.wipe_tracker();
Ok(())
@@ -612,18 +608,17 @@ impl<B: BlockT> StateBackend<HashFor<B>> for BenchmarkingState<B> {
if proof_recorder_root == Default::default() || proof_size == 1 {
// empty trie
proof_size
} else if let Some(size) = proof.encoded_compact_size::<HashFor<B>>(proof_recorder_root)
{
size as u32
} else {
if let Some(size) = proof.encoded_compact_size::<HashFor<B>>(proof_recorder_root) {
size as u32
} else {
panic!(
"proof rec root {:?}, root {:?}, genesis {:?}, rec_len {:?}",
self.proof_recorder_root.get(),
self.root.get(),
self.genesis_root,
proof_size,
);
}
panic!(
"proof rec root {:?}, root {:?}, genesis {:?}, rec_len {:?}",
self.proof_recorder_root.get(),
self.root.get(),
self.genesis_root,
proof_size,
);
}
})
}
+47 -55
View File
@@ -352,8 +352,8 @@ impl DatabaseSource {
//
// IIUC this is needed for polkadot to create its own dbs, so until it can use parity db
// I would think rocksdb, but later parity-db.
DatabaseSource::Auto { paritydb_path, .. } => Some(&paritydb_path),
DatabaseSource::RocksDb { path, .. } | DatabaseSource::ParityDb { path } => Some(&path),
DatabaseSource::Auto { paritydb_path, .. } => Some(paritydb_path),
DatabaseSource::RocksDb { path, .. } | DatabaseSource::ParityDb { path } => Some(path),
DatabaseSource::Custom(..) => None,
}
}
@@ -478,7 +478,7 @@ impl<Block: BlockT> BlockchainDb<Block> {
if is_finalized {
if with_state {
meta.finalized_state = Some((hash.clone(), number));
meta.finalized_state = Some((hash, number));
}
meta.finalized_number = number;
meta.finalized_hash = hash;
@@ -501,7 +501,7 @@ impl<Block: BlockT> sc_client_api::blockchain::HeaderBackend<Block> for Blockcha
}
let header =
utils::read_header(&*self.db, columns::KEY_LOOKUP, columns::HEADER, id)?;
cache_header(&mut cache, h.clone(), header.clone());
cache_header(&mut cache, *h, header.clone());
Ok(header)
},
BlockId::Number(_) =>
@@ -517,7 +517,7 @@ impl<Block: BlockT> sc_client_api::blockchain::HeaderBackend<Block> for Blockcha
genesis_hash: meta.genesis_hash,
finalized_hash: meta.finalized_hash,
finalized_number: meta.finalized_number,
finalized_state: meta.finalized_state.clone(),
finalized_state: meta.finalized_state,
number_leaves: self.leaves.read().count(),
block_gap: meta.block_gap,
}
@@ -540,10 +540,7 @@ impl<Block: BlockT> sc_client_api::blockchain::HeaderBackend<Block> for Blockcha
fn hash(&self, number: NumberFor<Block>) -> ClientResult<Option<Block::Hash>> {
self.header(BlockId::Number(number))
.and_then(|maybe_header| match maybe_header {
Some(header) => Ok(Some(header.hash().clone())),
None => Ok(None),
})
.map(|maybe_header| maybe_header.map(|header| header.hash()))
}
}
@@ -621,7 +618,7 @@ impl<Block: BlockT> sc_client_api::blockchain::Backend<Block> for BlockchainDb<B
}
fn last_finalized(&self) -> ClientResult<Block::Hash> {
Ok(self.meta.read().finalized_hash.clone())
Ok(self.meta.read().finalized_hash)
}
fn leaves(&self) -> ClientResult<Vec<Block::Hash>> {
@@ -765,8 +762,8 @@ impl<Block: BlockT> BlockImportOperation<Block> {
storage: Storage,
state_version: StateVersion,
) -> ClientResult<Block::Hash> {
if storage.top.keys().any(|k| well_known_keys::is_child_storage_key(&k)) {
return Err(sp_blockchain::Error::InvalidState.into())
if storage.top.keys().any(|k| well_known_keys::is_child_storage_key(k)) {
return Err(sp_blockchain::Error::InvalidState)
}
let child_delta = storage.children_default.iter().map(|(_storage_key, child_content)| {
@@ -1063,7 +1060,7 @@ impl<Block: BlockT> Backend<Block> {
) -> ClientResult<Self> {
let is_archive_pruning = config.state_pruning.is_archive();
let blockchain = BlockchainDb::new(db.clone())?;
let map_e = |e: sc_state_db::Error<io::Error>| sp_blockchain::Error::from_state_db(e);
let map_e = sp_blockchain::Error::from_state_db;
let state_db: StateDb<_, _> = StateDb::new(
config.state_pruning.clone(),
!db.supports_ref_counting(),
@@ -1087,7 +1084,7 @@ impl<Block: BlockT> Backend<Block> {
is_archive: is_archive_pruning,
io_stats: FrozenForDuration::new(std::time::Duration::from_secs(1)),
state_usage: Arc::new(StateUsageStats::new()),
keep_blocks: config.keep_blocks.clone(),
keep_blocks: config.keep_blocks,
genesis_state: RwLock::new(None),
};
@@ -1135,7 +1132,7 @@ impl<Block: BlockT> Backend<Block> {
(meta.best_number - best_number).saturated_into::<u64>() >
self.canonicalization_delay
{
return Err(sp_blockchain::Error::SetHeadTooOld.into())
return Err(sp_blockchain::Error::SetHeadTooOld)
}
let parent_exists =
@@ -1154,16 +1151,16 @@ impl<Block: BlockT> Backend<Block> {
(&r.number, &r.hash)
);
return Err(::sp_blockchain::Error::NotInFinalizedChain.into())
return Err(::sp_blockchain::Error::NotInFinalizedChain)
}
retracted.push(r.hash.clone());
retracted.push(r.hash);
utils::remove_number_to_key_mapping(transaction, columns::KEY_LOOKUP, r.number)?;
}
// canonicalize: set the number lookup to map to this block's hash.
for e in tree_route.enacted() {
enacted.push(e.hash.clone());
enacted.push(e.hash);
utils::insert_number_to_key_mapping(
transaction,
columns::KEY_LOOKUP,
@@ -1199,8 +1196,7 @@ impl<Block: BlockT> Backend<Block> {
"Last finalized {:?} not parent of {:?}",
last_finalized,
header.hash()
))
.into())
)))
}
Ok(())
}
@@ -1217,7 +1213,7 @@ impl<Block: BlockT> Backend<Block> {
// TODO: ensure best chain contains this block.
let number = *header.number();
self.ensure_sequential_finalization(header, last_finalized)?;
let with_state = sc_client_api::Backend::have_state_at(self, &hash, number);
let with_state = sc_client_api::Backend::have_state_at(self, hash, number);
self.note_finalized(transaction, header, *hash, finalization_displaced, with_state)?;
@@ -1264,9 +1260,10 @@ impl<Block: BlockT> Backend<Block> {
}
trace!(target: "db", "Canonicalize block #{} ({:?})", new_canonical, hash);
let commit = self.storage.state_db.canonicalize_block(&hash).map_err(
|e: sc_state_db::Error<io::Error>| sp_blockchain::Error::from_state_db(e),
)?;
let commit =
self.storage.state_db.canonicalize_block(&hash).map_err(
sp_blockchain::Error::from_state_db::<sc_state_db::Error<io::Error>>,
)?;
apply_state_commit(transaction, commit);
}
Ok(())
@@ -1282,7 +1279,7 @@ impl<Block: BlockT> Backend<Block> {
let mut meta_updates = Vec::with_capacity(operation.finalized_blocks.len());
let (best_num, mut last_finalized_hash, mut last_finalized_num, mut block_gap) = {
let meta = self.blockchain.meta.read();
(meta.best_number, meta.finalized_hash, meta.finalized_number, meta.block_gap.clone())
(meta.best_number, meta.finalized_hash, meta.finalized_number, meta.block_gap)
};
for (block, justification) in operation.finalized_blocks {
@@ -1297,14 +1294,14 @@ impl<Block: BlockT> Backend<Block> {
&mut finalization_displaced_leaves,
)?);
last_finalized_hash = block_hash;
last_finalized_num = block_header.number().clone();
last_finalized_num = *block_header.number();
}
let imported = if let Some(pending_block) = operation.pending_block {
let hash = pending_block.header.hash();
let parent_hash = *pending_block.header.parent_hash();
let number = pending_block.header.number().clone();
let number = *pending_block.header.number();
let existing_header =
number <= best_num && self.blockchain.header(BlockId::hash(hash))?.is_some();
@@ -1352,7 +1349,7 @@ impl<Block: BlockT> Backend<Block> {
// memory to bootstrap consensus. It is queried for an initial list of
// authorities, etc.
*self.genesis_state.write() = Some(Arc::new(DbGenesisStorage::new(
pending_block.header.state_root().clone(),
*pending_block.header.state_root(),
operation.db_updates.clone(),
)));
}
@@ -1411,7 +1408,7 @@ impl<Block: BlockT> Backend<Block> {
let commit = self
.storage
.state_db
.insert_block(&hash, number_u64, &pending_block.header.parent_hash(), changeset)
.insert_block(&hash, number_u64, pending_block.header.parent_hash(), changeset)
.map_err(|e: sc_state_db::Error<io::Error>| {
sp_blockchain::Error::from_state_db(e)
})?;
@@ -1419,7 +1416,7 @@ impl<Block: BlockT> Backend<Block> {
if number <= last_finalized_num {
// Canonicalize in the db when re-importing existing blocks with state.
let commit = self.storage.state_db.canonicalize_block(&hash).map_err(
|e: sc_state_db::Error<io::Error>| sp_blockchain::Error::from_state_db(e),
sp_blockchain::Error::from_state_db::<sc_state_db::Error<io::Error>>,
)?;
apply_state_commit(&mut transaction, commit);
meta_updates.push(MetaUpdate {
@@ -1549,11 +1546,8 @@ impl<Block: BlockT> Backend<Block> {
let number = header.number();
let hash = header.hash();
let (enacted, retracted) = self.set_head_with_transaction(
&mut transaction,
hash.clone(),
(number.clone(), hash.clone()),
)?;
let (enacted, retracted) =
self.set_head_with_transaction(&mut transaction, hash, (*number, hash))?;
meta_updates.push(MetaUpdate {
hash,
number: *number,
@@ -1616,9 +1610,9 @@ impl<Block: BlockT> Backend<Block> {
displaced: &mut Option<FinalizationDisplaced<Block::Hash, NumberFor<Block>>>,
with_state: bool,
) -> ClientResult<()> {
let f_num = f_header.number().clone();
let f_num = *f_header.number();
let lookup_key = utils::number_and_hash_to_lookup_key(f_num, f_hash.clone())?;
let lookup_key = utils::number_and_hash_to_lookup_key(f_num, f_hash)?;
if with_state {
transaction.set_from_vec(columns::META, meta_keys::FINALIZED_STATE, lookup_key.clone());
}
@@ -1631,9 +1625,10 @@ impl<Block: BlockT> Backend<Block> {
.map(|c| f_num.saturated_into::<u64>() > c)
.unwrap_or(true)
{
let commit = self.storage.state_db.canonicalize_block(&f_hash).map_err(
|e: sc_state_db::Error<io::Error>| sp_blockchain::Error::from_state_db(e),
)?;
let commit =
self.storage.state_db.canonicalize_block(&f_hash).map_err(
sp_blockchain::Error::from_state_db::<sc_state_db::Error<io::Error>>,
)?;
apply_state_commit(transaction, commit);
}
@@ -1664,18 +1659,18 @@ impl<Block: BlockT> Backend<Block> {
// Also discard all blocks from displaced branches
for h in displaced.leaves() {
let mut number = finalized;
let mut hash = h.clone();
let mut hash = *h;
// Follow displaced chains back until we reach a finalized block.
// Since leaves are discarded due to finality, they can't have parents
// that are canonical, but not yet finalized. So we stop deleting as soon as
// we reach canonical chain.
while self.blockchain.hash(number)? != Some(hash.clone()) {
let id = BlockId::<Block>::hash(hash.clone());
while self.blockchain.hash(number)? != Some(hash) {
let id = BlockId::<Block>::hash(hash);
match self.blockchain.header(id)? {
Some(header) => {
self.prune_block(transaction, id)?;
number = header.number().saturating_sub(One::one());
hash = header.parent_hash().clone();
hash = *header.parent_hash();
},
None => break,
}
@@ -1780,7 +1775,7 @@ fn apply_index_ops<Block: BlockT>(
// Bump ref counter
let extrinsic = extrinsic.encode();
transaction.reference(columns::TRANSACTION, DbHash::from_slice(hash.as_ref()));
DbExtrinsic::Indexed { hash: hash.clone(), header: extrinsic }
DbExtrinsic::Indexed { hash: *hash, header: extrinsic }
} else {
match index_map.get(&(index as u32)) {
Some((hash, size)) => {
@@ -2063,8 +2058,7 @@ impl<Block: BlockT> sc_client_api::backend::Backend<Block> for Backend<Block> {
let update_finalized = best_number < finalized;
let key =
utils::number_and_hash_to_lookup_key(best_number.clone(), &best_hash)?;
let key = utils::number_and_hash_to_lookup_key(best_number, &best_hash)?;
if update_finalized {
transaction.set_from_vec(
columns::META,
@@ -2143,8 +2137,8 @@ impl<Block: BlockT> sc_client_api::backend::Backend<Block> for Backend<Block> {
return Err(sp_blockchain::Error::Backend(format!("Can't remove best block {:?}", hash)))
}
let hdr = self.blockchain.header_metadata(hash.clone())?;
if !self.have_state_at(&hash, hdr.number) {
let hdr = self.blockchain.header_metadata(*hash)?;
if !self.have_state_at(hash, hdr.number) {
return Err(sp_blockchain::Error::UnknownBlock(format!(
"State already discarded for {:?}",
hash
@@ -2164,7 +2158,7 @@ impl<Block: BlockT> sc_client_api::backend::Backend<Block> for Backend<Block> {
apply_state_commit(&mut transaction, commit);
}
transaction.remove(columns::KEY_LOOKUP, hash.as_ref());
leaves.revert(hash.clone(), hdr.number);
leaves.revert(*hash, hdr.number);
leaves.prepare_transaction(&mut transaction, columns::META, meta_keys::LEAF_PREFIX);
self.storage.db.commit(transaction)?;
self.blockchain().remove_header_metadata(*hash);
@@ -2185,8 +2179,7 @@ impl<Block: BlockT> sc_client_api::backend::Backend<Block> for Backend<Block> {
};
if is_genesis {
if let Some(genesis_state) = &*self.genesis_state.read() {
let root = genesis_state.root.clone();
let db_state = DbState::<Block>::new(genesis_state.clone(), root);
let db_state = DbState::<Block>::new(genesis_state.clone(), genesis_state.root);
let state = RefTrackingState::new(db_state, self.storage.clone(), None);
let caching_state = CachingState::new(state, self.shared_cache.clone(), None);
let mut state = SyncingCachingState::new(
@@ -2218,8 +2211,7 @@ impl<Block: BlockT> sc_client_api::backend::Backend<Block> for Backend<Block> {
if let Ok(()) = self.storage.state_db.pin(&hash) {
let root = hdr.state_root;
let db_state = DbState::<Block>::new(self.storage.clone(), root);
let state =
RefTrackingState::new(db_state, self.storage.clone(), Some(hash.clone()));
let state = RefTrackingState::new(db_state, self.storage.clone(), Some(hash));
let caching_state =
CachingState::new(state, self.shared_cache.clone(), Some(hash));
Ok(SyncingCachingState::new(
@@ -2241,7 +2233,7 @@ impl<Block: BlockT> sc_client_api::backend::Backend<Block> for Backend<Block> {
fn have_state_at(&self, hash: &Block::Hash, number: NumberFor<Block>) -> bool {
if self.is_archive {
match self.blockchain.header_metadata(hash.clone()) {
match self.blockchain.header_metadata(*hash) {
Ok(header) => sp_state_machine::Storage::get(
self.storage.as_ref(),
&header.state_root,
+2 -2
View File
@@ -104,7 +104,7 @@ impl sp_core::offchain::OffchainStorage for LocalStorage {
{
drop(key_lock);
let key_lock = locks.get_mut(&key);
if let Some(_) = key_lock.and_then(Arc::get_mut) {
if key_lock.and_then(Arc::get_mut).is_some() {
locks.remove(&key);
}
}
@@ -114,7 +114,7 @@ impl sp_core::offchain::OffchainStorage for LocalStorage {
/// Concatenate the prefix and key to create an offchain key in the db.
pub(crate) fn concatenate_prefix_and_key(prefix: &[u8], key: &[u8]) -> Vec<u8> {
prefix.iter().chain(key.into_iter()).cloned().collect()
prefix.iter().chain(key.iter()).cloned().collect()
}
#[cfg(test)]
+7 -7
View File
@@ -360,9 +360,9 @@ impl<B: BlockT> CacheChanges<B> {
// Same block comitted twice with different state changes.
// Treat it as reenacted/retracted.
if is_best {
enacted.push(commit_hash.clone());
enacted.push(*commit_hash);
} else {
retracted.to_mut().push(commit_hash.clone());
retracted.to_mut().push(*commit_hash);
}
}
}
@@ -371,7 +371,7 @@ impl<B: BlockT> CacheChanges<B> {
// Propagate cache only if committing on top of the latest canonical state
// blocks are ordered by number and only one block with a given number is marked as
// canonical (contributed to canonical state cache)
if let Some(_) = self.parent_hash {
if self.parent_hash.is_some() {
let mut local_cache = self.local_cache.write();
if is_best {
trace!(
@@ -423,9 +423,9 @@ impl<B: BlockT> CacheChanges<B> {
storage: modifications,
child_storage: child_modifications,
number: *number,
hash: hash.clone(),
hash: *hash,
is_canon: is_best,
parent: parent.clone(),
parent: *parent,
};
let insert_at = cache
.modifications
@@ -564,7 +564,7 @@ impl<S: StateBackend<HashFor<B>>, B: BlockT> StateBackend<HashFor<B>> for Cachin
let cache = self.cache.shared_cache.upgradable_read();
if Self::is_allowed(Some(key), None, &self.cache.parent_hash, &cache.modifications) {
let mut cache = RwLockUpgradableReadGuard::upgrade(cache);
if let Some(entry) = cache.lru_hashes.get(key).map(|a| a.0.clone()) {
if let Some(entry) = cache.lru_hashes.get(key).map(|a| a.0) {
trace!("Found hash in shared cache: {:?}", HexDisplay::from(&key));
return Ok(entry)
}
@@ -934,7 +934,7 @@ impl<S, B: BlockT> Drop for SyncingCachingState<S, B> {
let _lock = self.lock.read();
self.state_usage.merge_sm(caching_state.usage.take());
if let Some(hash) = caching_state.cache.parent_hash.clone() {
if let Some(hash) = caching_state.cache.parent_hash {
let is_best = self.meta.read().best_hash == hash;
caching_state.cache.sync_cache(&[], &[], vec![], vec![], None, None, is_best);
}
+1 -1
View File
@@ -30,7 +30,7 @@ use kvdb_rocksdb::{Database, DatabaseConfig};
use sp_runtime::traits::Block as BlockT;
/// Version file name.
const VERSION_FILE_NAME: &'static str = "db_version";
const VERSION_FILE_NAME: &str = "db_version";
/// Current db version.
const CURRENT_VERSION: u32 = 4;
+15 -15
View File
@@ -201,16 +201,16 @@ fn open_database_at<Block: BlockT>(
db_type: DatabaseType,
) -> sp_blockchain::Result<Arc<dyn Database<DbHash>>> {
let db: Arc<dyn Database<DbHash>> = match &source {
DatabaseSource::ParityDb { path } => open_parity_db::<Block>(&path, db_type, true)?,
DatabaseSource::ParityDb { path } => open_parity_db::<Block>(path, db_type, true)?,
DatabaseSource::RocksDb { path, cache_size } =>
open_kvdb_rocksdb::<Block>(&path, db_type, true, *cache_size)?,
open_kvdb_rocksdb::<Block>(path, db_type, true, *cache_size)?,
DatabaseSource::Custom(db) => db.clone(),
DatabaseSource::Auto { paritydb_path, rocksdb_path, cache_size } => {
// check if rocksdb exists first, if not, open paritydb
match open_kvdb_rocksdb::<Block>(&rocksdb_path, db_type, false, *cache_size) {
match open_kvdb_rocksdb::<Block>(rocksdb_path, db_type, false, *cache_size) {
Ok(db) => db,
Err(OpenDbError::NotEnabled(_)) | Err(OpenDbError::DoesNotExist) =>
open_parity_db::<Block>(&paritydb_path, db_type, true)?,
open_parity_db::<Block>(paritydb_path, db_type, true)?,
Err(_) => return Err(backend_err("cannot open rocksdb. corrupted database")),
}
},
@@ -234,7 +234,7 @@ type OpenDbResult = Result<Arc<dyn Database<DbHash>>, OpenDbError>;
impl fmt::Display for OpenDbError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
OpenDbError::Internal(e) => write!(f, "{}", e.to_string()),
OpenDbError::Internal(e) => write!(f, "{}", e),
OpenDbError::DoesNotExist => write!(f, "Database does not exist at given location"),
OpenDbError::NotEnabled(feat) => {
write!(f, "`{}` feature not enabled, database can not be opened", feat)
@@ -300,7 +300,7 @@ fn open_kvdb_rocksdb<Block: BlockT>(
cache_size: usize,
) -> OpenDbResult {
// first upgrade database to required version
match crate::upgrade::upgrade_db::<Block>(&path, db_type) {
match crate::upgrade::upgrade_db::<Block>(path, db_type) {
// in case of missing version file, assume that database simply does not exist at given
// location
Ok(_) | Err(crate::upgrade::UpgradeError::MissingDatabaseVersionFile) => (),
@@ -363,8 +363,7 @@ pub fn check_database_type(
return Err(sp_blockchain::Error::Backend(format!(
"Unexpected database type. Expected: {}",
db_type.as_str()
))
.into())
)))
},
None => {
let mut transaction = Transaction::new();
@@ -425,9 +424,9 @@ pub fn read_db<Block>(
where
Block: BlockT,
{
block_id_to_lookup_key(db, col_index, id).and_then(|key| match key {
Some(key) => Ok(db.get(col, key.as_ref())),
None => Ok(None),
block_id_to_lookup_key(db, col_index, id).map(|key| match key {
Some(key) => db.get(col, key.as_ref()),
None => None,
})
}
@@ -442,9 +441,10 @@ pub fn remove_from_db<Block>(
where
Block: BlockT,
{
block_id_to_lookup_key(db, col_index, id).and_then(|key| match key {
Some(key) => Ok(transaction.remove(col, key.as_ref())),
None => Ok(()),
block_id_to_lookup_key(db, col_index, id).map(|key| {
if let Some(key) = key {
transaction.remove(col, key.as_ref());
}
})
}
@@ -458,7 +458,7 @@ pub fn read_header<Block: BlockT>(
match read_db(db, col_index, col, id)? {
Some(header) => match Block::Header::decode(&mut &header[..]) {
Ok(header) => Ok(Some(header)),
Err(_) => return Err(sp_blockchain::Error::Backend("Error decoding header".into())),
Err(_) => Err(sp_blockchain::Error::Backend("Error decoding header".into())),
},
None => Ok(None),
}
@@ -39,7 +39,7 @@ impl DataSegmentsSnapshot {
.map(|mut segment| {
// Just replace contents of the segment since the segments will be discarded later
// anyway.
let contents = mem::replace(segment.value_mut(), vec![]);
let contents = mem::take(segment.value_mut());
let init_expr = match segment.offset() {
Some(offset) => offset.code(),
@@ -187,9 +187,7 @@ impl RuntimeBlob {
}
/// Returns an iterator of all globals which were exported by [`expose_mutable_globals`].
pub(super) fn exported_internal_global_names<'module>(
&'module self,
) -> impl Iterator<Item = &'module str> {
pub(super) fn exported_internal_global_names(&self) -> impl Iterator<Item = &str> {
let exports = self.raw_module.export_section().map(|es| es.entries()).unwrap_or(&[]);
exports.iter().filter_map(|export| match export.internal() {
Internal::Global(_) if export.field().starts_with("exported_internal_global") =>
@@ -264,8 +264,8 @@ fn decode_environment_definition(
let memory_ref = memories
.get(memory_idx as usize)
.cloned()
.ok_or_else(|| InstantiationError::EnvironmentDefinitionCorrupted)?
.ok_or_else(|| InstantiationError::EnvironmentDefinitionCorrupted)?;
.ok_or(InstantiationError::EnvironmentDefinitionCorrupted)?
.ok_or(InstantiationError::EnvironmentDefinitionCorrupted)?;
memories_map.insert((module, field), memory_ref);
},
}
@@ -458,7 +458,7 @@ impl<DT: Clone> Store<DT> {
};
let mem_idx = memories.len();
memories.push(Some(memory.clone()));
memories.push(Some(memory));
Ok(mem_idx as u32)
}
@@ -472,7 +472,7 @@ impl<DT: Clone> Store<DT> {
pub fn instance(&self, instance_idx: u32) -> Result<Rc<SandboxInstance>> {
self.instances
.get(instance_idx as usize)
.ok_or_else(|| "Trying to access a non-existent instance")?
.ok_or("Trying to access a non-existent instance")?
.as_ref()
.map(|v| v.0.clone())
.ok_or_else(|| "Trying to access a torndown instance".into())
@@ -488,7 +488,7 @@ impl<DT: Clone> Store<DT> {
self.instances
.get(instance_idx as usize)
.as_ref()
.ok_or_else(|| "Trying to access a non-existent instance")?
.ok_or("Trying to access a non-existent instance")?
.as_ref()
.map(|v| v.1.clone())
.ok_or_else(|| "Trying to access a torndown instance".into())
@@ -504,7 +504,7 @@ impl<DT: Clone> Store<DT> {
self.memories
.get(memory_idx as usize)
.cloned()
.ok_or_else(|| "Trying to access a non-existent sandboxed memory")?
.ok_or("Trying to access a non-existent sandboxed memory")?
.ok_or_else(|| "Trying to access a torndown sandboxed memory".into())
}
@@ -564,7 +564,7 @@ impl<DT: Clone> Store<DT> {
#[cfg(feature = "wasmer-sandbox")]
BackendContext::Wasmer(ref context) =>
wasmer_instantiate(&context, wasm, guest_env, state, sandbox_context)?,
wasmer_instantiate(context, wasm, guest_env, state, sandbox_context)?,
};
Ok(UnregisteredInstance { sandbox_instance })
@@ -113,7 +113,7 @@ pub fn instantiate(
type Exports = HashMap<String, wasmer::Exports>;
let mut exports_map = Exports::new();
for import in module.imports().into_iter() {
for import in module.imports() {
match import.ty() {
// Nothing to do here
wasmer::ExternType::Global(_) | wasmer::ExternType::Table(_) => (),
@@ -121,7 +121,7 @@ pub fn instantiate(
wasmer::ExternType::Memory(_) => {
let exports = exports_map
.entry(import.module().to_string())
.or_insert(wasmer::Exports::new());
.or_insert_with(wasmer::Exports::new);
let memory = guest_env
.imports
@@ -173,7 +173,7 @@ pub fn instantiate(
let exports = exports_map
.entry(import.module().to_string())
.or_insert(wasmer::Exports::new());
.or_insert_with(wasmer::Exports::new);
exports.insert(import.name(), wasmer::Extern::Function(function));
},
@@ -78,7 +78,7 @@ impl ImportResolver for Imports {
// Here we use inner memory reference only to resolve the imports
// without accessing the memory contents. All subsequent memory accesses
// should happen through the wrapper, that enforces the memory access protocol.
let mem = wrapper.0.clone();
let mem = wrapper.0;
Ok(mem)
}
@@ -247,7 +247,7 @@ impl<'a> wasmi::Externals for GuestExternals<'a> {
serialized_result_val_ptr,
"Can't deallocate memory for dispatch thunk's result",
)
.and_then(|_| serialized_result_val)
.and(serialized_result_val)
.and_then(|serialized_result_val| {
let result_val = std::result::Result::<ReturnValue, HostError>::decode(&mut serialized_result_val.as_slice())
.map_err(|_| trap("Decoding Result<ReturnValue, HostError> failed!"))?;
@@ -253,7 +253,7 @@ where
wasm_code: &[u8],
ext: &mut dyn Externalities,
) -> std::result::Result<Vec<u8>, String> {
let runtime_blob = RuntimeBlob::uncompress_if_needed(&wasm_code)
let runtime_blob = RuntimeBlob::uncompress_if_needed(wasm_code)
.map_err(|e| format!("Failed to create runtime blob: {:?}", e))?;
if let Some(version) = crate::wasm_runtime::read_embedded_version(&runtime_blob)
@@ -493,8 +493,7 @@ impl RuntimeSpawn for RuntimeInstanceSpawn {
fn join(&self, handle: u64) -> Vec<u8> {
let receiver = self.tasks.lock().remove(&handle).expect("No task for the handle");
let output = receiver.recv().expect("Spawned task panicked for the handle");
output
receiver.recv().expect("Spawned task panicked for the handle")
}
}
@@ -368,7 +368,7 @@ pub fn read_embedded_version(blob: &RuntimeBlob) -> Result<Option<RuntimeVersion
.transpose()?
.map(Into::into);
let core_version = apis.as_ref().and_then(|apis| sp_version::core_version_from_apis(apis));
let core_version = apis.as_ref().and_then(sp_version::core_version_from_apis);
// We do not use `RuntimeVersion::decode` here because that `decode_version` relies on
// presence of a special API in the `apis` field to treat the input as a non-legacy version.
// However the structure found in the `runtime_version` always contain an empty `apis`
@@ -403,7 +403,7 @@ where
{
// The incoming code may be actually compressed. We decompress it here and then work with
// the uncompressed code from now on.
let blob = sc_executor_common::runtime_blob::RuntimeBlob::uncompress_if_needed(&code)?;
let blob = sc_executor_common::runtime_blob::RuntimeBlob::uncompress_if_needed(code)?;
// Use the runtime blob to scan if there is any metadata embedded into the wasm binary
// pertaining to runtime version. We do it before consuming the runtime blob for creating the
+13 -13
View File
@@ -103,7 +103,7 @@ impl<'a> sandbox::SandboxContext for SandboxContext<'a> {
match result {
Ok(Some(RuntimeValue::I64(val))) => Ok(val),
Ok(_) => return Err("Supervisor function returned unexpected result!".into()),
Ok(_) => Err("Supervisor function returned unexpected result!".into()),
Err(err) => Err(Error::Sandbox(err.to_string())),
}
}
@@ -161,7 +161,7 @@ impl Sandbox for FunctionExecutor {
Ok(buffer) => buffer,
};
if let Err(_) = self.memory.set(buf_ptr.into(), &buffer) {
if self.memory.set(buf_ptr.into(), &buffer).is_err() {
return Ok(sandbox_env::ERR_OUT_OF_BOUNDS)
}
@@ -185,7 +185,7 @@ impl Sandbox for FunctionExecutor {
Ok(buffer) => buffer,
};
if let Err(_) = sandboxed_memory.write_from(Pointer::new(offset as u32), &buffer) {
if sandboxed_memory.write_from(Pointer::new(offset as u32), &buffer).is_err() {
return Ok(sandbox_env::ERR_OUT_OF_BOUNDS)
}
@@ -241,9 +241,9 @@ impl Sandbox for FunctionExecutor {
Ok(None) => Ok(sandbox_env::ERR_OK),
Ok(Some(val)) => {
// Serialize return value and write it back into the memory.
sp_wasm_interface::ReturnValue::Value(val.into()).using_encoded(|val| {
sp_wasm_interface::ReturnValue::Value(val).using_encoded(|val| {
if val.len() > return_val_len as usize {
Err("Return value buffer is too small")?;
return Err("Return value buffer is too small".into())
}
self.write_memory(return_val, val).map_err(|_| "Return value buffer is OOB")?;
Ok(sandbox_env::ERR_OK)
@@ -272,11 +272,11 @@ impl Sandbox for FunctionExecutor {
let table = self
.table
.as_ref()
.ok_or_else(|| "Runtime doesn't have a table; sandbox is unavailable")?;
.ok_or("Runtime doesn't have a table; sandbox is unavailable")?;
table
.get(dispatch_thunk_id)
.map_err(|_| "dispatch_thunk_idx is out of the table bounds")?
.ok_or_else(|| "dispatch_thunk_idx points on an empty table entry")?
.ok_or("dispatch_thunk_idx points on an empty table entry")?
};
let guest_env =
@@ -458,9 +458,9 @@ impl wasmi::Externals for FunctionExecutor {
fn get_mem_instance(module: &ModuleRef) -> Result<MemoryRef, Error> {
Ok(module
.export_by_name("memory")
.ok_or_else(|| Error::InvalidMemoryReference)?
.ok_or(Error::InvalidMemoryReference)?
.as_memory()
.ok_or_else(|| Error::InvalidMemoryReference)?
.ok_or(Error::InvalidMemoryReference)?
.clone())
}
@@ -469,9 +469,9 @@ fn get_mem_instance(module: &ModuleRef) -> Result<MemoryRef, Error> {
fn get_heap_base(module: &ModuleRef) -> Result<u32, Error> {
let heap_base_val = module
.export_by_name("__heap_base")
.ok_or_else(|| Error::HeapBaseNotFoundOrInvalid)?
.ok_or(Error::HeapBaseNotFoundOrInvalid)?
.as_global()
.ok_or_else(|| Error::HeapBaseNotFoundOrInvalid)?
.ok_or(Error::HeapBaseNotFoundOrInvalid)?
.get();
match heap_base_val {
@@ -564,7 +564,7 @@ fn call_in_wasm_module(
match result {
Ok(Some(I64(r))) => {
let (ptr, length) = unpack_ptr_and_len(r as u64);
memory.get(ptr.into(), length as usize).map_err(|_| Error::Runtime)
memory.get(ptr, length as usize).map_err(|_| Error::Runtime)
},
Err(e) => {
trace!(
@@ -572,7 +572,7 @@ fn call_in_wasm_module(
"Failed to execute code with {} pages",
memory.current_size().0,
);
Err(e.into())
Err(e)
},
_ => Err(Error::InvalidReturn),
}
+9 -10
View File
@@ -243,7 +243,7 @@ impl<'a> Sandbox for HostContext<'a> {
// Serialize return value and write it back into the memory.
sp_wasm_interface::ReturnValue::Value(val.into()).using_encoded(|val| {
if val.len() > return_val_len as usize {
Err("Return value buffer is too small")?;
return Err("Return value buffer is too small".into())
}
<HostContext as FunctionContext>::write_memory(self, return_val, val)
.map_err(|_| "can't write return value")?;
@@ -273,19 +273,18 @@ impl<'a> Sandbox for HostContext<'a> {
.caller
.data()
.table()
.ok_or_else(|| "Runtime doesn't have a table; sandbox is unavailable")?;
.ok_or("Runtime doesn't have a table; sandbox is unavailable")?;
let table_item = table.get(&mut self.caller, dispatch_thunk_id);
table_item
.ok_or_else(|| "dispatch_thunk_id is out of bounds")?
.ok_or("dispatch_thunk_id is out of bounds")?
.funcref()
.ok_or_else(|| "dispatch_thunk_idx should be a funcref")?
.ok_or_else(|| "dispatch_thunk_idx should point to actual func")?
.ok_or("dispatch_thunk_idx should be a funcref")?
.ok_or("dispatch_thunk_idx should point to actual func")?
.clone()
};
let guest_env = match sandbox::GuestEnvironment::decode(&self.sandbox_store(), raw_env_def)
{
let guest_env = match sandbox::GuestEnvironment::decode(self.sandbox_store(), raw_env_def) {
Ok(guest_env) => guest_env,
Err(_) => return Ok(sandbox_env::ERR_MODULE as u32),
};
@@ -304,7 +303,7 @@ impl<'a> Sandbox for HostContext<'a> {
wasm,
guest_env,
state,
&mut SandboxContext { host_context: self, dispatch_thunk: dispatch_thunk.clone() },
&mut SandboxContext { host_context: self, dispatch_thunk },
)
}));
@@ -316,7 +315,7 @@ impl<'a> Sandbox for HostContext<'a> {
};
let instance_idx_or_err_code = match result {
Ok(instance) => instance.register(&mut self.sandbox_store_mut(), dispatch_thunk),
Ok(instance) => instance.register(self.sandbox_store_mut(), dispatch_thunk),
Err(sandbox::InstantiationError::StartTrapped) => sandbox_env::ERR_EXECUTION,
Err(_) => sandbox_env::ERR_MODULE,
};
@@ -366,7 +365,7 @@ impl<'a, 'b> sandbox::SandboxContext for SandboxContext<'a, 'b> {
if let Some(ret_val) = ret_vals[0].i64() {
Ok(ret_val)
} else {
return Err("Supervisor function returned unexpected result!".into())
Err("Supervisor function returned unexpected result!".into())
},
Err(err) => Err(err.to_string().into()),
}
@@ -88,10 +88,10 @@ impl RoundState {
voters: &HashSet<AuthorityId>,
) -> Result<Self, Error> {
let prevotes = &round_state.prevote_ids;
let missing_prevotes = voters.difference(&prevotes).cloned().collect();
let missing_prevotes = voters.difference(prevotes).cloned().collect();
let precommits = &round_state.precommit_ids;
let missing_precommits = voters.difference(&precommits).cloned().collect();
let missing_precommits = voters.difference(precommits).cloned().collect();
Ok(Self {
round: round.try_into()?,
@@ -557,8 +557,7 @@ where
fork_tree::FinalizationResult::Changed(change) => {
status.changed = true;
let pending_forced_changes =
std::mem::replace(&mut self.pending_forced_changes, Vec::new());
let pending_forced_changes = std::mem::take(&mut self.pending_forced_changes);
// we will keep all forced changes for any later blocks and that are a
// descendent of the finalized block (i.e. they are part of this branch).
@@ -430,7 +430,7 @@ where
// reset.
let set_state = VoterSetState::<Block>::live(
new_set.set_id,
&set,
set,
(new_set.canon_hash, new_set.canon_number),
);
let encoded = set_state.encode();
@@ -504,13 +504,13 @@ impl<N: Ord> Peers<N> {
fn new_peer(&mut self, who: PeerId, role: ObservedRole) {
match role {
ObservedRole::Authority if self.first_stage_peers.len() < LUCKY_PEERS => {
self.first_stage_peers.insert(who.clone());
self.first_stage_peers.insert(who);
},
ObservedRole::Authority if self.second_stage_peers.len() < LUCKY_PEERS => {
self.second_stage_peers.insert(who.clone());
self.second_stage_peers.insert(who);
},
ObservedRole::Light if self.lucky_light_peers.len() < LUCKY_PEERS => {
self.lucky_light_peers.insert(who.clone());
self.lucky_light_peers.insert(who);
},
_ => {},
}
@@ -590,11 +590,8 @@ impl<N: Ord> Peers<N> {
// - third set: LUCKY_PEERS random light client peers
let shuffled_peers = {
let mut peers = self
.inner
.iter()
.map(|(peer_id, info)| (*peer_id, info.clone()))
.collect::<Vec<_>>();
let mut peers =
self.inner.iter().map(|(peer_id, info)| (*peer_id, info)).collect::<Vec<_>>();
peers.shuffle(&mut rand::thread_rng());
peers
@@ -1103,7 +1100,7 @@ impl<Block: BlockT> Inner<Block> {
// won't be able to reply since they don't follow the full GRANDPA
// protocol and therefore might not have the vote data available.
if let (Some(peer), Some(local_view)) = (self.peers.peer(who), &self.local_view) {
if self.catch_up_config.request_allowed(&peer) &&
if self.catch_up_config.request_allowed(peer) &&
peer.view.set_id == local_view.set_id &&
peer.view.round.0.saturating_sub(CATCH_UP_THRESHOLD) > local_view.round.0
{
@@ -1195,7 +1192,7 @@ impl<Block: BlockT> Inner<Block> {
return (false, None)
} else {
// report peer for timeout
Some((peer.clone(), cost::CATCH_UP_REQUEST_TIMEOUT))
Some((*peer, cost::CATCH_UP_REQUEST_TIMEOUT))
}
},
PendingCatchUp::Processing { instant, .. } => {
@@ -1209,7 +1206,7 @@ impl<Block: BlockT> Inner<Block> {
};
self.pending_catch_up = PendingCatchUp::Requesting {
who: who.clone(),
who: *who,
request: catch_up_request.clone(),
instant: Instant::now(),
};
@@ -1488,7 +1485,7 @@ impl<Block: BlockT> sc_network_gossip::Validator<Block> for GossipValidator<Bloc
) {
let packet = {
let mut inner = self.inner.write();
inner.peers.new_peer(who.clone(), roles);
inner.peers.new_peer(*who, roles);
inner.local_view.as_ref().map(|v| NeighborPacket {
round: v.round,
@@ -1526,16 +1523,16 @@ impl<Block: BlockT> sc_network_gossip::Validator<Block> for GossipValidator<Bloc
match action {
Action::Keep(topic, cb) => {
self.report(who.clone(), cb);
self.report(*who, cb);
context.broadcast_message(topic, data.to_vec(), false);
sc_network_gossip::ValidationResult::ProcessAndKeep(topic)
},
Action::ProcessAndDiscard(topic, cb) => {
self.report(who.clone(), cb);
self.report(*who, cb);
sc_network_gossip::ValidationResult::ProcessAndDiscard(topic)
},
Action::Discard(cb) => {
self.report(who.clone(), cb);
self.report(*who, cb);
sc_network_gossip::ValidationResult::Discard
},
}
@@ -1572,7 +1569,7 @@ impl<Block: BlockT> sc_network_gossip::Validator<Block> for GossipValidator<Bloc
// if the topic is not something we're keeping at the moment,
// do not send.
let (maybe_round, set_id) = match inner.live_topics.topic_info(&topic) {
let (maybe_round, set_id) = match inner.live_topics.topic_info(topic) {
None => return false,
Some(x) => x,
};
@@ -1583,11 +1580,9 @@ impl<Block: BlockT> sc_network_gossip::Validator<Block> for GossipValidator<Bloc
// early return if the vote message isn't allowed at this stage.
return false
}
} else {
if !inner.global_message_allowed(who) {
// early return if the global message isn't allowed at this stage.
return false
}
} else if !inner.global_message_allowed(who) {
// early return if the global message isn't allowed at this stage.
return false
}
}
@@ -70,9 +70,9 @@ pub(crate) mod tests;
pub mod grandpa_protocol_name {
use sc_chain_spec::ChainSpec;
pub(crate) const NAME: &'static str = "/grandpa/1";
pub(crate) const NAME: &str = "/grandpa/1";
/// Old names for the notifications protocol, used for backward compatibility.
pub(crate) const LEGACY_NAMES: [&'static str; 1] = ["/paritytech/grandpa/1"];
pub(crate) const LEGACY_NAMES: [&str; 1] = ["/paritytech/grandpa/1"];
/// Name of the notifications protocol used by GRANDPA.
///
@@ -876,7 +876,7 @@ fn check_catch_up<Block: BlockT>(
let mut total_weight = 0;
for id in votes {
if let Some(weight) = voters.get(&id).map(|info| info.weight()) {
if let Some(weight) = voters.get(id).map(|info| info.weight()) {
total_weight += weight.get();
if total_weight > full_threshold {
return Err(cost::MALFORMED_CATCH_UP)
@@ -451,7 +451,7 @@ impl<BE, Block: BlockT, C, N: NetworkT<Block>, SC, VR> Environment<BE, Block, C,
F: FnOnce(&VoterSetState<Block>) -> Result<Option<VoterSetState<Block>>, Error>,
{
self.voter_set_state.with(|voter_set_state| {
if let Some(set_state) = f(&voter_set_state)? {
if let Some(set_state) = f(voter_set_state)? {
*voter_set_state = set_state;
if let Some(metrics) = self.metrics.as_ref() {
@@ -987,11 +987,9 @@ where
let mut current_rounds = current_rounds.clone();
current_rounds.remove(&round);
// NOTE: this condition should always hold as GRANDPA rounds are always
// NOTE: this entry should always exist as GRANDPA rounds are always
// started in increasing order, still it's better to play it safe.
if !current_rounds.contains_key(&(round + 1)) {
current_rounds.insert(round + 1, HasVoted::No);
}
current_rounds.entry(round + 1).or_insert(HasVoted::No);
let set_state = VoterSetState::<Block>::Live { completed_rounds, current_rounds };
@@ -1046,7 +1044,7 @@ where
.votes
.extend(historical_votes.seen().iter().skip(n_existing_votes).cloned());
already_completed.state = state;
crate::aux_schema::write_concluded_round(&*self.client, &already_completed)?;
crate::aux_schema::write_concluded_round(&*self.client, already_completed)?;
}
let set_state = VoterSetState::<Block>::Live {
@@ -439,8 +439,7 @@ where
// This code may be removed once warp sync to an old runtime is no longer needed.
for prefix in ["GrandpaFinality", "Grandpa"] {
let k = [twox_128(prefix.as_bytes()), twox_128(b"CurrentSetId")].concat();
if let Ok(Some(id)) =
self.inner.storage(&id, &sc_client_api::StorageKey(k.to_vec()))
if let Ok(Some(id)) = self.inner.storage(id, &sc_client_api::StorageKey(k.to_vec()))
{
if let Ok(id) = SetId::decode(&mut id.0.as_ref()) {
return Ok(id)
@@ -451,7 +450,7 @@ where
} else {
self.inner
.runtime_api()
.current_set_id(&id)
.current_set_id(id)
.map_err(|e| ConsensusError::ClientImport(e.to_string()))
}
}
@@ -732,7 +731,7 @@ impl<Backend, Block: BlockT, Client, SC> GrandpaBlockImport<Backend, Block, Clie
authority_set.pending_standard_changes =
authority_set.pending_standard_changes.clone().map(&mut |hash, _, original| {
authority_set_hard_forks.get(&hash).cloned().unwrap_or(original)
authority_set_hard_forks.get(hash).cloned().unwrap_or(original)
});
}
@@ -63,7 +63,7 @@ where
base: Block::Hash,
block: Block::Hash,
) -> Result<Vec<Block::Hash>, GrandpaError> {
environment::ancestry(&self.client, base, block)
environment::ancestry(self.client, base, block)
}
}
@@ -193,13 +193,13 @@ where
);
let observer_work = ObserverWork::new(
client.clone(),
client,
network,
persistent_data,
config.keystore,
voter_commands_rx,
Some(justification_sender),
telemetry.clone(),
telemetry,
);
let observer_work = observer_work.map_ok(|_| ()).map_err(|e| {
@@ -125,7 +125,7 @@ where
let current_target = current_target.clone();
// find the block at the given target height
Box::pin(std::future::ready(find_target(&*backend, target_number.clone(), &current_target)))
Box::pin(std::future::ready(find_target(&*backend, target_number, &current_target)))
}
}
@@ -205,7 +205,7 @@ impl<Block: BlockT> WarpSyncProof<Block> {
let hash = proof.header.hash();
let number = *proof.header.number();
if let Some((set_id, list)) = hard_forks.get(&(hash.clone(), number)) {
if let Some((set_id, list)) = hard_forks.get(&(hash, number)) {
current_set_id = *set_id;
current_authorities = list.clone();
} else {
+3 -3
View File
@@ -116,7 +116,7 @@ where
if let Some((ref last_num, ref last_hash)) = last_best {
if n.header.parent_hash() != last_hash && n.is_new_best {
let maybe_ancestor =
sp_blockchain::lowest_common_ancestor(&*client, last_hash.clone(), n.hash);
sp_blockchain::lowest_common_ancestor(&*client, *last_hash, n.hash);
match maybe_ancestor {
Ok(ref ancestor) if ancestor.hash != *last_hash => info!(
@@ -135,13 +135,13 @@ where
}
if n.is_new_best {
last_best = Some((n.header.number().clone(), n.hash.clone()));
last_best = Some((*n.header.number(), n.hash));
}
// If we already printed a message for a given block recently,
// we should not print it again.
if !last_blocks.contains(&n.hash) {
last_blocks.push_back(n.hash.clone());
last_blocks.push_back(n.hash);
if last_blocks.len() > max_blocks_to_track {
last_blocks.pop_front();
+5 -5
View File
@@ -198,7 +198,7 @@ impl SyncCryptoStore for LocalKeystore {
.0
.read()
.key_pair_by_type::<ed25519::Pair>(&pub_key, id)
.map_err(|e| TraitError::from(e))?;
.map_err(TraitError::from)?;
key_pair.map(|k| k.sign(msg).encode()).map(Ok).transpose()
},
sr25519::CRYPTO_ID => {
@@ -209,7 +209,7 @@ impl SyncCryptoStore for LocalKeystore {
.0
.read()
.key_pair_by_type::<sr25519::Pair>(&pub_key, id)
.map_err(|e| TraitError::from(e))?;
.map_err(TraitError::from)?;
key_pair.map(|k| k.sign(msg).encode()).map(Ok).transpose()
},
ecdsa::CRYPTO_ID => {
@@ -220,7 +220,7 @@ impl SyncCryptoStore for LocalKeystore {
.0
.read()
.key_pair_by_type::<ecdsa::Pair>(&pub_key, id)
.map_err(|e| TraitError::from(e))?;
.map_err(TraitError::from)?;
key_pair.map(|k| k.sign(msg).encode()).map(Ok).transpose()
},
_ => Err(TraitError::KeyNotSupported(id)),
@@ -320,7 +320,7 @@ impl SyncCryptoStore for LocalKeystore {
fn has_keys(&self, public_keys: &[(Vec<u8>, KeyTypeId)]) -> bool {
public_keys
.iter()
.all(|(p, t)| self.0.read().key_phrase_by_type(&p, *t).ok().flatten().is_some())
.all(|(p, t)| self.0.read().key_phrase_by_type(p, *t).ok().flatten().is_some())
}
fn sr25519_vrf_sign(
@@ -536,7 +536,7 @@ impl KeystoreInner {
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
match hex::decode(name) {
Ok(ref hex) if hex.len() > 4 => {
if &hex[0..4] != &id.0 {
if hex[0..4] != id.0 {
continue
}
let public = hex[4..].to_vec();
@@ -88,8 +88,7 @@ impl<'g, 'p, B: BlockT> ValidatorContext<B> for NetworkContext<'g, 'p, B> {
/// Send addressed message to a peer.
fn send_message(&mut self, who: &PeerId, message: Vec<u8>) {
self.network
.write_notification(who.clone(), self.gossip.protocol.clone(), message);
self.network.write_notification(*who, self.gossip.protocol.clone(), message);
}
/// Send all messages with given topic to a peer.
@@ -116,13 +115,13 @@ where
for (message_hash, topic, message) in messages.clone() {
let intent = match intent {
MessageIntent::Broadcast { .. } =>
if peer.known_messages.contains(&message_hash) {
if peer.known_messages.contains(message_hash) {
continue
} else {
MessageIntent::Broadcast
},
MessageIntent::PeriodicRebroadcast => {
if peer.known_messages.contains(&message_hash) {
if peer.known_messages.contains(message_hash) {
MessageIntent::PeriodicRebroadcast
} else {
// peer doesn't know message, so the logic should treat it as an
@@ -133,11 +132,11 @@ where
other => other,
};
if !message_allowed(id, intent, &topic, &message) {
if !message_allowed(id, intent, topic, message) {
continue
}
peer.known_messages.insert(message_hash.clone());
peer.known_messages.insert(*message_hash);
tracing::trace!(
target: "gossip",
@@ -146,7 +145,7 @@ where
?message,
"Propagating message",
);
network.write_notification(id.clone(), protocol.clone(), message.clone());
network.write_notification(*id, protocol.clone(), message.clone());
}
}
}
@@ -198,8 +197,7 @@ impl<B: BlockT> ConsensusGossip<B> {
?role,
"Registering peer",
);
self.peers
.insert(who.clone(), PeerConsensus { known_messages: Default::default() });
self.peers.insert(who, PeerConsensus { known_messages: Default::default() });
let validator = self.validator.clone();
let mut context = NetworkContext { gossip: self, network };
@@ -213,7 +211,7 @@ impl<B: BlockT> ConsensusGossip<B> {
message: Vec<u8>,
sender: Option<PeerId>,
) {
if self.known_messages.put(message_hash.clone(), ()).is_none() {
if self.known_messages.put(message_hash, ()).is_none() {
self.messages.push(MessageEntry { message_hash, topic, message, sender });
if let Some(ref metrics) = self.metrics {
@@ -319,10 +317,7 @@ impl<B: BlockT> ConsensusGossip<B> {
self.messages
.iter()
.filter(move |e| e.topic == topic)
.map(|entry| TopicNotification {
message: entry.message.clone(),
sender: entry.sender.clone(),
})
.map(|entry| TopicNotification { message: entry.message.clone(), sender: entry.sender })
}
/// Register incoming messages and return the ones that are new and valid (according to a gossip
@@ -355,7 +350,7 @@ impl<B: BlockT> ConsensusGossip<B> {
protocol = %self.protocol,
"Ignored already known message",
);
network.report_peer(who.clone(), rep::DUPLICATE_GOSSIP);
network.report_peer(who, rep::DUPLICATE_GOSSIP);
continue
}
@@ -393,15 +388,13 @@ impl<B: BlockT> ConsensusGossip<B> {
},
};
network.report_peer(who.clone(), rep::GOSSIP_SUCCESS);
network.report_peer(who, rep::GOSSIP_SUCCESS);
peer.known_messages.insert(message_hash);
to_forward.push((
topic,
TopicNotification { message: message.clone(), sender: Some(who.clone()) },
));
to_forward
.push((topic, TopicNotification { message: message.clone(), sender: Some(who) }));
if keep {
self.register_message_hashed(message_hash, topic, message, Some(who.clone()));
self.register_message_hashed(message_hash, topic, message, Some(who));
}
}
@@ -431,7 +424,7 @@ impl<B: BlockT> ConsensusGossip<B> {
continue
}
peer.known_messages.insert(entry.message_hash.clone());
peer.known_messages.insert(entry.message_hash);
tracing::trace!(
target: "gossip",
@@ -440,11 +433,7 @@ impl<B: BlockT> ConsensusGossip<B> {
?entry.message,
"Sending topic message",
);
network.write_notification(
who.clone(),
self.protocol.clone(),
entry.message.clone(),
);
network.write_notification(*who, self.protocol.clone(), entry.message.clone());
}
}
}
@@ -489,7 +478,7 @@ impl<B: BlockT> ConsensusGossip<B> {
);
peer.known_messages.insert(message_hash);
network.write_notification(who.clone(), self.protocol.clone(), message);
network.write_notification(*who, self.protocol.clone(), message);
}
}
+1 -2
View File
@@ -434,7 +434,6 @@ where
"Trying to send warp sync request when no protocol is configured {:?}",
request,
);
return
},
},
CustomMessageOutcome::NotificationStreamOpened {
@@ -449,7 +448,7 @@ where
protocol,
negotiated_fallback,
role: reported_roles_to_observed_role(roles),
notifications_sink: notifications_sink.clone(),
notifications_sink,
});
},
CustomMessageOutcome::NotificationStreamReplaced {
+3 -3
View File
@@ -65,7 +65,7 @@ const MAX_RESPONSE_QUEUE: usize = 20;
// Max number of blocks per wantlist
const MAX_WANTED_BLOCKS: usize = 16;
const PROTOCOL_NAME: &'static [u8] = b"/ipfs/bitswap/1.2.0";
const PROTOCOL_NAME: &[u8] = b"/ipfs/bitswap/1.2.0";
type FutureResult<T, E> = Pin<Box<dyn Future<Output = Result<T, E>> + Send>>;
@@ -167,10 +167,10 @@ impl Prefix {
let version = varint_encode::u64(self.version.into(), &mut buf);
res.extend_from_slice(version);
let mut buf = varint_encode::u64_buffer();
let codec = varint_encode::u64(self.codec.into(), &mut buf);
let codec = varint_encode::u64(self.codec, &mut buf);
res.extend_from_slice(codec);
let mut buf = varint_encode::u64_buffer();
let mh_type = varint_encode::u64(self.mh_type.into(), &mut buf);
let mh_type = varint_encode::u64(self.mh_type, &mut buf);
res.extend_from_slice(mh_type);
let mut buf = varint_encode::u64_buffer();
let mh_len = varint_encode::u64(self.mh_len as u64, &mut buf);
@@ -197,7 +197,7 @@ where
peer: *peer,
max_blocks,
direction,
from: from_block_id.clone(),
from: from_block_id,
attributes,
support_multiple_justifications,
};
+8 -8
View File
@@ -287,7 +287,7 @@ impl DiscoveryBehaviour {
for b in k.kbuckets() {
for e in b.iter() {
if !peers.contains(e.node.key.preimage()) {
peers.insert(e.node.key.preimage().clone());
peers.insert(*e.node.key.preimage());
}
}
}
@@ -307,7 +307,7 @@ impl DiscoveryBehaviour {
k.add_address(&peer_id, addr.clone());
}
self.pending_events.push_back(DiscoveryOut::Discovered(peer_id.clone()));
self.pending_events.push_back(DiscoveryOut::Discovered(peer_id));
addrs_list.push(addr);
}
}
@@ -718,7 +718,7 @@ impl NetworkBehaviour for DiscoveryBehaviour {
// Poll the stream that fires when we need to start a random Kademlia query.
if let Some(next_kad_random_query) = self.next_kad_random_query.as_mut() {
while let Poll::Ready(_) = next_kad_random_query.poll_unpin(cx) {
while next_kad_random_query.poll_unpin(cx).is_ready() {
let actually_started = if self.num_connections < self.discovery_only_if_under_num {
let random_peer_id = PeerId::random();
debug!(
@@ -815,7 +815,7 @@ impl NetworkBehaviour for DiscoveryBehaviour {
DiscoveryOut::ValueFound(
results,
stats.duration().unwrap_or_else(Default::default),
stats.duration().unwrap_or_default(),
)
},
Err(e @ libp2p::kad::GetRecordError::NotFound { .. }) => {
@@ -826,7 +826,7 @@ impl NetworkBehaviour for DiscoveryBehaviour {
);
DiscoveryOut::ValueNotFound(
e.into_key(),
stats.duration().unwrap_or_else(Default::default),
stats.duration().unwrap_or_default(),
)
},
Err(e) => {
@@ -837,7 +837,7 @@ impl NetworkBehaviour for DiscoveryBehaviour {
);
DiscoveryOut::ValueNotFound(
e.into_key(),
stats.duration().unwrap_or_else(Default::default),
stats.duration().unwrap_or_default(),
)
},
};
@@ -851,7 +851,7 @@ impl NetworkBehaviour for DiscoveryBehaviour {
let ev = match res {
Ok(ok) => DiscoveryOut::ValuePut(
ok.key,
stats.duration().unwrap_or_else(Default::default),
stats.duration().unwrap_or_default(),
),
Err(e) => {
debug!(
@@ -861,7 +861,7 @@ impl NetworkBehaviour for DiscoveryBehaviour {
);
DiscoveryOut::ValuePutFailed(
e.into_key(),
stats.duration().unwrap_or_else(Default::default),
stats.duration().unwrap_or_default(),
)
},
};
@@ -27,11 +27,7 @@ use std::time::Duration;
/// Generate the light client protocol name from chain specific protocol identifier.
fn generate_protocol_name(protocol_id: &ProtocolId) -> String {
let mut s = String::new();
s.push_str("/");
s.push_str(protocol_id.as_ref());
s.push_str("/light/2");
s
format!("/{}/light/2", protocol_id.as_ref())
}
/// Generates a [`ProtocolConfig`] for the light client request protocol, refusing incoming
+9 -14
View File
@@ -391,13 +391,8 @@ where
sc_peerset::Peerset::from_config(sc_peerset::PeersetConfig { sets })
};
let block_announces_protocol: Cow<'static, str> = Cow::from({
let mut proto = String::new();
proto.push_str("/");
proto.push_str(protocol_id.as_ref());
proto.push_str("/block-announces/1");
proto
});
let block_announces_protocol: Cow<'static, str> =
format!("/{}/block-announces/1", protocol_id.as_ref()).into();
let behaviour = {
let best_number = info.best_number;
@@ -952,7 +947,7 @@ where
},
};
peer.known_blocks.insert(hash.clone());
peer.known_blocks.insert(hash);
let is_best = match announce.state.unwrap_or(message::BlockState::Best) {
message::BlockState::Best => true,
@@ -1062,7 +1057,7 @@ where
/// Uses `protocol` to queue a new justification request and tries to dispatch all pending
/// requests.
pub fn request_justification(&mut self, hash: &B::Hash, number: NumberFor<B>) {
self.sync.request_justification(&hash, number)
self.sync.request_justification(hash, number)
}
/// Clear all pending justification requests.
@@ -1479,7 +1474,7 @@ where
},
};
finished_block_requests.push((id.clone(), req, protobuf_response));
finished_block_requests.push((*id, req, protobuf_response));
},
PeerRequest::State => {
let protobuf_response =
@@ -1576,7 +1571,7 @@ where
}
for (id, request) in self.sync.block_requests() {
let event = prepare_block_request(&mut self.peers, id.clone(), request);
let event = prepare_block_request(&mut self.peers, *id, request);
self.pending_messages.push_back(event);
}
if let Some((id, request)) = self.sync.state_request() {
@@ -1727,9 +1722,9 @@ where
}
},
NotificationsOut::CustomProtocolReplaced { peer_id, notifications_sink, set_id } =>
if set_id == HARDCODED_PEERSETS_SYNC {
CustomMessageOutcome::None
} else if self.bad_handshake_substreams.contains(&(peer_id, set_id)) {
if set_id == HARDCODED_PEERSETS_SYNC ||
self.bad_handshake_substreams.contains(&(peer_id, set_id))
{
CustomMessageOutcome::None
} else {
CustomMessageOutcome::NotificationStreamReplaced {
@@ -154,7 +154,7 @@ impl<H: HeaderT> generic::BlockAnnounce<H> {
AnnouncementSummary {
block_hash: self.header.hash(),
number: *self.header.number(),
parent_hash: self.header.parent_hash().clone(),
parent_hash: *self.header.parent_hash(),
state: self.state,
}
}
@@ -402,7 +402,7 @@ impl Notifications {
}
/// Returns the list of all the peers we have an open channel to.
pub fn open_peers<'a>(&'a self) -> impl Iterator<Item = &'a PeerId> + 'a {
pub fn open_peers(&self) -> impl Iterator<Item = &PeerId> {
self.peers.iter().filter(|(_, state)| state.is_open()).map(|((id, _), _)| id)
}
@@ -551,10 +551,7 @@ impl Notifications {
}
/// Returns the list of reserved peers.
pub fn reserved_peers<'a>(
&'a self,
set_id: sc_peerset::SetId,
) -> impl Iterator<Item = &'a PeerId> + 'a {
pub fn reserved_peers(&self, set_id: sc_peerset::SetId) -> impl Iterator<Item = &PeerId> {
self.peerset.reserved_peers(set_id)
}
@@ -621,7 +618,7 @@ impl Notifications {
);
trace!(target: "sub-libp2p", "Libp2p <= Dial {}", entry.key().0);
self.events.push_back(NetworkBehaviourAction::Dial {
opts: entry.key().0.clone().into(),
opts: entry.key().0.into(),
handler,
});
entry.insert(PeerState::Requested);
@@ -634,7 +631,7 @@ impl Notifications {
match mem::replace(occ_entry.get_mut(), PeerState::Poisoned) {
// Backoff (not expired) => PendingRequest
PeerState::Backoff { ref timer, ref timer_deadline } if *timer_deadline > now => {
let peer_id = occ_entry.key().0.clone();
let peer_id = occ_entry.key().0;
trace!(
target: "sub-libp2p",
"PSM => Connect({}, {:?}): Will start to connect at until {:?}",
@@ -656,7 +653,7 @@ impl Notifications {
);
trace!(target: "sub-libp2p", "Libp2p <= Dial {:?}", occ_entry.key());
self.events.push_back(NetworkBehaviourAction::Dial {
opts: occ_entry.key().0.clone().into(),
opts: occ_entry.key().0.into(),
handler,
});
*occ_entry.into_mut() = PeerState::Requested;
@@ -666,7 +663,7 @@ impl Notifications {
PeerState::Disabled { connections, backoff_until: Some(ref backoff) }
if *backoff > now =>
{
let peer_id = occ_entry.key().0.clone();
let peer_id = occ_entry.key().0;
trace!(
target: "sub-libp2p",
"PSM => Connect({}, {:?}): But peer is backed-off until {:?}",
@@ -781,7 +778,7 @@ impl Notifications {
trace!(target: "sub-libp2p", "Handler({:?}, {:?}) <= Open({:?})",
occ_entry.key(), *connec_id, set_id);
self.events.push_back(NetworkBehaviourAction::NotifyHandler {
peer_id: occ_entry.key().0.clone(),
peer_id: occ_entry.key().0,
handler: NotifyHandler::One(*connec_id),
event: NotifsHandlerIn::Open { protocol_index: set_id.into() },
});
@@ -861,10 +858,8 @@ impl Notifications {
if connections.iter().any(|(_, s)| matches!(s, ConnectionState::Open(_))) {
trace!(target: "sub-libp2p", "External API <= Closed({}, {:?})", entry.key().0, set_id);
let event = NotificationsOut::CustomProtocolClosed {
peer_id: entry.key().0.clone(),
set_id,
};
let event =
NotificationsOut::CustomProtocolClosed { peer_id: entry.key().0, set_id };
self.events.push_back(NetworkBehaviourAction::GenerateEvent(event));
}
@@ -874,7 +869,7 @@ impl Notifications {
trace!(target: "sub-libp2p", "Handler({:?}, {:?}) <= Close({:?})",
entry.key(), *connec_id, set_id);
self.events.push_back(NetworkBehaviourAction::NotifyHandler {
peer_id: entry.key().0.clone(),
peer_id: entry.key().0,
handler: NotifyHandler::One(*connec_id),
event: NotifsHandlerIn::Close { protocol_index: set_id.into() },
});
@@ -887,7 +882,7 @@ impl Notifications {
trace!(target: "sub-libp2p", "Handler({:?}, {:?}) <= Close({:?})",
entry.key(), *connec_id, set_id);
self.events.push_back(NetworkBehaviourAction::NotifyHandler {
peer_id: entry.key().0.clone(),
peer_id: entry.key().0,
handler: NotifyHandler::One(*connec_id),
event: NotifsHandlerIn::Close { protocol_index: set_id.into() },
});
@@ -1406,7 +1401,7 @@ impl NetworkBehaviour for Notifications {
trace!(target: "sub-libp2p", "Libp2p => Dial failure for {:?}", peer_id);
for set_id in (0..self.notif_protocols.len()).map(sc_peerset::SetId::from) {
if let Entry::Occupied(mut entry) = self.peers.entry((peer_id.clone(), set_id)) {
if let Entry::Occupied(mut entry) = self.peers.entry((peer_id, set_id)) {
match mem::replace(entry.get_mut(), PeerState::Poisoned) {
// The peer is not in our list.
st @ PeerState::Backoff { .. } => {
@@ -1646,7 +1641,6 @@ impl NetworkBehaviour for Notifications {
"OpenDesiredByRemote: Unexpected state in the custom protos handler: {:?}",
state);
debug_assert!(false);
return
},
};
},
@@ -1742,13 +1736,11 @@ impl NetworkBehaviour for Notifications {
state @ PeerState::Disabled { .. } |
state @ PeerState::DisabledPendingEnable { .. } => {
*entry.into_mut() = state;
return
},
state => {
error!(target: "sub-libp2p",
"Unexpected state in the custom protos handler: {:?}",
state);
return
},
}
},
@@ -1853,7 +1845,6 @@ impl NetworkBehaviour for Notifications {
"OpenResultOk: Unexpected state in the custom protos handler: {:?}",
state);
debug_assert!(false);
return
},
}
},
@@ -2052,9 +2043,7 @@ impl NetworkBehaviour for Notifications {
event: NotifsHandlerIn::Open { protocol_index: set_id.into() },
});
*connec_state = ConnectionState::Opening;
*peer_state = PeerState::Enabled {
connections: mem::replace(connections, Default::default()),
};
*peer_state = PeerState::Enabled { connections: mem::take(connections) };
} else {
*timer_deadline = Instant::now() + Duration::from_secs(5);
let delay = futures_timer::Delay::new(Duration::from_secs(5));
@@ -400,7 +400,7 @@ impl NotificationsSink {
/// error to send a notification using an unknown protocol.
///
/// This method will be removed in a future version.
pub fn send_sync_notification<'a>(&'a self, message: impl Into<Vec<u8>>) {
pub fn send_sync_notification(&self, message: impl Into<Vec<u8>>) {
let mut lock = self.inner.sync_channel.lock();
if let Some(tx) = lock.as_mut() {
@@ -425,7 +425,7 @@ impl NotificationsSink {
///
/// The protocol name is expected to be checked ahead of calling this method. It is a logic
/// error to send a notification using an unknown protocol.
pub async fn reserve_notification<'a>(&'a self) -> Result<Ready<'a>, ()> {
pub async fn reserve_notification(&self) -> Result<Ready<'_>, ()> {
let mut lock = self.inner.async_channel.lock().await;
let poll_ready = future::poll_fn(|cx| lock.poll_ready(cx)).await;
+61 -62
View File
@@ -672,7 +672,7 @@ where
self.best_queued_number
);
self.peers.insert(
who.clone(),
who,
PeerSync {
peer_id: who,
common_number: self.best_queued_number,
@@ -796,7 +796,7 @@ where
.iter()
// Only request blocks from peers who are ahead or on a par.
.filter(|(_, peer)| peer.best_number >= number)
.map(|(id, _)| id.clone())
.map(|(id, _)| *id)
.collect();
debug!(
@@ -809,7 +809,7 @@ where
debug!(target: "sync", "Explicit sync request for block {:?} with {:?}", hash, peers);
}
if self.is_known(&hash) {
if self.is_known(hash) {
debug!(target: "sync", "Refusing to sync known hash {:?}", hash);
return
}
@@ -843,7 +843,7 @@ where
let peers = &mut self.peers;
let mut matcher = self.extra_justifications.matcher();
std::iter::from_fn(move || {
if let Some((peer, request)) = matcher.next(&peers) {
if let Some((peer, request)) = matcher.next(peers) {
peers
.get_mut(&peer)
.expect(
@@ -1087,7 +1087,7 @@ where
if let Some(start_block) =
validate_blocks::<B>(&blocks, who, Some(request))?
{
self.blocks.insert(start_block, blocks, who.clone());
self.blocks.insert(start_block, blocks, *who);
}
self.drain_blocks()
},
@@ -1098,7 +1098,7 @@ where
if let Some(start_block) =
validate_blocks::<B>(&blocks, who, Some(request))?
{
gap_sync.blocks.insert(start_block, blocks, who.clone());
gap_sync.blocks.insert(start_block, blocks, *who);
}
gap = true;
let blocks: Vec<_> = gap_sync
@@ -1106,11 +1106,12 @@ where
.drain(gap_sync.best_queued_number + One::one())
.into_iter()
.map(|block_data| {
let justifications = block_data.block.justifications.or(
legacy_justification_mapping(
block_data.block.justification,
),
);
let justifications =
block_data.block.justifications.or_else(|| {
legacy_justification_mapping(
block_data.block.justification,
)
});
IncomingBlock {
hash: block_data.block.hash,
header: block_data.block.header,
@@ -1129,7 +1130,7 @@ where
blocks
} else {
debug!(target: "sync", "Unexpected gap block response from {}", who);
return Err(BadPeer(who.clone(), rep::NO_BLOCK))
return Err(BadPeer(*who, rep::NO_BLOCK))
}
},
PeerSyncState::DownloadingStale(_) => {
@@ -1144,7 +1145,7 @@ where
.map(|b| {
let justifications = b
.justifications
.or(legacy_justification_mapping(b.justification));
.or_else(|| legacy_justification_mapping(b.justification));
IncomingBlock {
hash: b.hash,
header: b.header,
@@ -1261,8 +1262,9 @@ where
blocks
.into_iter()
.map(|b| {
let justifications =
b.justifications.or(legacy_justification_mapping(b.justification));
let justifications = b
.justifications
.or_else(|| legacy_justification_mapping(b.justification));
IncomingBlock {
hash: b.hash,
header: b.header,
@@ -1294,7 +1296,7 @@ where
who: &PeerId,
response: StateResponse,
) -> Result<OnStateData<B>, BadPeer> {
if let Some(peer) = self.peers.get_mut(&who) {
if let Some(peer) = self.peers.get_mut(who) {
if let PeerSyncState::DownloadingState = peer.state {
peer.state = PeerSyncState::Available;
self.allowed_requests.set_all();
@@ -1357,7 +1359,7 @@ where
who: &PeerId,
response: warp::EncodedProof,
) -> Result<(), BadPeer> {
if let Some(peer) = self.peers.get_mut(&who) {
if let Some(peer) = self.peers.get_mut(who) {
if let PeerSyncState::DownloadingWarpProof = peer.state {
peer.state = PeerSyncState::Available;
self.allowed_requests.set_all();
@@ -1458,7 +1460,9 @@ where
return Err(BadPeer(who, rep::BAD_JUSTIFICATION))
}
block.justifications.or(legacy_justification_mapping(block.justification))
block
.justifications
.or_else(|| legacy_justification_mapping(block.justification))
} else {
// we might have asked the peer for a justification on a block that we assumed it
// had but didn't (regardless of whether it had a justification for it or not).
@@ -1488,19 +1492,19 @@ where
/// queue, with or without errors.
///
/// `peer_info` is passed in case of a restart.
pub fn on_blocks_processed<'a>(
&'a mut self,
pub fn on_blocks_processed(
&mut self,
imported: usize,
count: usize,
results: Vec<(Result<BlockImportStatus<NumberFor<B>>, BlockImportError>, B::Hash)>,
) -> impl Iterator<Item = Result<(PeerId, BlockRequest<B>), BadPeer>> + 'a {
) -> impl Iterator<Item = Result<(PeerId, BlockRequest<B>), BadPeer>> {
trace!(target: "sync", "Imported {} of {}", imported, count);
let mut output = Vec::new();
let mut has_error = false;
for (_, hash) in &results {
self.queue_blocks.remove(&hash);
self.queue_blocks.remove(hash);
}
for (result, hash) in results {
if has_error {
@@ -1659,7 +1663,7 @@ where
heads.sort();
let median = heads[heads.len() / 2];
if number + STATE_SYNC_FINALITY_THRESHOLD.saturated_into() >= median {
if let Ok(Some(header)) = self.client.header(BlockId::hash(hash.clone())) {
if let Ok(Some(header)) = self.client.header(BlockId::hash(*hash)) {
log::debug!(
target: "sync",
"Starting state sync for #{} ({})",
@@ -1688,7 +1692,7 @@ where
/// Updates our internal state for best queued block and then goes
/// through all peers to update our view of their state as well.
fn on_block_queued(&mut self, hash: &B::Hash, number: NumberFor<B>) {
if self.fork_targets.remove(&hash).is_some() {
if self.fork_targets.remove(hash).is_some() {
trace!(target: "sync", "Completed fork sync {:?}", hash);
}
if let Some(gap_sync) = &mut self.gap_sync {
@@ -1741,7 +1745,7 @@ where
return HasSlotForBlockAnnounceValidation::TotalMaximumSlotsReached
}
match self.block_announce_validation_per_peer_stats.entry(peer.clone()) {
match self.block_announce_validation_per_peer_stats.entry(*peer) {
Entry::Vacant(entry) => {
entry.insert(1);
HasSlotForBlockAnnounceValidation::Yes
@@ -1830,8 +1834,7 @@ where
// Let external validator check the block announcement.
let assoc_data = announce.data.as_ref().map_or(&[][..], |v| v.as_slice());
let future = self.block_announce_validator.validate(&header, assoc_data);
let hash = hash.clone();
let future = self.block_announce_validator.validate(header, assoc_data);
self.block_announce_validation.push(
async move {
@@ -1900,7 +1903,7 @@ where
PreValidateBlockAnnounce::Skip => return,
};
match self.block_announce_validation_per_peer_stats.entry(peer.clone()) {
match self.block_announce_validation_per_peer_stats.entry(*peer) {
Entry::Vacant(_) => {
error!(
target: "sync",
@@ -1994,7 +1997,7 @@ where
if known || self.is_already_downloading(&hash) {
trace!(target: "sync", "Known block announce from {}: {}", who, hash);
if let Some(target) = self.fork_targets.get_mut(&hash) {
target.peers.insert(who.clone());
target.peers.insert(who);
}
return PollBlockAnnounceValidation::Nothing { is_best, who, announce }
}
@@ -2070,9 +2073,7 @@ where
/// Restart the sync process. This will reset all pending block requests and return an iterator
/// of new block requests to make to peers. Peers that were downloading finality data (i.e.
/// their state was `DownloadingJustification`) are unaffected and will stay in the same state.
fn restart<'a>(
&'a mut self,
) -> impl Iterator<Item = Result<(PeerId, BlockRequest<B>), BadPeer>> + 'a {
fn restart(&mut self) -> impl Iterator<Item = Result<(PeerId, BlockRequest<B>), BadPeer>> + '_ {
self.blocks.clear();
if let Err(e) = self.reset_sync_start_point() {
warn!(target: "sync", "💔 Unable to restart sync: {}", e);
@@ -2084,18 +2085,15 @@ where
old_peers.into_iter().filter_map(move |(id, mut p)| {
// peers that were downloading justifications
// should be kept in that state.
match p.state {
PeerSyncState::DownloadingJustification(_) => {
// We make sure our commmon number is at least something we have.
p.common_number = self.best_queued_number;
self.peers.insert(id, p);
return None
},
_ => {},
if let PeerSyncState::DownloadingJustification(_) = p.state {
// We make sure our commmon number is at least something we have.
p.common_number = self.best_queued_number;
self.peers.insert(id, p);
return None
}
// handle peers that were in other states.
match self.new_peer(id.clone(), p.best_hash, p.best_number) {
match self.new_peer(id, p.best_hash, p.best_number) {
Ok(None) => None,
Ok(Some(x)) => Some(Ok((id, x))),
Err(e) => Some(Err(e)),
@@ -2124,23 +2122,24 @@ where
self.import_existing = false;
self.best_queued_hash = info.best_hash;
self.best_queued_number = info.best_number;
if self.mode == SyncMode::Full {
if self.client.block_status(&BlockId::hash(info.best_hash))? !=
if self.mode == SyncMode::Full &&
self.client.block_status(&BlockId::hash(info.best_hash))? !=
BlockStatus::InChainWithState
{
self.import_existing = true;
// Latest state is missing, start with the last finalized state or genesis instead.
if let Some((hash, number)) = info.finalized_state {
debug!(target: "sync", "Starting from finalized state #{}", number);
self.best_queued_hash = hash;
self.best_queued_number = number;
} else {
debug!(target: "sync", "Restarting from genesis");
self.best_queued_hash = Default::default();
self.best_queued_number = Zero::zero();
}
{
self.import_existing = true;
// Latest state is missing, start with the last finalized state or genesis instead.
if let Some((hash, number)) = info.finalized_state {
debug!(target: "sync", "Starting from finalized state #{}", number);
self.best_queued_hash = hash;
self.best_queued_number = number;
} else {
debug!(target: "sync", "Restarting from genesis");
self.best_queued_hash = Default::default();
self.best_queued_number = Zero::zero();
}
}
if let Some((start, end)) = info.block_gap {
debug!(target: "sync", "Starting gap sync #{} - #{}", start, end);
self.gap_sync = Some(GapSync {
@@ -2192,7 +2191,7 @@ where
let justifications = block_data
.block
.justifications
.or(legacy_justification_mapping(block_data.block.justification));
.or_else(|| legacy_justification_mapping(block_data.block.justification));
IncomingBlock {
hash: block_data.block.hash,
header: block_data.block.header,
@@ -2349,7 +2348,7 @@ fn peer_block_request<B: BlockT>(
let request = message::generic::BlockRequest {
id: 0,
fields: attrs.clone(),
fields: attrs,
from,
to: None,
direction: message::Direction::Descending,
@@ -2369,7 +2368,7 @@ fn peer_gap_block_request<B: BlockT>(
common_number: NumberFor<B>,
) -> Option<(Range<NumberFor<B>>, BlockRequest<B>)> {
let range = blocks.needed_blocks(
id.clone(),
*id,
MAX_BLOCKS_TO_REQUEST,
std::cmp::min(peer.best_number, target),
common_number,
@@ -2383,7 +2382,7 @@ fn peer_gap_block_request<B: BlockT>(
let request = message::generic::BlockRequest {
id: 0,
fields: attrs.clone(),
fields: attrs,
from,
to: None,
direction: message::Direction::Descending,
@@ -2430,11 +2429,11 @@ fn fork_sync_request<B: BlockT>(
};
trace!(target: "sync", "Downloading requested fork {:?} from {}, {} blocks", hash, id, count);
return Some((
hash.clone(),
*hash,
message::generic::BlockRequest {
id: 0,
fields: attributes.clone(),
from: message::FromBlock::Hash(hash.clone()),
fields: attributes,
from: message::FromBlock::Hash(*hash),
to: None,
direction: message::Direction::Descending,
max: Some(count),
@@ -327,7 +327,7 @@ impl<'a, B: BlockT> Matcher<'a, B> {
{
continue
}
self.extras.active_requests.insert(peer.clone(), request);
self.extras.active_requests.insert(*peer, request);
trace!(target: "sync",
"Sending {} request to {:?} for {:?}",
@@ -71,7 +71,7 @@ where
Self {
client,
target_block: target.hash(),
target_root: target.state_root().clone(),
target_root: *target.state_root(),
target_header: target,
last_key: SmallVec::default(),
state: HashMap::default(),
@@ -149,18 +149,16 @@ where
if entry.0.len() > 0 && entry.1.len() > 1 {
// Already imported child_trie with same root.
// Warning this will not work with parallel download.
} else {
if entry.0.is_empty() {
for (key, _value) in key_values.iter() {
self.imported_bytes += key.len() as u64;
}
} else if entry.0.is_empty() {
for (key, _value) in key_values.iter() {
self.imported_bytes += key.len() as u64;
}
entry.0 = key_values;
} else {
for (key, value) in key_values {
self.imported_bytes += key.len() as u64;
entry.0.push((key, value))
}
entry.0 = key_values;
} else {
for (key, value) in key_values {
self.imported_bytes += key.len() as u64;
entry.0.push((key, value))
}
}
}
@@ -172,7 +170,7 @@ where
// the parent cursor stays valid.
// Empty parent trie content only happens when all the response content
// is part of a single child trie.
if self.last_key.len() == 2 && response.entries[0].entries.len() == 0 {
if self.last_key.len() == 2 && response.entries[0].entries.is_empty() {
// Do not remove the parent trie position.
self.last_key.pop();
} else {
@@ -220,7 +218,7 @@ where
self.target_block,
self.target_header.clone(),
ImportedState {
block: self.target_block.clone(),
block: self.target_block,
state: std::mem::take(&mut self.state).into(),
},
)
@@ -94,7 +94,7 @@ where
match &mut self.phase {
Phase::WarpProof { .. } => {
log::debug!(target: "sync", "Unexpected state response");
return ImportResult::BadResponse
ImportResult::BadResponse
},
Phase::State(sync) => sync.import(response),
}
@@ -111,13 +111,13 @@ where
match self.warp_sync_provider.verify(&response, *set_id, authorities.clone()) {
Err(e) => {
log::debug!(target: "sync", "Bad warp proof response: {}", e);
return WarpProofImportResult::BadResponse
WarpProofImportResult::BadResponse
},
Ok(VerificationResult::Partial(new_set_id, new_authorities, new_last_hash)) => {
log::debug!(target: "sync", "Verified partial proof, set_id={:?}", new_set_id);
*set_id = new_set_id;
*authorities = new_authorities;
*last_hash = new_last_hash.clone();
*last_hash = new_last_hash;
self.total_proof_bytes += response.0.len() as u64;
WarpProofImportResult::Success
},
@@ -355,25 +355,21 @@ impl RequestResponsesBehaviour {
(Instant::now(), pending_response),
);
debug_assert!(prev_req_id.is_none(), "Expect request id to be unique.");
} else {
if pending_response.send(Err(RequestFailure::NotConnected)).is_err() {
log::debug!(
target: "sub-libp2p",
"Not connected to peer {:?}. At the same time local \
node is no longer interested in the result.",
target,
);
};
}
} else {
if pending_response.send(Err(RequestFailure::UnknownProtocol)).is_err() {
} else if pending_response.send(Err(RequestFailure::NotConnected)).is_err() {
log::debug!(
target: "sub-libp2p",
"Unknown protocol {:?}. At the same time local \
"Not connected to peer {:?}. At the same time local \
node is no longer interested in the result.",
protocol_name,
target,
);
};
}
} else if pending_response.send(Err(RequestFailure::UnknownProtocol)).is_err() {
log::debug!(
target: "sub-libp2p",
"Unknown protocol {:?}. At the same time local \
node is no longer interested in the result.",
protocol_name,
);
}
}
@@ -599,7 +595,7 @@ impl NetworkBehaviour for RequestResponsesBehaviour {
// will be reported by the corresponding `RequestResponse` through
// an `InboundFailure::Omission` event.
let _ = resp_builder.try_send(IncomingRequest {
peer: peer.clone(),
peer,
payload: request,
pending_response: tx,
});
@@ -648,7 +644,7 @@ impl NetworkBehaviour for RequestResponsesBehaviour {
if let Ok(payload) = result {
if let Some((protocol, _)) = self.protocols.get_mut(&*protocol_name) {
if let Err(_) = protocol.send_response(inner_channel, Ok(payload)) {
if protocol.send_response(inner_channel, Ok(payload)).is_err() {
// Note: Failure is handled further below when receiving
// `InboundFailure` event from `RequestResponse` behaviour.
log::debug!(
@@ -658,11 +654,9 @@ impl NetworkBehaviour for RequestResponsesBehaviour {
Dropping response",
request_id, protocol_name,
);
} else {
if let Some(sent_feedback) = sent_feedback {
self.send_feedback
.insert((protocol_name, request_id).into(), sent_feedback);
}
} else if let Some(sent_feedback) = sent_feedback {
self.send_feedback
.insert((protocol_name, request_id).into(), sent_feedback);
}
}
}
@@ -718,13 +712,10 @@ impl NetworkBehaviour for RequestResponsesBehaviour {
message:
RequestResponseMessage::Request { request_id, request, channel, .. },
} => {
self.pending_responses_arrival_time.insert(
(protocol.clone(), request_id.clone()).into(),
Instant::now(),
);
self.pending_responses_arrival_time
.insert((protocol.clone(), request_id).into(), Instant::now());
let get_peer_reputation =
self.peerset.clone().peer_reputation(peer.clone());
let get_peer_reputation = self.peerset.clone().peer_reputation(peer);
let get_peer_reputation = Box::pin(get_peer_reputation);
// Save the Future-like state with params to poll `get_peer_reputation`
+20 -28
View File
@@ -195,7 +195,7 @@ where
// Private and public keys configuration.
let local_identity = params.network_config.node_key.clone().into_keypair()?;
let local_public = local_identity.public();
let local_peer_id = local_public.clone().to_peer_id();
let local_peer_id = local_public.to_peer_id();
info!(
target: "sub-libp2p",
"🏷 Local node identity is: {}",
@@ -248,7 +248,7 @@ where
Err(Error::DuplicateBootnode {
address: addr.clone(),
first_id: *peer_id,
second_id: other.0.clone(),
second_id: other.0,
})
} else {
Ok(())
@@ -644,7 +644,7 @@ where
.collect()
};
let peer_id = Swarm::<Behaviour<B, Client>>::local_peer_id(&swarm).to_base58();
let peer_id = Swarm::<Behaviour<B, Client>>::local_peer_id(swarm).to_base58();
let listened_addresses = swarm.listeners().cloned().collect();
let external_addresses = swarm.external_addresses().map(|r| &r.addr).cloned().collect();
@@ -664,7 +664,7 @@ where
.behaviour_mut()
.user_protocol_mut()
.peers_info()
.map(|(id, info)| (id.clone(), info.clone()))
.map(|(id, info)| (*id, info.clone()))
.collect()
}
@@ -753,7 +753,7 @@ impl<B: BlockT + 'static, H: ExHashT> NetworkService<B, H> {
// `peers_notifications_sinks` mutex as soon as possible.
let sink = {
let peers_notifications_sinks = self.peers_notifications_sinks.lock();
if let Some(sink) = peers_notifications_sinks.get(&(target.clone(), protocol.clone())) {
if let Some(sink) = peers_notifications_sinks.get(&(target, protocol.clone())) {
sink.clone()
} else {
// Notification silently discarded, as documented.
@@ -1093,7 +1093,7 @@ impl<B: BlockT + 'static, H: ExHashT> NetworkService<B, H> {
let _ = self
.to_worker
.unbounded_send(ServiceToWorkerMsg::AddKnownAddress(peer_id.clone(), addr));
.unbounded_send(ServiceToWorkerMsg::AddKnownAddress(peer_id, addr));
let _ = self.to_worker.unbounded_send(ServiceToWorkerMsg::AddReserved(peer_id));
Ok(())
}
@@ -1173,7 +1173,7 @@ impl<B: BlockT + 'static, H: ExHashT> NetworkService<B, H> {
if !addr.is_empty() {
let _ = self
.to_worker
.unbounded_send(ServiceToWorkerMsg::AddKnownAddress(peer_id.clone(), addr));
.unbounded_send(ServiceToWorkerMsg::AddKnownAddress(peer_id, addr));
}
let _ = self
.to_worker
@@ -1227,7 +1227,7 @@ impl<B: BlockT + 'static, H: ExHashT> NetworkService<B, H> {
if !addr.is_empty() {
let _ = self
.to_worker
.unbounded_send(ServiceToWorkerMsg::AddKnownAddress(peer_id.clone(), addr));
.unbounded_send(ServiceToWorkerMsg::AddKnownAddress(peer_id, addr));
}
let _ = self
.to_worker
@@ -1351,9 +1351,7 @@ pub struct NotificationSender {
impl NotificationSender {
/// Returns a future that resolves when the `NotificationSender` is ready to send a
/// notification.
pub async fn ready<'a>(
&'a self,
) -> Result<NotificationSenderReady<'a>, NotificationSenderError> {
pub async fn ready(&self) -> Result<NotificationSenderReady<'_>, NotificationSenderError> {
Ok(NotificationSenderReady {
ready: match self.sink.reserve_notification().await {
Ok(r) => r,
@@ -1771,7 +1769,7 @@ where
if let Some(metrics) = this.metrics.as_ref() {
metrics
.kademlia_random_queries_total
.with_label_values(&[&protocol.as_ref()])
.with_label_values(&[protocol.as_ref()])
.inc();
},
Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::NotificationStreamOpened {
@@ -1790,7 +1788,7 @@ where
{
let mut peers_notifications_sinks = this.peers_notifications_sinks.lock();
let _previous_value = peers_notifications_sinks
.insert((remote.clone(), protocol.clone()), notifications_sink);
.insert((remote, protocol.clone()), notifications_sink);
debug_assert!(_previous_value.is_none());
}
this.event_streams.send(Event::NotificationStreamOpened {
@@ -1848,13 +1846,12 @@ where
.inc();
}
this.event_streams.send(Event::NotificationStreamClosed {
remote: remote.clone(),
remote,
protocol: protocol.clone(),
});
{
let mut peers_notifications_sinks = this.peers_notifications_sinks.lock();
let _previous_value =
peers_notifications_sinks.remove(&(remote.clone(), protocol));
let _previous_value = peers_notifications_sinks.remove(&(remote, protocol));
debug_assert!(_previous_value.is_some());
}
},
@@ -2117,10 +2114,7 @@ where
for (lower_ilog2_bucket_bound, num_entries) in buckets {
metrics
.kbuckets_num_nodes
.with_label_values(&[
&proto.as_ref(),
&lower_ilog2_bucket_bound.to_string(),
])
.with_label_values(&[proto.as_ref(), &lower_ilog2_bucket_bound.to_string()])
.set(num_entries as u64);
}
}
@@ -2128,7 +2122,7 @@ where
{
metrics
.kademlia_records_count
.with_label_values(&[&proto.as_ref()])
.with_label_values(&[proto.as_ref()])
.set(num_entries as u64);
}
for (proto, num_entries) in
@@ -2136,7 +2130,7 @@ where
{
metrics
.kademlia_records_sizes_total
.with_label_values(&[&proto.as_ref()])
.with_label_values(&[proto.as_ref()])
.set(num_entries as u64);
}
metrics
@@ -2211,12 +2205,10 @@ where
number: NumberFor<B>,
success: bool,
) {
self.protocol.behaviour_mut().user_protocol_mut().justification_import_result(
who,
hash.clone(),
number,
success,
);
self.protocol
.behaviour_mut()
.user_protocol_mut()
.justification_import_result(who, *hash, number, success);
}
fn request_justification(&mut self, hash: &B::Hash, number: NumberFor<B>) {
self.protocol
@@ -280,8 +280,8 @@ impl MetricSource for BandwidthCounters {
type N = u64;
fn collect(&self, mut set: impl FnMut(&[&str], Self::N)) {
set(&[&"in"], self.0.total_inbound());
set(&[&"out"], self.0.total_outbound());
set(&["in"], self.0.total_inbound());
set(&["out"], self.0.total_outbound());
}
}
@@ -197,9 +197,9 @@ fn format_label(prefix: &str, protocol: &str, callback: impl FnOnce(&str)) {
label_buffer.clear();
label_buffer.reserve(prefix.len() + protocol.len() + 2);
label_buffer.push_str(prefix);
label_buffer.push_str("\"");
label_buffer.push('"');
label_buffer.push_str(protocol);
label_buffer.push_str("\"");
label_buffer.push('"');
callback(&label_buffer);
});
}
@@ -249,14 +249,14 @@ impl Metrics {
.inc_by(num);
},
Event::NotificationStreamOpened { protocol, .. } => {
format_label("notif-open-", &protocol, |protocol_label| {
format_label("notif-open-", protocol, |protocol_label| {
self.events_total
.with_label_values(&[protocol_label, "sent", name])
.inc_by(num);
});
},
Event::NotificationStreamClosed { protocol, .. } => {
format_label("notif-closed-", &protocol, |protocol_label| {
format_label("notif-closed-", protocol, |protocol_label| {
self.events_total
.with_label_values(&[protocol_label, "sent", name])
.inc_by(num);
@@ -264,7 +264,7 @@ impl Metrics {
},
Event::NotificationsReceived { messages, .. } =>
for (protocol, message) in messages {
format_label("notif-", &protocol, |protocol_label| {
format_label("notif-", protocol, |protocol_label| {
self.events_total
.with_label_values(&[protocol_label, "sent", name])
.inc_by(num);
@@ -290,24 +290,24 @@ impl Metrics {
.inc();
},
Event::NotificationStreamOpened { protocol, .. } => {
format_label("notif-open-", &protocol, |protocol_label| {
format_label("notif-open-", protocol, |protocol_label| {
self.events_total.with_label_values(&[protocol_label, "received", name]).inc();
});
},
Event::NotificationStreamClosed { protocol, .. } => {
format_label("notif-closed-", &protocol, |protocol_label| {
format_label("notif-closed-", protocol, |protocol_label| {
self.events_total.with_label_values(&[protocol_label, "received", name]).inc();
});
},
Event::NotificationsReceived { messages, .. } =>
for (protocol, message) in messages {
format_label("notif-", &protocol, |protocol_label| {
format_label("notif-", protocol, |protocol_label| {
self.events_total
.with_label_values(&[protocol_label, "received", name])
.inc();
});
self.notifications_sizes
.with_label_values(&[&protocol, "received", name])
.with_label_values(&[protocol, "received", name])
.inc_by(u64::try_from(message.len()).unwrap_or(u64::MAX));
},
}
@@ -63,11 +63,7 @@ pub fn generate_protocol_config(protocol_id: &ProtocolId) -> ProtocolConfig {
/// Generate the state protocol name from chain specific protocol identifier.
fn generate_protocol_name(protocol_id: &ProtocolId) -> String {
let mut s = String::new();
s.push_str("/");
s.push_str(protocol_id.as_ref());
s.push_str("/state/2");
s
format!("/{}/state/2", protocol_id.as_ref())
}
/// The key of [`BlockRequestHandler::seen_requests`].
@@ -152,8 +148,7 @@ where
let request = StateRequest::decode(&payload[..])?;
let block: B::Hash = Decode::decode(&mut request.block.as_ref())?;
let key =
SeenRequestsKey { peer: *peer, block: block.clone(), start: request.start.clone() };
let key = SeenRequestsKey { peer: *peer, block, start: request.start.clone() };
let mut reputation_changes = Vec::new();
+1 -9
View File
@@ -133,15 +133,7 @@ pub struct TransactionsHandlerPrototype {
impl TransactionsHandlerPrototype {
/// Create a new instance.
pub fn new(protocol_id: ProtocolId) -> Self {
Self {
protocol_name: Cow::from({
let mut proto = String::new();
proto.push_str("/");
proto.push_str(protocol_id.as_ref());
proto.push_str("/transactions/1");
proto
}),
}
Self { protocol_name: format!("/{}/transactions/1", protocol_id.as_ref()).into() }
}
/// Returns the configuration of the set to put in the network configuration.
+3 -3
View File
@@ -82,11 +82,11 @@ pub fn build_transport(
rare panic here is basically zero");
// Legacy noise configurations for backward compatibility.
let mut noise_legacy = noise::LegacyConfig::default();
noise_legacy.recv_legacy_handshake = true;
let noise_legacy =
noise::LegacyConfig { recv_legacy_handshake: true, ..Default::default() };
let mut xx_config = noise::NoiseConfig::xx(noise_keypair);
xx_config.set_legacy_config(noise_legacy.clone());
xx_config.set_legacy_config(noise_legacy);
xx_config.into_authenticated()
};

Some files were not shown because too many files have changed in this diff Show More