mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-06-11 17:41:08 +00:00
Improve overall performance (#6699)
* Improve overall performance * Clean up code Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com> * Remove needless :: Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com> * Remove needless :: Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com> Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>
This commit is contained in:
@@ -156,7 +156,7 @@ pub fn new_full(config: Configuration) -> Result<TaskManager, ServiceError> {
|
||||
// if the node isn't actively participating in consensus then it doesn't
|
||||
// need a keystore, regardless of which protocol we use below.
|
||||
let keystore = if role.is_authority() {
|
||||
Some(keystore.clone() as sp_core::traits::BareCryptoStorePtr)
|
||||
Some(keystore as sp_core::traits::BareCryptoStorePtr)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
@@ -182,11 +182,11 @@ pub fn new_full(config: Configuration) -> Result<TaskManager, ServiceError> {
|
||||
let grandpa_config = sc_finality_grandpa::GrandpaParams {
|
||||
config: grandpa_config,
|
||||
link: grandpa_link,
|
||||
network: network.clone(),
|
||||
inherent_data_providers: inherent_data_providers.clone(),
|
||||
network,
|
||||
inherent_data_providers,
|
||||
telemetry_on_connect: Some(telemetry_on_connect_sinks.on_connect_stream()),
|
||||
voting_rule: sc_finality_grandpa::VotingRulesBuilder::default().build(),
|
||||
prometheus_registry: prometheus_registry.clone(),
|
||||
prometheus_registry,
|
||||
shared_voter_state: SharedVoterState::empty(),
|
||||
};
|
||||
|
||||
@@ -200,7 +200,7 @@ pub fn new_full(config: Configuration) -> Result<TaskManager, ServiceError> {
|
||||
sc_finality_grandpa::setup_disabled_grandpa(
|
||||
client,
|
||||
&inherent_data_providers,
|
||||
network.clone(),
|
||||
network,
|
||||
)?;
|
||||
}
|
||||
|
||||
@@ -221,7 +221,7 @@ pub fn new_light(config: Configuration) -> Result<TaskManager, ServiceError> {
|
||||
|
||||
let pool_api = sc_transaction_pool::LightChainApi::new(
|
||||
builder.client().clone(),
|
||||
fetcher.clone(),
|
||||
fetcher,
|
||||
);
|
||||
let pool = Arc::new(sc_transaction_pool::BasicPool::new_light(
|
||||
builder.config().transaction_pool.clone(),
|
||||
|
||||
@@ -124,7 +124,6 @@ impl Clone for TempDatabase {
|
||||
.map(|f_result|
|
||||
f_result.expect("failed to read file in seed db")
|
||||
.path()
|
||||
.clone()
|
||||
).collect();
|
||||
fs_extra::copy_items(
|
||||
&self_db_files,
|
||||
|
||||
@@ -272,7 +272,7 @@ pub fn new_full_base(
|
||||
// if the node isn't actively participating in consensus then it doesn't
|
||||
// need a keystore, regardless of which protocol we use below.
|
||||
let keystore = if role.is_authority() {
|
||||
Some(keystore.clone() as BareCryptoStorePtr)
|
||||
Some(keystore as BareCryptoStorePtr)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
@@ -302,7 +302,7 @@ pub fn new_full_base(
|
||||
inherent_data_providers: inherent_data_providers.clone(),
|
||||
telemetry_on_connect: Some(telemetry_on_connect_sinks.on_connect_stream()),
|
||||
voting_rule: grandpa::VotingRulesBuilder::default().build(),
|
||||
prometheus_registry: prometheus_registry.clone(),
|
||||
prometheus_registry,
|
||||
shared_voter_state,
|
||||
};
|
||||
|
||||
@@ -403,7 +403,7 @@ pub fn new_light_base(config: Configuration) -> Result<(
|
||||
babe_block_import,
|
||||
None,
|
||||
Some(Box::new(finality_proof_import)),
|
||||
client.clone(),
|
||||
client,
|
||||
select_chain,
|
||||
inherent_data_providers.clone(),
|
||||
spawn_task_handle,
|
||||
|
||||
@@ -118,7 +118,6 @@ impl Clone for BenchDb {
|
||||
.map(|f_result|
|
||||
f_result.expect("failed to read file in seed db")
|
||||
.path()
|
||||
.clone()
|
||||
).collect();
|
||||
fs_extra::copy_items(
|
||||
&seed_db_files,
|
||||
|
||||
@@ -131,7 +131,7 @@ fn generate_chain_spec(
|
||||
Default::default(),
|
||||
);
|
||||
|
||||
chain_spec.as_json(false).map_err(|err| err.to_string())
|
||||
chain_spec.as_json(false).map_err(|err| err)
|
||||
}
|
||||
|
||||
fn generate_authority_keys_and_store(
|
||||
|
||||
@@ -124,7 +124,7 @@ impl<Block: BlockT + Clone> Clone for Blockchain<Block> {
|
||||
fn clone(&self) -> Self {
|
||||
let storage = Arc::new(RwLock::new(self.storage.read().clone()));
|
||||
Blockchain {
|
||||
storage: storage.clone(),
|
||||
storage,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -155,7 +155,7 @@ impl<Block: BlockT> Blockchain<Block> {
|
||||
aux: HashMap::new(),
|
||||
}));
|
||||
Blockchain {
|
||||
storage: storage.clone(),
|
||||
storage,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -346,7 +346,7 @@ impl<Block: BlockT> HeaderMetadata<Block> for Blockchain<Block> {
|
||||
|
||||
fn header_metadata(&self, hash: Block::Hash) -> Result<CachedHeaderMetadata<Block>, Self::Error> {
|
||||
self.header(BlockId::hash(hash))?.map(|header| CachedHeaderMetadata::from(&header))
|
||||
.ok_or(sp_blockchain::Error::UnknownBlock(format!("header not found: {}", hash)))
|
||||
.ok_or_else(|| sp_blockchain::Error::UnknownBlock(format!("header not found: {}", hash)))
|
||||
}
|
||||
|
||||
fn insert_header_metadata(&self, _hash: Block::Hash, _metadata: CachedHeaderMetadata<Block>) {
|
||||
|
||||
@@ -158,7 +158,7 @@ pub trait CliConfiguration: Sized {
|
||||
fn database_cache_size(&self) -> Result<Option<usize>> {
|
||||
Ok(self.database_params()
|
||||
.map(|x| x.database_cache_size())
|
||||
.unwrap_or(Default::default()))
|
||||
.unwrap_or_default())
|
||||
}
|
||||
|
||||
/// Get the database backend variant.
|
||||
@@ -195,7 +195,7 @@ pub trait CliConfiguration: Sized {
|
||||
fn state_cache_size(&self) -> Result<usize> {
|
||||
Ok(self.import_params()
|
||||
.map(|x| x.state_cache_size())
|
||||
.unwrap_or(Default::default()))
|
||||
.unwrap_or_default())
|
||||
}
|
||||
|
||||
/// Get the state cache child ratio (if any).
|
||||
@@ -212,7 +212,7 @@ pub trait CliConfiguration: Sized {
|
||||
fn pruning(&self, unsafe_pruning: bool, role: &Role) -> Result<PruningMode> {
|
||||
self.pruning_params()
|
||||
.map(|x| x.pruning(unsafe_pruning, role))
|
||||
.unwrap_or(Ok(Default::default()))
|
||||
.unwrap_or_else(|| Ok(Default::default()))
|
||||
}
|
||||
|
||||
/// Get the chain ID (string).
|
||||
@@ -236,7 +236,7 @@ pub trait CliConfiguration: Sized {
|
||||
fn wasm_method(&self) -> Result<WasmExecutionMethod> {
|
||||
Ok(self.import_params()
|
||||
.map(|x| x.wasm_method())
|
||||
.unwrap_or(Default::default()))
|
||||
.unwrap_or_default())
|
||||
}
|
||||
|
||||
/// Get the execution strategies.
|
||||
@@ -251,7 +251,7 @@ pub trait CliConfiguration: Sized {
|
||||
Ok(self
|
||||
.import_params()
|
||||
.map(|x| x.execution_strategies(is_dev, is_validator))
|
||||
.unwrap_or(Default::default()))
|
||||
.unwrap_or_default())
|
||||
}
|
||||
|
||||
/// Get the RPC HTTP address (`None` if disabled).
|
||||
@@ -365,7 +365,7 @@ pub trait CliConfiguration: Sized {
|
||||
fn tracing_targets(&self) -> Result<Option<String>> {
|
||||
Ok(self.import_params()
|
||||
.map(|x| x.tracing_targets())
|
||||
.unwrap_or(Default::default()))
|
||||
.unwrap_or_else(|| Default::default()))
|
||||
}
|
||||
|
||||
/// Get the TracingReceiver value from the current object
|
||||
@@ -375,7 +375,7 @@ pub trait CliConfiguration: Sized {
|
||||
fn tracing_receiver(&self) -> Result<TracingReceiver> {
|
||||
Ok(self.import_params()
|
||||
.map(|x| x.tracing_receiver())
|
||||
.unwrap_or(Default::default()))
|
||||
.unwrap_or_default())
|
||||
}
|
||||
|
||||
/// Get the node key from the current object
|
||||
@@ -385,7 +385,7 @@ pub trait CliConfiguration: Sized {
|
||||
fn node_key(&self, net_config_dir: &PathBuf) -> Result<NodeKeyConfig> {
|
||||
self.node_key_params()
|
||||
.map(|x| x.node_key(net_config_dir))
|
||||
.unwrap_or(Ok(Default::default()))
|
||||
.unwrap_or_else(|| Ok(Default::default()))
|
||||
}
|
||||
|
||||
/// Get maximum runtime instances
|
||||
|
||||
@@ -113,7 +113,7 @@ impl ImportParams {
|
||||
default
|
||||
};
|
||||
|
||||
exec.execution.unwrap_or(strat.unwrap_or(default)).into()
|
||||
exec.execution.unwrap_or_else(|| strat.unwrap_or(default)).into()
|
||||
};
|
||||
|
||||
let default_execution_import_block = if is_validator {
|
||||
|
||||
@@ -94,7 +94,7 @@ impl KeystoreParams {
|
||||
let path = self
|
||||
.keystore_path
|
||||
.clone()
|
||||
.unwrap_or(base_path.join(DEFAULT_KEYSTORE_CONFIG_PATH));
|
||||
.unwrap_or_else(|| base_path.join(DEFAULT_KEYSTORE_CONFIG_PATH));
|
||||
|
||||
Ok(KeystoreConfig::Path { path, password })
|
||||
}
|
||||
|
||||
@@ -165,7 +165,7 @@ pub fn start_aura<B, C, SC, E, I, P, SO, CAW, Error>(
|
||||
CAW: CanAuthorWith<B> + Send,
|
||||
{
|
||||
let worker = AuraWorker {
|
||||
client: client.clone(),
|
||||
client,
|
||||
block_import: Arc::new(Mutex::new(block_import)),
|
||||
env,
|
||||
keystore,
|
||||
@@ -839,7 +839,7 @@ pub fn import_queue<B, I, C, P, S>(
|
||||
initialize_authorities_cache(&*client)?;
|
||||
|
||||
let verifier = AuraVerifier {
|
||||
client: client.clone(),
|
||||
client,
|
||||
inherent_data_providers,
|
||||
phantom: PhantomData,
|
||||
};
|
||||
|
||||
@@ -512,7 +512,7 @@ impl<Block: BlockT> HeaderMetadata<Block> for BlockchainDb<Block> {
|
||||
header_metadata.clone(),
|
||||
);
|
||||
header_metadata
|
||||
}).ok_or(ClientError::UnknownBlock(format!("header not found in db: {}", hash)))
|
||||
}).ok_or_else(|| ClientError::UnknownBlock(format!("header not found in db: {}", hash)))
|
||||
}, Ok)
|
||||
}
|
||||
|
||||
|
||||
@@ -200,7 +200,7 @@ impl<Block: BlockT> HeaderMetadata<Block> for LightStorage<Block> {
|
||||
header_metadata.clone(),
|
||||
);
|
||||
header_metadata
|
||||
}).ok_or(ClientError::UnknownBlock(format!("header not found in db: {}", hash)))
|
||||
}).ok_or_else(|| ClientError::UnknownBlock(format!("header not found in db: {}", hash)))
|
||||
}, Ok)
|
||||
}
|
||||
|
||||
|
||||
@@ -181,8 +181,8 @@ pub fn insert_hash_to_key_mapping<N: TryInto<u32>, H: AsRef<[u8]> + Clone>(
|
||||
) -> sp_blockchain::Result<()> {
|
||||
transaction.set_from_vec(
|
||||
key_lookup_col,
|
||||
hash.clone().as_ref(),
|
||||
number_and_hash_to_lookup_key(number, hash)?,
|
||||
hash.as_ref(),
|
||||
number_and_hash_to_lookup_key(number, hash.clone())?,
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -353,7 +353,7 @@ fn execute_sandboxed(
|
||||
Memory::new() can't return a Error qed"
|
||||
),
|
||||
};
|
||||
env_builder.add_memory("env", "memory", memory.clone());
|
||||
env_builder.add_memory("env", "memory", memory);
|
||||
env_builder
|
||||
};
|
||||
|
||||
|
||||
@@ -336,7 +336,7 @@ impl<D: NativeExecutionDispatch + 'static> CodeExecutor for NativeExecutor<D> {
|
||||
let res = with_externalities_safe(&mut **ext, move || (call)())
|
||||
.and_then(|r| r
|
||||
.map(NativeOrEncoded::Native)
|
||||
.map_err(|s| Error::ApiError(s.to_string()))
|
||||
.map_err(|s| Error::ApiError(s))
|
||||
);
|
||||
|
||||
Ok(res)
|
||||
|
||||
@@ -234,7 +234,6 @@ impl<'a> Sandbox for FunctionExecutor<'a> {
|
||||
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")?
|
||||
.clone()
|
||||
};
|
||||
|
||||
let guest_env = match sandbox::GuestEnvironment::decode(&self.sandbox_store, raw_env_def) {
|
||||
|
||||
@@ -701,8 +701,8 @@ impl<Block: BlockT> Sink<Message<Block>> for OutgoingMessages<Block>
|
||||
keystore.local_id().clone(),
|
||||
self.round,
|
||||
self.set_id,
|
||||
).ok_or(
|
||||
Error::Signing(format!(
|
||||
).ok_or_else(
|
||||
|| Error::Signing(format!(
|
||||
"Failed to sign GRANDPA vote for round {} targetting {:?}", self.round, target_hash
|
||||
))
|
||||
)?;
|
||||
|
||||
@@ -310,7 +310,7 @@ impl BareCryptoStore for Store {
|
||||
.fold(Vec::new(), |mut v, k| {
|
||||
v.push(CryptoTypePublicPair(sr25519::CRYPTO_ID, k.clone()));
|
||||
v.push(CryptoTypePublicPair(ed25519::CRYPTO_ID, k.clone()));
|
||||
v.push(CryptoTypePublicPair(ecdsa::CRYPTO_ID, k.clone()));
|
||||
v.push(CryptoTypePublicPair(ecdsa::CRYPTO_ID, k));
|
||||
v
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -180,7 +180,7 @@ impl<B: BlockT> ConsensusGossip<B> {
|
||||
|
||||
let validator = self.validator.clone();
|
||||
let mut context = NetworkContext { gossip: self, network };
|
||||
validator.new_peer(&mut context, &who, role.clone());
|
||||
validator.new_peer(&mut context, &who, role);
|
||||
}
|
||||
|
||||
fn register_message_hashed(
|
||||
|
||||
@@ -409,7 +409,7 @@ where
|
||||
},
|
||||
body: if get_body {
|
||||
self.chain.block_body(&BlockId::Hash(hash))?
|
||||
.unwrap_or(Vec::new())
|
||||
.unwrap_or_default()
|
||||
.iter_mut()
|
||||
.map(|extrinsic| extrinsic.encode())
|
||||
.collect()
|
||||
@@ -418,7 +418,7 @@ where
|
||||
},
|
||||
receipt: Vec::new(),
|
||||
message_queue: Vec::new(),
|
||||
justification: justification.unwrap_or(Vec::new()),
|
||||
justification: justification.unwrap_or_default(),
|
||||
is_empty_justification,
|
||||
};
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ pub enum Error {
|
||||
/// Io error
|
||||
Io(std::io::Error),
|
||||
/// Client error
|
||||
Client(sp_blockchain::Error),
|
||||
Client(Box<sp_blockchain::Error>),
|
||||
/// The same bootnode (based on address) is registered with two different peer ids.
|
||||
#[display(
|
||||
fmt = "The same bootnode (`{}`) is registered with two different peer ids: `{}` and `{}`",
|
||||
|
||||
@@ -206,7 +206,7 @@ where
|
||||
let finality_proof = if let Some(provider) = &self.finality_proof_provider {
|
||||
provider
|
||||
.prove_finality(block_hash, &request.request)?
|
||||
.unwrap_or(Vec::new())
|
||||
.unwrap_or_default()
|
||||
} else {
|
||||
log::error!("Answering a finality proof request while finality provider is empty");
|
||||
return Err(From::from("Empty finality proof provider".to_string()))
|
||||
|
||||
@@ -806,7 +806,7 @@ impl GenericProto {
|
||||
debug!(target: "sub-libp2p", "PSM => Accept({:?}, {:?}): Obsolete incoming,
|
||||
sending back dropped", index, incoming.peer_id);
|
||||
debug!(target: "sub-libp2p", "PSM <= Dropped({:?})", incoming.peer_id);
|
||||
self.peerset.dropped(incoming.peer_id.clone());
|
||||
self.peerset.dropped(incoming.peer_id);
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -141,7 +141,7 @@ impl<B: BlockT> ExtraRequests<B> {
|
||||
request,
|
||||
);
|
||||
}
|
||||
self.failed_requests.entry(request).or_insert(Vec::new()).push((who, Instant::now()));
|
||||
self.failed_requests.entry(request).or_default().push((who, Instant::now()));
|
||||
self.pending_requests.push_front(request);
|
||||
} else {
|
||||
trace!(target: "sync", "No active {} request to {:?}",
|
||||
|
||||
@@ -678,7 +678,7 @@ pub trait TestNetFactory: Sized {
|
||||
protocol_id: ProtocolId::from(&b"test-protocol-name"[..]),
|
||||
import_queue,
|
||||
block_announce_validator: config.block_announce_validator
|
||||
.unwrap_or(Box::new(DefaultBlockAnnounceValidator)),
|
||||
.unwrap_or_else(|| Box::new(DefaultBlockAnnounceValidator)),
|
||||
metrics_registry: None,
|
||||
}).unwrap();
|
||||
|
||||
|
||||
@@ -539,7 +539,7 @@ fn resolve_header<Block: BlockT, F: Fetcher<Block>>(
|
||||
|
||||
maybe_header.then(move |result|
|
||||
ready(result.and_then(|maybe_header|
|
||||
maybe_header.ok_or(ClientError::UnknownBlock(format!("{}", block)))
|
||||
maybe_header.ok_or_else(|| ClientError::UnknownBlock(format!("{}", block)))
|
||||
).map_err(client_err)),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -438,7 +438,7 @@ impl ServiceBuilder<(), (), (), (), (), (), (), (), (), (), ()> {
|
||||
backend,
|
||||
task_manager,
|
||||
keystore,
|
||||
fetcher: Some(fetcher.clone()),
|
||||
fetcher: Some(fetcher),
|
||||
select_chain: None,
|
||||
import_queue: (),
|
||||
finality_proof_request_builder: None,
|
||||
@@ -1286,7 +1286,7 @@ fn gen_handler<TBl, TBackend, TExPool, TRpc, TCl>(
|
||||
client.clone(),
|
||||
subscriptions.clone(),
|
||||
remote_backend.clone(),
|
||||
on_demand.clone()
|
||||
on_demand,
|
||||
);
|
||||
(chain, state, child_state)
|
||||
|
||||
@@ -1298,15 +1298,15 @@ fn gen_handler<TBl, TBackend, TExPool, TRpc, TCl>(
|
||||
};
|
||||
|
||||
let author = sc_rpc::author::Author::new(
|
||||
client.clone(),
|
||||
transaction_pool.clone(),
|
||||
client,
|
||||
transaction_pool,
|
||||
subscriptions,
|
||||
keystore.clone(),
|
||||
keystore,
|
||||
deny_unsafe,
|
||||
);
|
||||
let system = system::System::new(system_info, system_rpc_tx.clone(), deny_unsafe);
|
||||
let system = system::System::new(system_info, system_rpc_tx, deny_unsafe);
|
||||
|
||||
let maybe_offchain_rpc = offchain_storage.clone()
|
||||
let maybe_offchain_rpc = offchain_storage
|
||||
.map(|storage| {
|
||||
let offchain = sc_rpc::offchain::Offchain::new(storage, deny_unsafe);
|
||||
// FIXME: Use plain Option (don't collect into HashMap) when we upgrade to jsonrpc 14.1
|
||||
@@ -1357,7 +1357,7 @@ fn build_network<TBl, TExPool, TImpQu, TCl>(
|
||||
{
|
||||
let transaction_pool_adapter = Arc::new(TransactionPoolAdapter {
|
||||
imports_external_transactions: !matches!(config.role, Role::Light),
|
||||
pool: transaction_pool.clone(),
|
||||
pool: transaction_pool,
|
||||
client: client.clone(),
|
||||
});
|
||||
|
||||
@@ -1391,8 +1391,8 @@ fn build_network<TBl, TExPool, TImpQu, TCl>(
|
||||
chain: client.clone(),
|
||||
finality_proof_provider,
|
||||
finality_proof_request_builder,
|
||||
on_demand: on_demand.clone(),
|
||||
transaction_pool: transaction_pool_adapter.clone() as _,
|
||||
on_demand: on_demand,
|
||||
transaction_pool: transaction_pool_adapter as _,
|
||||
import_queue: Box::new(import_queue),
|
||||
protocol_id,
|
||||
block_announce_validator,
|
||||
@@ -1407,7 +1407,7 @@ fn build_network<TBl, TExPool, TImpQu, TCl>(
|
||||
let future = build_network_future(
|
||||
config.role.clone(),
|
||||
network_mut,
|
||||
client.clone(),
|
||||
client,
|
||||
network_status_sinks.clone(),
|
||||
system_rpc_rx,
|
||||
has_bootnodes,
|
||||
|
||||
@@ -52,8 +52,8 @@ impl<B: BlockT> BlockRules<B> {
|
||||
bad_blocks: BadBlocks<B>,
|
||||
) -> Self {
|
||||
Self {
|
||||
bad: bad_blocks.unwrap_or(HashSet::new()),
|
||||
forks: fork_blocks.unwrap_or(vec![]).into_iter().collect(),
|
||||
bad: bad_blocks.unwrap_or_else(|| HashSet::new()),
|
||||
forks: fork_blocks.unwrap_or_else(|| vec![]).into_iter().collect(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -518,7 +518,7 @@ pub fn sync<G, E, Fb, F, Lb, L, B, ExF, U>(
|
||||
let temp = tempdir_with_prefix("substrate-sync-test");
|
||||
let mut network = TestNet::new(
|
||||
&temp,
|
||||
spec.clone(),
|
||||
spec,
|
||||
(0..NUM_FULL_NODES).map(|_| { |cfg| full_builder(cfg) }),
|
||||
(0..NUM_LIGHT_NODES).map(|_| { |cfg| light_builder(cfg) }),
|
||||
// Note: this iterator is empty but we can't just use `iter::empty()`, otherwise
|
||||
@@ -592,7 +592,7 @@ pub fn consensus<G, E, Fb, F, Lb, L>(
|
||||
let temp = tempdir_with_prefix("substrate-consensus-test");
|
||||
let mut network = TestNet::new(
|
||||
&temp,
|
||||
spec.clone(),
|
||||
spec,
|
||||
(0..NUM_FULL_NODES / 2).map(|_| { |cfg| full_builder(cfg).map(|s| (s, ())) }),
|
||||
(0..NUM_LIGHT_NODES / 2).map(|_| { |cfg| light_builder(cfg) }),
|
||||
authorities.into_iter().map(|key| (key, { |cfg| full_builder(cfg).map(|s| (s, ())) })),
|
||||
|
||||
@@ -278,7 +278,7 @@ impl<Hash: hash::Hash + Member + Serialize, Ex: std::fmt::Debug> BasePool<Hash,
|
||||
tx: Transaction<Hash, Ex>,
|
||||
) -> error::Result<Imported<Hash, Ex>> {
|
||||
if self.is_imported(&tx.hash) {
|
||||
return Err(error::Error::AlreadyImported(Box::new(tx.hash.clone())))
|
||||
return Err(error::Error::AlreadyImported(Box::new(tx.hash)))
|
||||
}
|
||||
|
||||
let tx = WaitingTransaction::new(
|
||||
|
||||
@@ -538,7 +538,7 @@ impl<Hash: hash::Hash + Member, Ex> Iterator for BestIterator<Hash, Ex> {
|
||||
}
|
||||
}
|
||||
|
||||
return Some(best.transaction.clone())
|
||||
return Some(best.transaction)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -305,7 +305,7 @@ impl<Client, F, Block> sc_transaction_graph::ChainApi for
|
||||
|
||||
fn block_body(&self, id: &BlockId<Self::Block>) -> Self::BodyFuture {
|
||||
let header = self.client.header(*id)
|
||||
.and_then(|h| h.ok_or(sp_blockchain::Error::UnknownBlock(format!("{}", id))));
|
||||
.and_then(|h| h.ok_or_else(|| sp_blockchain::Error::UnknownBlock(format!("{}", id))));
|
||||
let header = match header {
|
||||
Ok(header) => header,
|
||||
Err(err) => {
|
||||
|
||||
@@ -1092,7 +1092,7 @@ impl<T: Trait<I>, I: Instance> Currency<T::AccountId> for Module<T, I> where
|
||||
|
||||
// defensive only: overflow should never happen, however in case it does, then this
|
||||
// operation is a no-op.
|
||||
account.free = account.free.checked_add(&value).ok_or(Self::PositiveImbalance::zero())?;
|
||||
account.free = account.free.checked_add(&value).ok_or_else(|| Self::PositiveImbalance::zero())?;
|
||||
|
||||
Ok(PositiveImbalance::new(value))
|
||||
}).unwrap_or_else(|x| x)
|
||||
@@ -1153,7 +1153,7 @@ impl<T: Trait<I>, I: Instance> Currency<T::AccountId> for Module<T, I> where
|
||||
};
|
||||
account.free = value;
|
||||
Ok(imbalance)
|
||||
}).unwrap_or(SignedImbalance::Positive(Self::PositiveImbalance::zero()))
|
||||
}).unwrap_or_else(|_| SignedImbalance::Positive(Self::PositiveImbalance::zero()))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -801,7 +801,7 @@ where
|
||||
|
||||
fn rent_allowance(&self) -> BalanceOf<T> {
|
||||
storage::rent_allowance::<T>(&self.ctx.self_account)
|
||||
.unwrap_or(<BalanceOf<T>>::max_value()) // Must never be triggered actually
|
||||
.unwrap_or_else(|_| <BalanceOf<T>>::max_value()) // Must never be triggered actually
|
||||
}
|
||||
|
||||
fn block_number(&self) -> T::BlockNumber { self.block_number }
|
||||
|
||||
@@ -648,7 +648,7 @@ impl<T: Trait> Module<T> {
|
||||
let cfg = Config::preload();
|
||||
let vm = WasmVm::new(&cfg.schedule);
|
||||
let loader = WasmLoader::new(&cfg.schedule);
|
||||
let mut ctx = ExecutionContext::top_level(origin.clone(), &cfg, &vm, &loader);
|
||||
let mut ctx = ExecutionContext::top_level(origin, &cfg, &vm, &loader);
|
||||
func(&mut ctx, gas_meter)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,7 +104,7 @@ fn compute_fee_per_block<T: Trait>(
|
||||
|
||||
effective_storage_size
|
||||
.checked_mul(&T::RentByteFee::get())
|
||||
.unwrap_or(<BalanceOf<T>>::max_value())
|
||||
.unwrap_or_else(|| <BalanceOf<T>>::max_value())
|
||||
}
|
||||
|
||||
/// Returns amount of funds available to consume by rent mechanism.
|
||||
@@ -179,7 +179,7 @@ fn consider_case<T: Trait>(
|
||||
|
||||
let dues = fee_per_block
|
||||
.checked_mul(&blocks_passed.saturated_into::<u32>().into())
|
||||
.unwrap_or(<BalanceOf<T>>::max_value());
|
||||
.unwrap_or_else(|| <BalanceOf<T>>::max_value());
|
||||
let insufficient_rent = rent_budget < dues;
|
||||
|
||||
// If the rent payment cannot be withdrawn due to locks on the account balance, then evict the
|
||||
|
||||
@@ -607,7 +607,7 @@ decl_module! {
|
||||
// returns NoMember error in case of error.
|
||||
let _ = Self::remove_and_replace_member(&who)?;
|
||||
T::Currency::unreserve(&who, T::CandidacyBond::get());
|
||||
Self::deposit_event(RawEvent::MemberRenounced(who.clone()));
|
||||
Self::deposit_event(RawEvent::MemberRenounced(who));
|
||||
},
|
||||
Renouncing::RunnerUp => {
|
||||
let mut runners_up_with_stake = Self::runners_up();
|
||||
@@ -1002,7 +1002,7 @@ impl<T: Trait> Module<T> {
|
||||
);
|
||||
T::ChangeMembers::change_members_sorted(
|
||||
&incoming,
|
||||
&outgoing.clone(),
|
||||
&outgoing,
|
||||
&new_members_ids,
|
||||
);
|
||||
T::ChangeMembers::set_prime(prime);
|
||||
|
||||
@@ -295,12 +295,12 @@ decl_module! {
|
||||
ensure!(!other_signatories.is_empty(), Error::<T>::TooFewSignatories);
|
||||
let other_signatories_len = other_signatories.len();
|
||||
ensure!(other_signatories_len < max_sigs, Error::<T>::TooManySignatories);
|
||||
let signatories = Self::ensure_sorted_and_insert(other_signatories, who.clone())?;
|
||||
let signatories = Self::ensure_sorted_and_insert(other_signatories, who)?;
|
||||
|
||||
let id = Self::multi_account_id(&signatories, 1);
|
||||
|
||||
let call_len = call.using_encoded(|c| c.len());
|
||||
let result = call.dispatch(RawOrigin::Signed(id.clone()).into());
|
||||
let result = call.dispatch(RawOrigin::Signed(id).into());
|
||||
|
||||
result.map(|post_dispatch_info| post_dispatch_info.actual_weight
|
||||
.map(|actual_weight| weight_of::as_multi_threshold_1::<T>(
|
||||
|
||||
@@ -257,7 +257,7 @@ benchmarks! {
|
||||
.flat_map(|reporter| vec![
|
||||
frame_system::Event::<T>::NewAccount(reporter.clone()).into(),
|
||||
<T as BalancesTrait>::Event::from(
|
||||
pallet_balances::Event::<T>::Endowed(reporter.clone(), (reward_amount / r).into())
|
||||
pallet_balances::Event::<T>::Endowed(reporter, (reward_amount / r).into())
|
||||
).into()
|
||||
]);
|
||||
|
||||
|
||||
@@ -355,7 +355,7 @@ decl_module! {
|
||||
// if there is already an element with `score`, we insert
|
||||
// right before that. if not, the search returns a location
|
||||
// where we can insert while maintaining order.
|
||||
let item = (who.clone(), Some(score.clone()));
|
||||
let item = (who, Some(score.clone()));
|
||||
let location = pool
|
||||
.binary_search_by_key(
|
||||
&Reverse(score),
|
||||
|
||||
@@ -162,7 +162,7 @@ fn main() {
|
||||
match mode {
|
||||
Mode::WeakerSubmission => {
|
||||
assert_eq!(
|
||||
call.dispatch_bypass_filter(origin.clone().into()).unwrap_err().error,
|
||||
call.dispatch_bypass_filter(origin.into()).unwrap_err().error,
|
||||
DispatchError::Module {
|
||||
index: 0,
|
||||
error: 16,
|
||||
|
||||
@@ -61,7 +61,7 @@ pub fn create_validator_with_nominators<T: Trait>(
|
||||
let validator_prefs = ValidatorPrefs {
|
||||
commission: Perbill::from_percent(50),
|
||||
};
|
||||
Staking::<T>::validate(RawOrigin::Signed(v_controller.clone()).into(), validator_prefs)?;
|
||||
Staking::<T>::validate(RawOrigin::Signed(v_controller).into(), validator_prefs)?;
|
||||
let stash_lookup: <T::Lookup as StaticLookup>::Source = T::Lookup::unlookup(v_stash.clone());
|
||||
|
||||
points_total += 10;
|
||||
@@ -375,7 +375,7 @@ benchmarks! {
|
||||
for _ in 0 .. l {
|
||||
staking_ledger.unlocking.push(unlock_chunk.clone())
|
||||
}
|
||||
Ledger::<T>::insert(controller.clone(), staking_ledger.clone());
|
||||
Ledger::<T>::insert(controller, staking_ledger);
|
||||
let slash_amount = T::Currency::minimum_balance() * 10.into();
|
||||
let balance_before = T::Currency::free_balance(&stash);
|
||||
}: {
|
||||
|
||||
@@ -1626,7 +1626,7 @@ decl_module! {
|
||||
let era = Self::current_era().unwrap_or(0) + T::BondingDuration::get();
|
||||
ledger.unlocking.push(UnlockChunk { value, era });
|
||||
Self::update_ledger(&controller, &ledger);
|
||||
Self::deposit_event(RawEvent::Unbonded(ledger.stash.clone(), value));
|
||||
Self::deposit_event(RawEvent::Unbonded(ledger.stash, value));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -370,7 +370,7 @@ fn slash_nominators<T: Trait>(
|
||||
let mut era_slash = <Module<T> as Store>::NominatorSlashInEra::get(
|
||||
&slash_era,
|
||||
stash,
|
||||
).unwrap_or(Zero::zero());
|
||||
).unwrap_or_else(|| Zero::zero());
|
||||
|
||||
era_slash += own_slash_difference;
|
||||
|
||||
|
||||
@@ -158,7 +158,7 @@ pub fn get_weak_solution<T: Trait>(
|
||||
|
||||
// self stake
|
||||
<Validators<T>>::iter().for_each(|(who, _p)| {
|
||||
*backing_stake_of.entry(who.clone()).or_insert(Zero::zero()) +=
|
||||
*backing_stake_of.entry(who.clone()).or_insert_with(|| Zero::zero()) +=
|
||||
<Module<T>>::slashable_balance_of(&who)
|
||||
});
|
||||
|
||||
|
||||
@@ -249,7 +249,7 @@ impl StorageLineDefExt {
|
||||
StorageLineTypeDef::DoubleMap(map) => map.value.clone(),
|
||||
};
|
||||
let is_option = ext::extract_type_option(&query_type).is_some();
|
||||
let value_type = ext::extract_type_option(&query_type).unwrap_or(query_type.clone());
|
||||
let value_type = ext::extract_type_option(&query_type).unwrap_or_else(|| query_type.clone());
|
||||
|
||||
let module_runtime_generic = &def.module_runtime_generic;
|
||||
let module_runtime_trait = &def.module_runtime_trait;
|
||||
@@ -328,7 +328,7 @@ impl StorageLineDefExt {
|
||||
|
||||
pub enum StorageLineTypeDef {
|
||||
Map(MapDef),
|
||||
DoubleMap(DoubleMapDef),
|
||||
DoubleMap(Box<DoubleMapDef>),
|
||||
Simple(syn::Type),
|
||||
}
|
||||
|
||||
|
||||
@@ -198,7 +198,7 @@ impl_parse_for_opt!(DeclStorageBuild => keyword::build);
|
||||
#[derive(ToTokens, Debug)]
|
||||
enum DeclStorageType {
|
||||
Map(DeclStorageMap),
|
||||
DoubleMap(DeclStorageDoubleMap),
|
||||
DoubleMap(Box<DeclStorageDoubleMap>),
|
||||
Simple(syn::Type),
|
||||
}
|
||||
|
||||
@@ -478,13 +478,13 @@ fn parse_storage_line_defs(
|
||||
}
|
||||
),
|
||||
DeclStorageType::DoubleMap(map) => super::StorageLineTypeDef::DoubleMap(
|
||||
super::DoubleMapDef {
|
||||
Box::new(super::DoubleMapDef {
|
||||
hasher1: map.hasher1.inner.ok_or_else(no_hasher_error)?.into(),
|
||||
hasher2: map.hasher2.inner.ok_or_else(no_hasher_error)?.into(),
|
||||
key1: map.key1,
|
||||
key2: map.key2,
|
||||
value: map.value,
|
||||
}
|
||||
})
|
||||
),
|
||||
DeclStorageType::Simple(expr) => super::StorageLineTypeDef::Simple(expr),
|
||||
};
|
||||
|
||||
@@ -30,7 +30,7 @@ pub(crate) fn fields_idents(
|
||||
fields: impl Iterator<Item = syn::Field>,
|
||||
) -> impl Iterator<Item = proc_macro2::TokenStream> {
|
||||
fields.enumerate().map(|(ix, field)| {
|
||||
field.ident.clone().map(|i| quote!{#i}).unwrap_or_else(|| {
|
||||
field.ident.map(|i| quote!{#i}).unwrap_or_else(|| {
|
||||
let f_ix: syn::Ident = syn::Ident::new(&format!("f_{}", ix), Span::call_site());
|
||||
quote!( #f_ix )
|
||||
})
|
||||
@@ -41,7 +41,7 @@ pub(crate) fn fields_access(
|
||||
fields: impl Iterator<Item = syn::Field>,
|
||||
) -> impl Iterator<Item = proc_macro2::TokenStream> {
|
||||
fields.enumerate().map(|(ix, field)| {
|
||||
field.ident.clone().map(|i| quote!( #i )).unwrap_or_else(|| {
|
||||
field.ident.map(|i| quote!( #i )).unwrap_or_else(|| {
|
||||
let f_ix: syn::Index = syn::Index {
|
||||
index: ix as u32,
|
||||
span: Span::call_site(),
|
||||
|
||||
@@ -185,7 +185,7 @@ impl<T: SigningTypes, C: AppCrypto<T::Public, T::Signature>, X> Signer<T, C, X>
|
||||
let generic_public = C::GenericPublic::from(key);
|
||||
let public = generic_public.into();
|
||||
let account_id = public.clone().into_account();
|
||||
Account::new(index, account_id, public.clone())
|
||||
Account::new(index, account_id, public)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -252,7 +252,7 @@ fn generate_native_call_generators(decl: &ItemTrait) -> Result<TokenStream> {
|
||||
}
|
||||
FnArg::Typed(arg)
|
||||
},
|
||||
r => r.clone(),
|
||||
r => r,
|
||||
});
|
||||
|
||||
let (impl_generics, ty_generics, where_clause) = decl.generics.split_for_impl();
|
||||
|
||||
@@ -417,7 +417,7 @@ fn extend_with_runtime_decl_path(mut trait_: Path) -> Path {
|
||||
};
|
||||
|
||||
let pos = trait_.segments.len() - 1;
|
||||
trait_.segments.insert(pos, runtime.clone().into());
|
||||
trait_.segments.insert(pos, runtime.into());
|
||||
trait_
|
||||
}
|
||||
|
||||
|
||||
@@ -48,8 +48,8 @@ fn main() {
|
||||
digits_u.reverse();
|
||||
digits_v.reverse();
|
||||
|
||||
let num_u = num_bigint::BigUint::new(digits_u.clone());
|
||||
let num_v = num_bigint::BigUint::new(digits_v.clone());
|
||||
let num_u = num_bigint::BigUint::new(digits_u);
|
||||
let num_v = num_bigint::BigUint::new(digits_v);
|
||||
|
||||
if check_digit_lengths(&u, &v, 4) {
|
||||
assert_eq!(u.cmp(&v), ue.cmp(&ve));
|
||||
@@ -146,14 +146,14 @@ fn main() {
|
||||
// Division
|
||||
|
||||
if v.len() == 1 && v.get(0) != 0 {
|
||||
let w = u.clone().div_unit(v.get(0));
|
||||
let num_w = num_u.clone() / &num_v;
|
||||
let w = u.div_unit(v.get(0));
|
||||
let num_w = num_u / &num_v;
|
||||
assert_biguints_eq(&w, &num_w);
|
||||
} else if u.len() > v.len() && v.len() > 0 {
|
||||
let num_remainder = num_u.clone() % num_v.clone();
|
||||
|
||||
let (w, remainder) = u.clone().div(&v, return_remainder).unwrap();
|
||||
let num_w = num_u.clone() / &num_v;
|
||||
let (w, remainder) = u.div(&v, return_remainder).unwrap();
|
||||
let num_w = num_u / &num_v;
|
||||
|
||||
assert_biguints_eq(&w, &num_w);
|
||||
|
||||
|
||||
@@ -84,7 +84,7 @@ pub trait FixedPointNumber:
|
||||
fn saturating_from_integer<N: FixedPointOperand>(int: N) -> Self {
|
||||
let mut n: I129 = int.into();
|
||||
n.value = n.value.saturating_mul(Self::DIV.saturated_into());
|
||||
Self::from_inner(from_i129(n).unwrap_or(to_bound(int, 0)))
|
||||
Self::from_inner(from_i129(n).unwrap_or_else(|| to_bound(int, 0)))
|
||||
}
|
||||
|
||||
/// Creates `self` from an integer number `int`.
|
||||
@@ -101,7 +101,7 @@ pub trait FixedPointNumber:
|
||||
if d == D::zero() {
|
||||
panic!("attempt to divide by zero")
|
||||
}
|
||||
Self::checked_from_rational(n, d).unwrap_or(to_bound(n, d))
|
||||
Self::checked_from_rational(n, d).unwrap_or_else(|| to_bound(n, d))
|
||||
}
|
||||
|
||||
/// Creates `self` from a rational number. Equal to `n / d`.
|
||||
@@ -137,7 +137,7 @@ pub trait FixedPointNumber:
|
||||
///
|
||||
/// Returns `N::min` or `N::max` if the result does not fit in `N`.
|
||||
fn saturating_mul_int<N: FixedPointOperand>(self, n: N) -> N {
|
||||
self.checked_mul_int(n).unwrap_or(to_bound(self.into_inner(), n))
|
||||
self.checked_mul_int(n).unwrap_or_else(|| to_bound(self.into_inner(), n))
|
||||
}
|
||||
|
||||
/// Checked division for integer type `N`. Equal to `self / d`.
|
||||
@@ -160,7 +160,7 @@ pub trait FixedPointNumber:
|
||||
if d == N::zero() {
|
||||
panic!("attempt to divide by zero")
|
||||
}
|
||||
self.checked_div_int(d).unwrap_or(to_bound(self.into_inner(), d))
|
||||
self.checked_div_int(d).unwrap_or_else(|| to_bound(self.into_inner(), d))
|
||||
}
|
||||
|
||||
/// Saturating multiplication for integer type `N`, adding the result back.
|
||||
@@ -183,7 +183,7 @@ pub trait FixedPointNumber:
|
||||
if inner >= Self::Inner::zero() {
|
||||
self
|
||||
} else {
|
||||
Self::from_inner(inner.checked_neg().unwrap_or(Self::Inner::max_value()))
|
||||
Self::from_inner(inner.checked_neg().unwrap_or_else(|| Self::Inner::max_value()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -301,7 +301,7 @@ impl<N: FixedPointOperand> From<N> for I129 {
|
||||
if n < N::zero() {
|
||||
let value: u128 = n.checked_neg()
|
||||
.map(|n| n.unique_saturated_into())
|
||||
.unwrap_or(N::max_value().unique_saturated_into().saturating_add(1));
|
||||
.unwrap_or_else(|| N::max_value().unique_saturated_into().saturating_add(1));
|
||||
I129 { value, negative: true }
|
||||
} else {
|
||||
I129 { value: n.unique_saturated_into(), negative: false }
|
||||
@@ -399,7 +399,7 @@ macro_rules! implement_fixed {
|
||||
}
|
||||
|
||||
fn saturating_mul(self, rhs: Self) -> Self {
|
||||
self.checked_mul(&rhs).unwrap_or(to_bound(self.0, rhs.0))
|
||||
self.checked_mul(&rhs).unwrap_or_else(|| to_bound(self.0, rhs.0))
|
||||
}
|
||||
|
||||
fn saturating_pow(self, exp: usize) -> Self {
|
||||
|
||||
@@ -108,7 +108,7 @@ impl<B: BlockT, Transaction: Send> ImportQueue<B> for BasicQueue<B, Transaction>
|
||||
) {
|
||||
let _ = self.sender
|
||||
.unbounded_send(
|
||||
ToWorkerMsg::ImportJustification(who.clone(), hash, number, justification)
|
||||
ToWorkerMsg::ImportJustification(who, hash, number, justification)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -180,7 +180,7 @@ impl DeriveJunction {
|
||||
impl<T: AsRef<str>> From<T> for DeriveJunction {
|
||||
fn from(j: T) -> DeriveJunction {
|
||||
let j = j.as_ref();
|
||||
let (code, hard) = if j.starts_with("/") {
|
||||
let (code, hard) = if j.starts_with('/') {
|
||||
(&j[1..], true)
|
||||
} else {
|
||||
(j, false)
|
||||
|
||||
@@ -359,7 +359,7 @@ impl offchain::Externalities for TestOffchainExt {
|
||||
if let Some(req) = state.requests.get_mut(&request_id) {
|
||||
let response = req.response
|
||||
.as_mut()
|
||||
.expect(&format!("No response provided for request: {:?}", request_id));
|
||||
.unwrap_or_else(|| panic!("No response provided for request: {:?}", request_id));
|
||||
|
||||
if req.read >= response.len() {
|
||||
// Remove the pending request as per spec.
|
||||
|
||||
@@ -90,7 +90,7 @@ impl crate::traits::BareCryptoStore for KeyStore {
|
||||
v
|
||||
}))
|
||||
})
|
||||
.unwrap_or(Ok(vec![]))
|
||||
.unwrap_or_else(|| Ok(vec![]))
|
||||
}
|
||||
|
||||
fn sr25519_public_keys(&self, id: KeyTypeId) -> Vec<sr25519::Public> {
|
||||
@@ -222,19 +222,19 @@ impl crate::traits::BareCryptoStore for KeyStore {
|
||||
ed25519::CRYPTO_ID => {
|
||||
let key_pair: ed25519::Pair = self
|
||||
.ed25519_key_pair(id, &ed25519::Public::from_slice(key.1.as_slice()))
|
||||
.ok_or(Error::PairNotFound("ed25519".to_owned()))?;
|
||||
.ok_or_else(|| Error::PairNotFound("ed25519".to_owned()))?;
|
||||
return Ok(key_pair.sign(msg).encode());
|
||||
}
|
||||
sr25519::CRYPTO_ID => {
|
||||
let key_pair: sr25519::Pair = self
|
||||
.sr25519_key_pair(id, &sr25519::Public::from_slice(key.1.as_slice()))
|
||||
.ok_or(Error::PairNotFound("sr25519".to_owned()))?;
|
||||
.ok_or_else(|| Error::PairNotFound("sr25519".to_owned()))?;
|
||||
return Ok(key_pair.sign(msg).encode());
|
||||
}
|
||||
ecdsa::CRYPTO_ID => {
|
||||
let key_pair: ecdsa::Pair = self
|
||||
.ecdsa_key_pair(id, &ecdsa::Public::from_slice(key.1.as_slice()))
|
||||
.ok_or(Error::PairNotFound("ecdsa".to_owned()))?;
|
||||
.ok_or_else(|| Error::PairNotFound("ecdsa".to_owned()))?;
|
||||
return Ok(key_pair.sign(msg).encode());
|
||||
}
|
||||
_ => Err(Error::KeyNotSupported(id))
|
||||
@@ -249,7 +249,7 @@ impl crate::traits::BareCryptoStore for KeyStore {
|
||||
) -> Result<VRFSignature, Error> {
|
||||
let transcript = make_transcript(transcript_data);
|
||||
let pair = self.sr25519_key_pair(key_type, public)
|
||||
.ok_or(Error::PairNotFound("Not found".to_owned()))?;
|
||||
.ok_or_else(|| Error::PairNotFound("Not found".to_owned()))?;
|
||||
|
||||
let (inout, proof, _) = pair.as_ref().vrf_sign(transcript);
|
||||
Ok(VRFSignature {
|
||||
|
||||
@@ -114,7 +114,7 @@ fn main() {
|
||||
*stake_of_tree.get(who).unwrap()
|
||||
};
|
||||
|
||||
let mut staked = assignment_ratio_to_staked(assignments.clone(), &stake_of);
|
||||
let mut staked = assignment_ratio_to_staked(assignments, &stake_of);
|
||||
let winners = to_without_backing(winners);
|
||||
let mut support = build_support_map(winners.as_ref(), staked.as_ref()).0;
|
||||
|
||||
|
||||
@@ -416,7 +416,7 @@ pub fn seq_phragmen<AccountId, R>(
|
||||
n.load.n(),
|
||||
n.budget,
|
||||
c.approval_stake,
|
||||
).unwrap_or(Bounded::max_value());
|
||||
).unwrap_or_else(|_| Bounded::max_value());
|
||||
let temp_d = n.load.d();
|
||||
let temp = Rational128::from(temp_n, temp_d);
|
||||
c.score = c.score.lazy_saturating_add(temp);
|
||||
@@ -470,14 +470,14 @@ pub fn seq_phragmen<AccountId, R>(
|
||||
n.load.n(),
|
||||
)
|
||||
// If result cannot fit in u128. Not much we can do about it.
|
||||
.unwrap_or(Bounded::max_value());
|
||||
.unwrap_or_else(|_| Bounded::max_value());
|
||||
|
||||
TryFrom::try_from(parts)
|
||||
// If the result cannot fit into R::Inner. Defensive only. This can
|
||||
// never happen. `desired_scale * e / n`, where `e / n < 1` always
|
||||
// yields a value smaller than `desired_scale`, which will fit into
|
||||
// R::Inner.
|
||||
.unwrap_or(Bounded::max_value())
|
||||
.unwrap_or_else(|_| Bounded::max_value())
|
||||
} else {
|
||||
// defensive only. Both edge and voter loads are built from
|
||||
// scores, hence MUST have the same denominator.
|
||||
|
||||
@@ -362,11 +362,11 @@ fn reduce_all<A: IdentifierT>(assignments: &mut Vec<StakedAssignment<A>>) -> u32
|
||||
// create both.
|
||||
let voter_node = tree
|
||||
.entry(voter_id.clone())
|
||||
.or_insert(Node::new(voter_id).into_ref())
|
||||
.or_insert_with(|| Node::new(voter_id).into_ref())
|
||||
.clone();
|
||||
let target_node = tree
|
||||
.entry(target_id.clone())
|
||||
.or_insert(Node::new(target_id).into_ref())
|
||||
.or_insert_with(|| Node::new(target_id).into_ref())
|
||||
.clone();
|
||||
|
||||
// If one exists but the other one doesn't, or if both does not, then set the existing
|
||||
|
||||
@@ -46,7 +46,7 @@ pub fn key_changes<'a, H: Hasher, Number: BlockNumber>(
|
||||
key: &'a [u8],
|
||||
) -> Result<DrilldownIterator<'a, H, Number>, String> {
|
||||
// we can't query any roots before root
|
||||
let max = ::std::cmp::min(max.clone(), end.number.clone());
|
||||
let max = std::cmp::min(max, end.number.clone());
|
||||
|
||||
Ok(DrilldownIterator {
|
||||
essence: DrilldownIteratorEssence {
|
||||
@@ -85,7 +85,7 @@ pub fn key_changes_proof<'a, H: Hasher, Number: BlockNumber>(
|
||||
key: &[u8],
|
||||
) -> Result<Vec<Vec<u8>>, String> where H::Out: Codec {
|
||||
// we can't query any roots before root
|
||||
let max = ::std::cmp::min(max.clone(), end.number.clone());
|
||||
let max = std::cmp::min(max, end.number.clone());
|
||||
|
||||
let mut iter = ProvingDrilldownIterator {
|
||||
essence: DrilldownIteratorEssence {
|
||||
@@ -156,7 +156,7 @@ pub fn key_changes_proof_check_with_db<'a, H: Hasher, Number: BlockNumber>(
|
||||
key: &[u8]
|
||||
) -> Result<Vec<(Number, u32)>, String> where H::Out: Encode {
|
||||
// we can't query any roots before root
|
||||
let max = ::std::cmp::min(max.clone(), end.number.clone());
|
||||
let max = std::cmp::min(max, end.number.clone());
|
||||
|
||||
DrilldownIterator {
|
||||
essence: DrilldownIteratorEssence {
|
||||
|
||||
@@ -471,8 +471,8 @@ where
|
||||
let root = self
|
||||
.storage(prefixed_storage_key.as_slice())
|
||||
.and_then(|k| Decode::decode(&mut &k[..]).ok())
|
||||
.unwrap_or(
|
||||
empty_child_trie_root::<Layout<H>>()
|
||||
.unwrap_or_else(
|
||||
|| empty_child_trie_root::<Layout<H>>()
|
||||
);
|
||||
trace!(target: "state", "{:04x}: ChildRoot({})(cached) {}",
|
||||
self.id,
|
||||
@@ -512,8 +512,8 @@ where
|
||||
let root = self
|
||||
.storage(prefixed_storage_key.as_slice())
|
||||
.and_then(|k| Decode::decode(&mut &k[..]).ok())
|
||||
.unwrap_or(
|
||||
empty_child_trie_root::<Layout<H>>()
|
||||
.unwrap_or_else(
|
||||
|| empty_child_trie_root::<Layout<H>>()
|
||||
);
|
||||
trace!(target: "state", "{:04x}: ChildRoot({})(no_change) {}",
|
||||
self.id,
|
||||
|
||||
@@ -109,7 +109,7 @@ where
|
||||
Some(map) => insert_into_memory_db::<H, _>(
|
||||
root,
|
||||
self.backend_storage_mut(),
|
||||
map.clone().into_iter().chain(new_child_roots.into_iter()),
|
||||
map.into_iter().chain(new_child_roots.into_iter()),
|
||||
),
|
||||
None => insert_into_memory_db::<H, _>(
|
||||
root,
|
||||
|
||||
@@ -71,7 +71,7 @@ impl<'a, S, H> ProvingBackendRecorder<'a, S, H>
|
||||
let storage_key = child_info.storage_key();
|
||||
let root = self.storage(storage_key)?
|
||||
.and_then(|r| Decode::decode(&mut &r[..]).ok())
|
||||
.unwrap_or(empty_child_trie_root::<Layout<H>>());
|
||||
.unwrap_or_else(|| empty_child_trie_root::<Layout<H>>());
|
||||
|
||||
let mut read_overlay = S::Overlay::default();
|
||||
let eph = Ephemeral::new(
|
||||
|
||||
@@ -202,7 +202,7 @@ impl<S: TrieBackendStorage<H>, H: Hasher> Backend<H> for TrieBackend<S, H> where
|
||||
let prefixed_storage_key = child_info.prefixed_storage_key();
|
||||
let mut root = match self.storage(prefixed_storage_key.as_slice()) {
|
||||
Ok(value) =>
|
||||
value.and_then(|r| Decode::decode(&mut &r[..]).ok()).unwrap_or(default_root.clone()),
|
||||
value.and_then(|r| Decode::decode(&mut &r[..]).ok()).unwrap_or_else(|| default_root.clone()),
|
||||
Err(e) => {
|
||||
warn!(target: "trie", "Failed to read child storage root: {}", e);
|
||||
default_root.clone()
|
||||
|
||||
@@ -171,7 +171,7 @@ impl<S: TrieBackendStorage<H>, H: Hasher> TrieBackendEssence<S, H> where H::Out:
|
||||
key: &[u8],
|
||||
) -> Result<Option<StorageValue>, String> {
|
||||
let root = self.child_root(child_info)?
|
||||
.unwrap_or(empty_child_trie_root::<Layout<H>>().encode());
|
||||
.unwrap_or_else(|| empty_child_trie_root::<Layout<H>>().encode());
|
||||
|
||||
let map_e = |e| format!("Trie lookup error: {}", e);
|
||||
|
||||
@@ -186,7 +186,7 @@ impl<S: TrieBackendStorage<H>, H: Hasher> TrieBackendEssence<S, H> where H::Out:
|
||||
f: F,
|
||||
) {
|
||||
let root = match self.child_root(child_info) {
|
||||
Ok(v) => v.unwrap_or(empty_child_trie_root::<Layout<H>>().encode()),
|
||||
Ok(v) => v.unwrap_or_else(|| empty_child_trie_root::<Layout<H>>().encode()),
|
||||
Err(e) => {
|
||||
debug!(target: "trie", "Error while iterating child storage: {}", e);
|
||||
return;
|
||||
@@ -211,7 +211,7 @@ impl<S: TrieBackendStorage<H>, H: Hasher> TrieBackendEssence<S, H> where H::Out:
|
||||
mut f: F,
|
||||
) {
|
||||
let root_vec = match self.child_root(child_info) {
|
||||
Ok(v) => v.unwrap_or(empty_child_trie_root::<Layout<H>>().encode()),
|
||||
Ok(v) => v.unwrap_or_else(|| empty_child_trie_root::<Layout<H>>().encode()),
|
||||
Err(e) => {
|
||||
debug!(target: "trie", "Error while iterating child storage: {}", e);
|
||||
return;
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
use sp_std::{
|
||||
vec,
|
||||
borrow::Cow, marker::PhantomData, mem, iter::Iterator, result, vec::Vec,
|
||||
};
|
||||
|
||||
@@ -275,8 +276,7 @@ impl PartialEq for dyn Function {
|
||||
pub trait FunctionContext {
|
||||
/// Read memory from `address` into a vector.
|
||||
fn read_memory(&self, address: Pointer<u8>, size: WordSize) -> Result<Vec<u8>> {
|
||||
let mut vec = Vec::with_capacity(size as usize);
|
||||
vec.resize(size as usize, 0);
|
||||
let mut vec = vec![0; size as usize];
|
||||
self.read_memory_into(address, &mut vec)?;
|
||||
Ok(vec)
|
||||
}
|
||||
|
||||
@@ -348,7 +348,7 @@ pub fn new_light() -> (
|
||||
|
||||
let storage = sc_client_db::light::LightStorage::new_test();
|
||||
let blockchain = Arc::new(sc_light::Blockchain::new(storage));
|
||||
let backend = Arc::new(LightBackend::new(blockchain.clone()));
|
||||
let backend = Arc::new(LightBackend::new(blockchain));
|
||||
let executor = new_native_executor();
|
||||
let local_call_executor = client::LocalCallExecutor::new(backend.clone(), executor, sp_core::tasks::executor(), Default::default());
|
||||
let call_executor = LightExecutor::new(
|
||||
|
||||
@@ -284,7 +284,7 @@ pub fn test_children_for_backend<B: 'static>(backend: Arc<B>) where
|
||||
Default::default(),
|
||||
false,
|
||||
).unwrap().build().unwrap().block;
|
||||
client.import(BlockOrigin::Own, b4.clone()).unwrap();
|
||||
client.import(BlockOrigin::Own, b4).unwrap();
|
||||
|
||||
// // B2 -> C3
|
||||
let mut builder = client.new_block_at(
|
||||
@@ -413,7 +413,7 @@ pub fn test_blockchain_query_by_number_gets_canonical<B: 'static>(backend: Arc<B
|
||||
Default::default(),
|
||||
false,
|
||||
).unwrap().build().unwrap().block;
|
||||
client.import(BlockOrigin::Own, b4.clone()).unwrap();
|
||||
client.import(BlockOrigin::Own, b4).unwrap();
|
||||
|
||||
// // B2 -> C3
|
||||
let mut builder = client.new_block_at(
|
||||
@@ -429,7 +429,7 @@ pub fn test_blockchain_query_by_number_gets_canonical<B: 'static>(backend: Arc<B
|
||||
nonce: 1,
|
||||
}).unwrap();
|
||||
let c3 = builder.build().unwrap().block;
|
||||
client.import(BlockOrigin::Own, c3.clone()).unwrap();
|
||||
client.import(BlockOrigin::Own, c3).unwrap();
|
||||
|
||||
// A1 -> D2
|
||||
let mut builder = client.new_block_at(
|
||||
@@ -445,7 +445,7 @@ pub fn test_blockchain_query_by_number_gets_canonical<B: 'static>(backend: Arc<B
|
||||
nonce: 0,
|
||||
}).unwrap();
|
||||
let d2 = builder.build().unwrap().block;
|
||||
client.import(BlockOrigin::Own, d2.clone()).unwrap();
|
||||
client.import(BlockOrigin::Own, d2).unwrap();
|
||||
|
||||
let genesis_hash = client.chain_info().genesis_hash;
|
||||
|
||||
|
||||
@@ -47,7 +47,7 @@ impl GenesisConfig {
|
||||
) -> Self {
|
||||
GenesisConfig {
|
||||
changes_trie_config,
|
||||
authorities: authorities.clone(),
|
||||
authorities: authorities,
|
||||
balances: endowed_accounts.into_iter().map(|a| (a, balance)).collect(),
|
||||
heap_pages_override,
|
||||
extra_storage,
|
||||
|
||||
@@ -263,7 +263,7 @@ fn adjust_nonce<P, AccountId, Index>(
|
||||
// `provides` tag. And increment the nonce if we find a transaction
|
||||
// that matches the current one.
|
||||
let mut current_nonce = nonce.clone();
|
||||
let mut current_tag = (account.clone(), nonce.clone()).encode();
|
||||
let mut current_tag = (account.clone(), nonce).encode();
|
||||
for tx in pool.ready() {
|
||||
log::debug!(
|
||||
target: "rpc",
|
||||
|
||||
@@ -189,7 +189,7 @@ fn check_skip_build() -> bool {
|
||||
/// Write to the given `file` if the `content` is different.
|
||||
fn write_file_if_changed(file: PathBuf, content: String) {
|
||||
if fs::read_to_string(&file).ok().as_ref() != Some(&content) {
|
||||
fs::write(&file, content).expect(&format!("Writing `{}` can not fail!", file.display()));
|
||||
fs::write(&file, content).unwrap_or_else(|_| panic!("Writing `{}` can not fail!", file.display()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -200,7 +200,7 @@ fn copy_file_if_changed(src: PathBuf, dst: PathBuf) {
|
||||
|
||||
if src_file != dst_file {
|
||||
fs::copy(&src, &dst)
|
||||
.expect(&format!("Copying `{}` to `{}` can not fail; qed", src.display(), dst.display()));
|
||||
.unwrap_or_else(|_| panic!("Copying `{}` to `{}` can not fail; qed", src.display(), dst.display()));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -205,7 +205,7 @@ fn find_and_clear_workspace_members(wasm_workspace: &Path) -> Vec<String> {
|
||||
.map(|d| d.into_path())
|
||||
.filter(|p| p.is_dir())
|
||||
.filter_map(|p| p.file_name().map(|f| f.to_owned()).and_then(|s| s.into_string().ok()))
|
||||
.filter(|f| !f.starts_with(".") && f != "target")
|
||||
.filter(|f| !f.starts_with('.') && f != "target")
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let mut i = 0;
|
||||
|
||||
Reference in New Issue
Block a user