mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-06-09 19:01:08 +00:00
Make clippy _a little_ more annoying (#10570)
* Clippy: +complexity * Update client/cli/src/arg_enums.rs Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com> * Update bin/node/inspect/src/lib.rs Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com> * Update primitives/keystore/src/testing.rs Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com> * Update frame/elections/src/lib.rs Co-authored-by: Keith Yeung <kungfukeith11@gmail.com> * Update primitives/npos-elections/fuzzer/src/reduce.rs Co-authored-by: Keith Yeung <kungfukeith11@gmail.com> * Incorporating feedback * No need for Ok * Additional * Needed slice * Wigy's suggestions on less derefs * fix count * reverting changes brought in by option_map_unit_fn * add --all-targets Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com> Co-authored-by: Keith Yeung <kungfukeith11@gmail.com>
This commit is contained in:
@@ -10,5 +10,24 @@ rustflags = [
|
||||
"-Aclippy::all",
|
||||
"-Dclippy::correctness",
|
||||
"-Aclippy::if-same-then-else",
|
||||
"-Aclippy::clone-double-ref"
|
||||
"-Aclippy::clone-double-ref",
|
||||
"-Dclippy::complexity",
|
||||
"-Aclippy::clone_on_copy", # Too common
|
||||
"-Aclippy::needless_lifetimes", # Backward compat?
|
||||
"-Aclippy::zero-prefixed-literal", # 00_1000_000
|
||||
"-Aclippy::type_complexity", # raison d'etre
|
||||
"-Aclippy::nonminimal-bool", # maybe
|
||||
"-Aclippy::borrowed-box", # Reasonable to fix this one
|
||||
"-Aclippy::too-many-arguments", # (Turning this on would lead to)
|
||||
"-Aclippy::unnecessary_cast", # Types may change
|
||||
"-Aclippy::identity-op", # One case where we do 0 +
|
||||
"-Aclippy::useless_conversion", # Types may change
|
||||
"-Aclippy::unit_arg", # styalistic.
|
||||
"-Aclippy::option-map-unit-fn", # styalistic
|
||||
"-Aclippy::bind_instead_of_map", # styalistic
|
||||
"-Aclippy::erasing_op", # E.g. 0 * DOLLARS
|
||||
"-Aclippy::eq_op", # In tests we test equality.
|
||||
"-Aclippy::while_immutable_condition", # false positives
|
||||
"-Aclippy::needless_option_as_deref", # false positives
|
||||
"-Aclippy::derivable_impls", # false positives
|
||||
]
|
||||
|
||||
@@ -350,7 +350,7 @@ cargo-clippy:
|
||||
<<: *docker-env
|
||||
<<: *test-refs
|
||||
script:
|
||||
- SKIP_WASM_BUILD=1 env -u RUSTFLAGS cargo +nightly clippy
|
||||
- SKIP_WASM_BUILD=1 env -u RUSTFLAGS cargo +nightly clippy --all-targets
|
||||
|
||||
cargo-check-benches:
|
||||
stage: test
|
||||
|
||||
@@ -60,7 +60,7 @@ pub fn new_partial(
|
||||
ServiceError,
|
||||
> {
|
||||
if config.keystore_remote.is_some() {
|
||||
return Err(ServiceError::Other(format!("Remote Keystores are not supported.")))
|
||||
return Err(ServiceError::Other("Remote Keystores are not supported.".into()))
|
||||
}
|
||||
|
||||
let telemetry = config
|
||||
|
||||
@@ -261,7 +261,7 @@ impl<Hash: FromStr + Debug, Number: FromStr + Debug> FromStr for ExtrinsicAddres
|
||||
|
||||
let index = it
|
||||
.next()
|
||||
.ok_or_else(|| format!("Extrinsic index missing: example \"5:0\""))?
|
||||
.ok_or("Extrinsic index missing: example \"5:0\"")?
|
||||
.parse()
|
||||
.map_err(|e| format!("Invalid index format: {}", e))?;
|
||||
|
||||
|
||||
@@ -223,7 +223,7 @@ impl<G, E> ChainSpec<G, E> {
|
||||
|
||||
/// Network protocol id.
|
||||
pub fn protocol_id(&self) -> Option<&str> {
|
||||
self.client_spec.protocol_id.as_ref().map(String::as_str)
|
||||
self.client_spec.protocol_id.as_deref()
|
||||
}
|
||||
|
||||
/// Additional loosly-typed properties of the chain.
|
||||
|
||||
@@ -51,7 +51,7 @@ impl std::str::FromStr for WasmExecutionMethod {
|
||||
}
|
||||
#[cfg(not(feature = "wasmtime"))]
|
||||
{
|
||||
Err(format!("`Compiled` variant requires the `wasmtime` feature to be enabled"))
|
||||
Err("`Compiled` variant requires the `wasmtime` feature to be enabled".into())
|
||||
}
|
||||
} else {
|
||||
Err(format!("Unknown variant `{}`, known variants: {:?}", s, Self::variants()))
|
||||
|
||||
@@ -70,7 +70,7 @@ fn sign<P: sp_core::Pair>(
|
||||
message: Vec<u8>,
|
||||
) -> error::Result<String> {
|
||||
let pair = utils::pair_from_suri::<P>(suri, password)?;
|
||||
Ok(format!("{}", hex::encode(pair.sign(&message))))
|
||||
Ok(hex::encode(pair.sign(&message)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -57,7 +57,7 @@ impl VerifyCmd {
|
||||
let message = utils::read_message(self.message.as_ref(), self.hex)?;
|
||||
let sig_data = utils::decode_hex(&self.sig)?;
|
||||
let uri = utils::read_uri(self.uri.as_ref())?;
|
||||
let uri = if uri.starts_with("0x") { &uri[2..] } else { &uri };
|
||||
let uri = if let Some(uri) = uri.strip_prefix("0x") { uri } else { &uri };
|
||||
|
||||
with_crypto_scheme!(self.crypto_scheme.scheme, verify(sig_data, message, uri))
|
||||
}
|
||||
|
||||
@@ -79,8 +79,8 @@ impl FromStr for BlockNumberOrHash {
|
||||
type Err = String;
|
||||
|
||||
fn from_str(block_number: &str) -> Result<Self, Self::Err> {
|
||||
if block_number.starts_with("0x") {
|
||||
if let Some(pos) = &block_number[2..].chars().position(|c| !c.is_ascii_hexdigit()) {
|
||||
if let Some(rest) = block_number.strip_prefix("0x") {
|
||||
if let Some(pos) = rest.chars().position(|c| !c.is_ascii_hexdigit()) {
|
||||
Err(format!(
|
||||
"Expected block hash, found illegal hex character at position: {}",
|
||||
2 + pos,
|
||||
|
||||
@@ -287,9 +287,9 @@ impl<Block: BlockT, Transaction> BlockImportParams<Block, Transaction> {
|
||||
pub fn take_intermediate<T: 'static>(&mut self, key: &[u8]) -> Result<Box<T>, Error> {
|
||||
let (k, v) = self.intermediates.remove_entry(key).ok_or(Error::NoIntermediate)?;
|
||||
|
||||
v.downcast::<T>().or_else(|v| {
|
||||
v.downcast::<T>().map_err(|v| {
|
||||
self.intermediates.insert(k, v);
|
||||
Err(Error::InvalidIntermediate)
|
||||
Error::InvalidIntermediate
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -279,7 +279,7 @@ where
|
||||
// a quick check to see if we're in the authorities
|
||||
let epoch = self.epoch(parent, slot)?;
|
||||
let (authority, _) = self.authorities.first().expect("authorities is non-emptyp; qed");
|
||||
let has_authority = epoch.authorities.iter().find(|(id, _)| *id == *authority).is_some();
|
||||
let has_authority = epoch.authorities.iter().any(|(id, _)| *id == *authority);
|
||||
|
||||
if !has_authority {
|
||||
log::info!(target: "manual-seal", "authority not found");
|
||||
|
||||
@@ -173,7 +173,7 @@ pub async fn run_manual_seal<B, BI, CB, E, C, TP, SC, CS, CIDP>(
|
||||
env: &mut env,
|
||||
select_chain: &select_chain,
|
||||
block_import: &mut block_import,
|
||||
consensus_data_provider: consensus_data_provider.as_ref().map(|p| &**p),
|
||||
consensus_data_provider: consensus_data_provider.as_deref(),
|
||||
pool: pool.clone(),
|
||||
client: client.clone(),
|
||||
create_inherent_data_providers: &create_inherent_data_providers,
|
||||
@@ -408,8 +408,8 @@ mod tests {
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
// assert that the background task returns ok
|
||||
assert_eq!(rx.await.unwrap().unwrap(), ());
|
||||
// check that the background task returns ok:
|
||||
rx.await.unwrap().unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -672,7 +672,6 @@ mod test {
|
||||
assert_eq!(rw_tracker.1, 0);
|
||||
assert_eq!(rw_tracker.2, 2);
|
||||
assert_eq!(rw_tracker.3, 0);
|
||||
drop(rw_tracker);
|
||||
bench_state.wipe().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1993,7 +1993,7 @@ impl<Block: BlockT> sc_client_api::backend::Backend<Block> for Backend<Block> {
|
||||
});
|
||||
let database_cache = MemorySize::from_bytes(0);
|
||||
let state_cache =
|
||||
MemorySize::from_bytes((*&self.shared_cache).read().used_storage_cache_size());
|
||||
MemorySize::from_bytes(self.shared_cache.read().used_storage_cache_size());
|
||||
let state_db = self.storage.state_db.memory_info();
|
||||
|
||||
Some(UsageInfo {
|
||||
@@ -2452,7 +2452,7 @@ pub(crate) mod tests {
|
||||
let storage = vec![(vec![1, 3, 5], None), (vec![5, 5, 5], Some(vec![4, 5, 6]))];
|
||||
|
||||
let (root, overlay) = op.old_state.storage_root(
|
||||
storage.iter().map(|(k, v)| (&k[..], v.as_ref().map(|v| &v[..]))),
|
||||
storage.iter().map(|(k, v)| (k.as_slice(), v.as_ref().map(|v| &v[..]))),
|
||||
state_version,
|
||||
);
|
||||
op.update_db_storage(overlay).unwrap();
|
||||
@@ -3000,7 +3000,7 @@ pub(crate) mod tests {
|
||||
let storage = vec![(b"test".to_vec(), Some(b"test2".to_vec()))];
|
||||
|
||||
let (root, overlay) = op.old_state.storage_root(
|
||||
storage.iter().map(|(k, v)| (&k[..], v.as_ref().map(|v| &v[..]))),
|
||||
storage.iter().map(|(k, v)| (k.as_slice(), v.as_ref().map(|v| &v[..]))),
|
||||
state_version,
|
||||
);
|
||||
op.update_db_storage(overlay).unwrap();
|
||||
|
||||
@@ -92,7 +92,7 @@ impl sp_core::offchain::OffchainStorage for LocalStorage {
|
||||
{
|
||||
let _key_guard = key_lock.lock();
|
||||
let val = self.db.get(columns::OFFCHAIN, &key);
|
||||
is_set = val.as_ref().map(|x| &**x) == old_value;
|
||||
is_set = val.as_deref() == old_value;
|
||||
|
||||
if is_set {
|
||||
self.set(prefix, item_key, new_value)
|
||||
|
||||
@@ -126,7 +126,7 @@ fn call_in_wasm<E: Externalities>(
|
||||
let executor =
|
||||
crate::WasmExecutor::<HostFunctions>::new(execution_method, Some(1024), 8, None, 2);
|
||||
executor.uncached_call(
|
||||
RuntimeBlob::uncompress_if_needed(&wasm_binary_unwrap()[..]).unwrap(),
|
||||
RuntimeBlob::uncompress_if_needed(wasm_binary_unwrap()).unwrap(),
|
||||
ext,
|
||||
true,
|
||||
function,
|
||||
@@ -479,7 +479,7 @@ fn should_trap_when_heap_exhausted(wasm_method: WasmExecutionMethod) {
|
||||
|
||||
let err = executor
|
||||
.uncached_call(
|
||||
RuntimeBlob::uncompress_if_needed(&wasm_binary_unwrap()[..]).unwrap(),
|
||||
RuntimeBlob::uncompress_if_needed(wasm_binary_unwrap()).unwrap(),
|
||||
&mut ext.ext(),
|
||||
true,
|
||||
"test_exhaust_heap",
|
||||
@@ -491,7 +491,7 @@ fn should_trap_when_heap_exhausted(wasm_method: WasmExecutionMethod) {
|
||||
}
|
||||
|
||||
fn mk_test_runtime(wasm_method: WasmExecutionMethod, pages: u64) -> Arc<dyn WasmModule> {
|
||||
let blob = RuntimeBlob::uncompress_if_needed(&wasm_binary_unwrap()[..])
|
||||
let blob = RuntimeBlob::uncompress_if_needed(wasm_binary_unwrap())
|
||||
.expect("failed to create a runtime blob out of test runtime");
|
||||
|
||||
crate::wasm_runtime::create_wasm_runtime_with_code::<HostFunctions>(
|
||||
@@ -597,7 +597,7 @@ fn parallel_execution(wasm_method: WasmExecutionMethod) {
|
||||
assert_eq!(
|
||||
executor
|
||||
.uncached_call(
|
||||
RuntimeBlob::uncompress_if_needed(&wasm_binary_unwrap()[..]).unwrap(),
|
||||
RuntimeBlob::uncompress_if_needed(wasm_binary_unwrap()).unwrap(),
|
||||
&mut ext,
|
||||
true,
|
||||
"test_twox_128",
|
||||
@@ -691,7 +691,7 @@ fn panic_in_spawned_instance_panics_on_joining_its_result(wasm_method: WasmExecu
|
||||
let error_result =
|
||||
call_in_wasm("test_panic_in_spawned", &[], wasm_method, &mut ext).unwrap_err();
|
||||
|
||||
assert!(format!("{}", error_result).contains("Spawned task"));
|
||||
assert!(error_result.contains("Spawned task"));
|
||||
}
|
||||
|
||||
test_wasm_execution!(memory_is_cleared_between_invocations);
|
||||
|
||||
@@ -82,7 +82,7 @@ mod tests {
|
||||
);
|
||||
let res = executor
|
||||
.uncached_call(
|
||||
RuntimeBlob::uncompress_if_needed(&wasm_binary_unwrap()[..]).unwrap(),
|
||||
RuntimeBlob::uncompress_if_needed(wasm_binary_unwrap()).unwrap(),
|
||||
&mut ext,
|
||||
true,
|
||||
"test_empty_return",
|
||||
|
||||
@@ -77,7 +77,7 @@ struct VersionedRuntime {
|
||||
|
||||
impl VersionedRuntime {
|
||||
/// Run the given closure `f` with an instance of this runtime.
|
||||
fn with_instance<'c, R, F>(&self, ext: &mut dyn Externalities, f: F) -> Result<R, Error>
|
||||
fn with_instance<R, F>(&self, ext: &mut dyn Externalities, f: F) -> Result<R, Error>
|
||||
where
|
||||
F: FnOnce(
|
||||
&Arc<dyn WasmModule>,
|
||||
|
||||
@@ -195,7 +195,7 @@ impl<'a> Sandbox for HostContext<'a> {
|
||||
&mut self,
|
||||
instance_id: u32,
|
||||
export_name: &str,
|
||||
args: &[u8],
|
||||
mut args: &[u8],
|
||||
return_val: Pointer<u8>,
|
||||
return_val_len: u32,
|
||||
state: u32,
|
||||
@@ -203,7 +203,7 @@ impl<'a> Sandbox for HostContext<'a> {
|
||||
trace!(target: "sp-sandbox", "invoke, instance_idx={}", instance_id);
|
||||
|
||||
// Deserialize arguments and convert them into wasmi types.
|
||||
let args = Vec::<sp_wasm_interface::Value>::decode(&mut &args[..])
|
||||
let args = Vec::<sp_wasm_interface::Value>::decode(&mut args)
|
||||
.map_err(|_| "Can't decode serialized arguments for the invocation")?
|
||||
.into_iter()
|
||||
.map(Into::into)
|
||||
|
||||
@@ -313,7 +313,7 @@ fn test_max_memory_pages() {
|
||||
#[test]
|
||||
fn test_instances_without_reuse_are_not_leaked() {
|
||||
let runtime = crate::create_runtime::<HostFunctions>(
|
||||
RuntimeBlob::uncompress_if_needed(&wasm_binary_unwrap()[..]).unwrap(),
|
||||
RuntimeBlob::uncompress_if_needed(wasm_binary_unwrap()).unwrap(),
|
||||
crate::Config {
|
||||
heap_pages: 2048,
|
||||
max_memory_size: None,
|
||||
|
||||
@@ -615,8 +615,7 @@ impl<N: Ord> Peers<N> {
|
||||
// `LUCKY_PEERS / 2` is filled we start allocating to the second stage set.
|
||||
let half_lucky = LUCKY_PEERS / 2;
|
||||
let one_and_a_half_lucky = LUCKY_PEERS + half_lucky;
|
||||
let mut n_authorities_added = 0;
|
||||
for peer_id in shuffled_authorities {
|
||||
for (n_authorities_added, peer_id) in shuffled_authorities.enumerate() {
|
||||
if n_authorities_added < half_lucky {
|
||||
first_stage_peers.insert(*peer_id);
|
||||
} else if n_authorities_added < one_and_a_half_lucky {
|
||||
@@ -624,8 +623,6 @@ impl<N: Ord> Peers<N> {
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
n_authorities_added += 1;
|
||||
}
|
||||
|
||||
// fill up first and second sets with remaining peers (either full or authorities)
|
||||
|
||||
@@ -267,7 +267,7 @@ pub struct Config {
|
||||
|
||||
impl Config {
|
||||
fn name(&self) -> &str {
|
||||
self.name.as_ref().map(|s| s.as_str()).unwrap_or("<unknown>")
|
||||
self.name.as_deref().unwrap_or("<unknown>")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -441,10 +441,7 @@ where
|
||||
keys: Option<Vec<StorageKey>>,
|
||||
) {
|
||||
let keys = Into::<Option<Vec<_>>>::into(keys);
|
||||
let stream = match self
|
||||
.client
|
||||
.storage_changes_notification_stream(keys.as_ref().map(|x| &**x), None)
|
||||
{
|
||||
let stream = match self.client.storage_changes_notification_stream(keys.as_deref(), None) {
|
||||
Ok(stream) => stream,
|
||||
Err(err) => {
|
||||
let _ = subscriber.reject(client_err(err).into());
|
||||
|
||||
@@ -32,7 +32,7 @@ use substrate_test_runtime_client::{prelude::*, runtime};
|
||||
const STORAGE_KEY: &[u8] = b"child";
|
||||
|
||||
fn prefixed_storage_key() -> PrefixedStorageKey {
|
||||
let child_info = ChildInfo::new_default(&STORAGE_KEY[..]);
|
||||
let child_info = ChildInfo::new_default(STORAGE_KEY);
|
||||
child_info.prefixed_storage_key()
|
||||
}
|
||||
|
||||
|
||||
@@ -354,26 +354,26 @@ fn test_add_reset_log_filter() {
|
||||
};
|
||||
|
||||
// Initiate logs loop in child process
|
||||
child_in.write(b"\n").unwrap();
|
||||
child_in.write_all(b"\n").unwrap();
|
||||
assert!(read_line().contains(EXPECTED_BEFORE_ADD));
|
||||
|
||||
// Initiate add directive & reload in child process
|
||||
child_in.write(b"add_reload\n").unwrap();
|
||||
child_in.write_all(b"add_reload\n").unwrap();
|
||||
assert!(read_line().contains(EXPECTED_BEFORE_ADD));
|
||||
assert!(read_line().contains(EXPECTED_AFTER_ADD));
|
||||
|
||||
// Check that increasing the max log level works
|
||||
child_in.write(b"add_trace\n").unwrap();
|
||||
child_in.write_all(b"add_trace\n").unwrap();
|
||||
assert!(read_line().contains(EXPECTED_WITH_TRACE));
|
||||
assert!(read_line().contains(EXPECTED_BEFORE_ADD));
|
||||
assert!(read_line().contains(EXPECTED_AFTER_ADD));
|
||||
|
||||
// Initiate logs filter reset in child process
|
||||
child_in.write(b"reset\n").unwrap();
|
||||
child_in.write_all(b"reset\n").unwrap();
|
||||
assert!(read_line().contains(EXPECTED_BEFORE_ADD));
|
||||
|
||||
// Return from child process
|
||||
child_in.write(b"exit\n").unwrap();
|
||||
child_in.write_all(b"exit\n").unwrap();
|
||||
assert!(child_process.wait().expect("Error waiting for child process").success());
|
||||
|
||||
// Check for EOF
|
||||
|
||||
@@ -363,7 +363,7 @@ where
|
||||
spawn_handle,
|
||||
config.clone(),
|
||||
)?;
|
||||
Ok(crate::client::Client::new(
|
||||
crate::client::Client::new(
|
||||
backend,
|
||||
executor,
|
||||
genesis_storage,
|
||||
@@ -373,7 +373,7 @@ where
|
||||
prometheus_registry,
|
||||
telemetry,
|
||||
config,
|
||||
)?)
|
||||
)
|
||||
}
|
||||
|
||||
/// Parameters to pass into `build`.
|
||||
|
||||
@@ -266,9 +266,7 @@ where
|
||||
&runtime_code,
|
||||
self.spawn_handle.clone(),
|
||||
)
|
||||
.with_storage_transaction_cache(
|
||||
storage_transaction_cache.as_mut().map(|c| &mut **c),
|
||||
)
|
||||
.with_storage_transaction_cache(storage_transaction_cache.as_deref_mut())
|
||||
.set_parent_hash(at_hash);
|
||||
state_machine.execute_using_consensus_failure_handler(
|
||||
execution_manager,
|
||||
|
||||
@@ -1409,10 +1409,9 @@ where
|
||||
id: &BlockId<Block>,
|
||||
key: &StorageKey,
|
||||
) -> sp_blockchain::Result<Option<Block::Hash>> {
|
||||
Ok(self
|
||||
.state_at(id)?
|
||||
self.state_at(id)?
|
||||
.storage_hash(&key.0)
|
||||
.map_err(|e| sp_blockchain::Error::from_state(Box::new(e)))?)
|
||||
.map_err(|e| sp_blockchain::Error::from_state(Box::new(e)))
|
||||
}
|
||||
|
||||
fn child_storage_keys(
|
||||
@@ -1449,10 +1448,9 @@ where
|
||||
child_info: &ChildInfo,
|
||||
key: &StorageKey,
|
||||
) -> sp_blockchain::Result<Option<Block::Hash>> {
|
||||
Ok(self
|
||||
.state_at(id)?
|
||||
self.state_at(id)?
|
||||
.child_storage_hash(child_info, &key.0)
|
||||
.map_err(|e| sp_blockchain::Error::from_state(Box::new(e)))?)
|
||||
.map_err(|e| sp_blockchain::Error::from_state(Box::new(e)))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -134,12 +134,12 @@ fn discard_descendants<BlockHash: Hash, Key: Hash>(
|
||||
hash: &BlockHash,
|
||||
) -> u32 {
|
||||
let (first, mut remainder) = if let Some((first, rest)) = levels.0.split_first_mut() {
|
||||
(Some(first), (rest, &mut levels.1[..]))
|
||||
(Some(first), (rest, &mut *levels.1))
|
||||
} else {
|
||||
if let Some((first, rest)) = levels.1.split_first_mut() {
|
||||
(Some(first), (&mut levels.0[..], rest))
|
||||
(Some(first), (&mut *levels.0, rest))
|
||||
} else {
|
||||
(None, (&mut levels.0[..], &mut levels.1[..]))
|
||||
(None, (&mut *levels.0, &mut *levels.1))
|
||||
}
|
||||
};
|
||||
let mut pinned_children = 0;
|
||||
@@ -261,8 +261,7 @@ impl<BlockHash: Hash, Key: Hash> NonCanonicalOverlay<BlockHash, Key> {
|
||||
.push((to_meta_key(LAST_CANONICAL, &()), last_canonicalized.encode()));
|
||||
self.last_canonicalized = Some(last_canonicalized);
|
||||
} else if self.last_canonicalized.is_some() {
|
||||
if number < front_block_number ||
|
||||
number >= front_block_number + self.levels.len() as u64 + 1
|
||||
if number < front_block_number || number > front_block_number + self.levels.len() as u64
|
||||
{
|
||||
trace!(target: "state-db", "Failed to insert block {}, current is {} .. {})",
|
||||
number,
|
||||
|
||||
@@ -119,7 +119,7 @@ pub fn prefix_logs_with(arg: TokenStream, item: TokenStream) -> TokenStream {
|
||||
let name = syn::parse_macro_input!(arg as Expr);
|
||||
|
||||
let crate_name = match crate_name("sc-tracing") {
|
||||
Ok(FoundCrate::Itself) => Ident::from(Ident::new("sc_tracing", Span::call_site())),
|
||||
Ok(FoundCrate::Itself) => Ident::new("sc_tracing", Span::call_site()),
|
||||
Ok(FoundCrate::Name(crate_name)) => Ident::new(&crate_name, Span::call_site()),
|
||||
Err(e) => return Error::new(Span::call_site(), e).to_compile_error().into(),
|
||||
};
|
||||
|
||||
@@ -267,7 +267,7 @@ where
|
||||
.lock()
|
||||
.drain()
|
||||
// Patch wasm identifiers
|
||||
.filter_map(|(_, s)| patch_and_filter(SpanDatum::from(s), targets))
|
||||
.filter_map(|(_, s)| patch_and_filter(s, targets))
|
||||
.collect();
|
||||
let events: Vec<_> = block_subscriber
|
||||
.events
|
||||
@@ -315,7 +315,7 @@ fn event_values_filter(event: &TraceEvent, filter_kind: &str, values: &str) -> b
|
||||
.values
|
||||
.string_values
|
||||
.get(filter_kind)
|
||||
.and_then(|value| Some(check_target(values, value, &event.level)))
|
||||
.map(|value| check_target(values, value, &event.level))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
|
||||
@@ -464,7 +464,10 @@ impl From<SpanDatum> for sp_rpc::tracing::Span {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use parking_lot::Mutex;
|
||||
use std::sync::Arc;
|
||||
use std::sync::{
|
||||
mpsc::{Receiver, Sender},
|
||||
Arc,
|
||||
};
|
||||
use tracing_subscriber::layer::SubscriberExt;
|
||||
|
||||
struct TestTraceHandler {
|
||||
@@ -617,14 +620,14 @@ mod tests {
|
||||
let span1 = tracing::info_span!(target: "test_target", "test_span1");
|
||||
let _guard1 = span1.enter();
|
||||
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let (tx, rx): (Sender<bool>, Receiver<bool>) = mpsc::channel();
|
||||
let handle = thread::spawn(move || {
|
||||
let span2 = tracing::info_span!(target: "test_target", "test_span2");
|
||||
let _guard2 = span2.enter();
|
||||
// emit event
|
||||
tracing::event!(target: "test_target", tracing::Level::INFO, "test_event1");
|
||||
for msg in rx.recv() {
|
||||
if msg == false {
|
||||
if !msg {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
@@ -224,12 +224,8 @@ impl<B: ChainApi> Pool<B> {
|
||||
hashes: &[ExtrinsicHash<B>],
|
||||
) -> Result<(), B::Error> {
|
||||
// Get details of all extrinsics that are already in the pool
|
||||
let in_pool_tags = self
|
||||
.validated_pool
|
||||
.extrinsics_tags(hashes)
|
||||
.into_iter()
|
||||
.filter_map(|x| x)
|
||||
.flatten();
|
||||
let in_pool_tags =
|
||||
self.validated_pool.extrinsics_tags(hashes).into_iter().flatten().flatten();
|
||||
|
||||
// Prune all transactions that provide given tags
|
||||
let prune_status = self.validated_pool.prune_tags(in_pool_tags)?;
|
||||
|
||||
@@ -61,17 +61,12 @@ pub mod pallet {
|
||||
pub(super) type NextKeys<T: Config> =
|
||||
StorageValue<_, WeakBoundedVec<AuthorityId, T::MaxAuthorities>, ValueQuery>;
|
||||
|
||||
#[cfg_attr(feature = "std", derive(Default))]
|
||||
#[pallet::genesis_config]
|
||||
pub struct GenesisConfig {
|
||||
pub keys: Vec<AuthorityId>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl Default for GenesisConfig {
|
||||
fn default() -> Self {
|
||||
Self { keys: Default::default() }
|
||||
}
|
||||
}
|
||||
#[pallet::genesis_build]
|
||||
impl<T: Config> GenesisBuild<T> for GenesisConfig {
|
||||
fn build(&self) {
|
||||
|
||||
@@ -479,9 +479,9 @@ mod tests {
|
||||
where
|
||||
I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,
|
||||
{
|
||||
for (id, data) in digests {
|
||||
for (id, mut data) in digests {
|
||||
if id == TEST_ID {
|
||||
return u64::decode(&mut &data[..]).ok()
|
||||
return u64::decode(&mut data).ok()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -499,9 +499,9 @@ mod tests {
|
||||
let author =
|
||||
AuthorGiven::find_author(pre_runtime_digests).ok_or_else(|| "no author")?;
|
||||
|
||||
for (id, seal) in seals {
|
||||
for (id, mut seal) in seals {
|
||||
if id == TEST_ID {
|
||||
match u64::decode(&mut &seal[..]) {
|
||||
match u64::decode(&mut seal) {
|
||||
Err(_) => return Err("wrong seal"),
|
||||
Ok(a) => {
|
||||
if a != author {
|
||||
|
||||
@@ -310,19 +310,13 @@ pub mod pallet {
|
||||
#[pallet::storage]
|
||||
pub(super) type NextEpochConfig<T> = StorageValue<_, BabeEpochConfiguration>;
|
||||
|
||||
#[cfg_attr(feature = "std", derive(Default))]
|
||||
#[pallet::genesis_config]
|
||||
pub struct GenesisConfig {
|
||||
pub authorities: Vec<(AuthorityId, BabeAuthorityWeight)>,
|
||||
pub epoch_config: Option<BabeEpochConfiguration>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl Default for GenesisConfig {
|
||||
fn default() -> Self {
|
||||
GenesisConfig { authorities: Default::default(), epoch_config: Default::default() }
|
||||
}
|
||||
}
|
||||
|
||||
#[pallet::genesis_build]
|
||||
impl<T: Config> GenesisBuild<T> for GenesisConfig {
|
||||
fn build(&self) {
|
||||
|
||||
@@ -742,7 +742,7 @@ impl<T: Config> Bag<T> {
|
||||
/// Check if the bag contains a node with `id`.
|
||||
#[cfg(feature = "std")]
|
||||
fn contains(&self, id: &T::AccountId) -> bool {
|
||||
self.iter().find(|n| n.id() == id).is_some()
|
||||
self.iter().any(|n| n.id() == id)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -409,12 +409,7 @@ pub mod pallet {
|
||||
let reducible_balance = Self::reducible_balance(&transactor, keep_alive);
|
||||
let dest = T::Lookup::lookup(dest)?;
|
||||
let keep_alive = if keep_alive { KeepAlive } else { AllowDeath };
|
||||
<Self as Currency<_>>::transfer(
|
||||
&transactor,
|
||||
&dest,
|
||||
reducible_balance,
|
||||
keep_alive.into(),
|
||||
)?;
|
||||
<Self as Currency<_>>::transfer(&transactor, &dest, reducible_balance, keep_alive)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -619,7 +614,7 @@ pub enum Reasons {
|
||||
|
||||
impl From<WithdrawReasons> for Reasons {
|
||||
fn from(r: WithdrawReasons) -> Reasons {
|
||||
if r == WithdrawReasons::from(WithdrawReasons::TRANSACTION_PAYMENT) {
|
||||
if r == WithdrawReasons::TRANSACTION_PAYMENT {
|
||||
Reasons::Fee
|
||||
} else if r.contains(WithdrawReasons::TRANSACTION_PAYMENT) {
|
||||
Reasons::All
|
||||
|
||||
@@ -592,8 +592,7 @@ mod tests {
|
||||
contract: BOB,
|
||||
amount: Deposit::Charge(<Test as Config>::Currency::minimum_balance() * 2),
|
||||
terminated: false,
|
||||
}],
|
||||
..Default::default()
|
||||
}]
|
||||
}
|
||||
)
|
||||
});
|
||||
@@ -663,8 +662,7 @@ mod tests {
|
||||
amount: Deposit::Charge(2),
|
||||
terminated: false
|
||||
}
|
||||
],
|
||||
..Default::default()
|
||||
]
|
||||
}
|
||||
)
|
||||
});
|
||||
@@ -717,8 +715,7 @@ mod tests {
|
||||
amount: Deposit::Charge(12),
|
||||
terminated: false
|
||||
}
|
||||
],
|
||||
..Default::default()
|
||||
]
|
||||
}
|
||||
)
|
||||
});
|
||||
|
||||
@@ -1592,7 +1592,7 @@ define_env!(Env, <E: Ext>,
|
||||
output_len_ptr: u32
|
||||
) -> u32 => {
|
||||
use crate::chain_extension::{ChainExtension, Environment, RetVal};
|
||||
if <E::T as Config>::ChainExtension::enabled() == false {
|
||||
if !<E::T as Config>::ChainExtension::enabled() {
|
||||
Err(Error::<E::T>::NoChainExtension)?;
|
||||
}
|
||||
let env = Environment::new(ctx, input_ptr, input_len, output_ptr, output_len_ptr);
|
||||
|
||||
@@ -544,7 +544,7 @@ impl<T: Config> Pallet<T> {
|
||||
|
||||
// Time to finish. We might have reduced less than expected due to rounding error. Increase
|
||||
// one last time if we have any room left, the reduce until we are sure we are below limit.
|
||||
while voters + 1 <= max_voters && weight_with(voters + 1) < max_weight {
|
||||
while voters < max_voters && weight_with(voters + 1) < max_weight {
|
||||
voters += 1;
|
||||
}
|
||||
while voters.checked_sub(1).is_some() && weight_with(voters) > max_weight {
|
||||
|
||||
@@ -836,7 +836,7 @@ impl<T: Config> Pallet<T> {
|
||||
|
||||
/// Check if `who` is currently an active runner-up.
|
||||
fn is_runner_up(who: &T::AccountId) -> bool {
|
||||
Self::runners_up().iter().position(|r| &r.who == who).is_some()
|
||||
Self::runners_up().iter().any(|r| &r.who == who)
|
||||
}
|
||||
|
||||
/// Get the members' account ids.
|
||||
|
||||
@@ -738,7 +738,7 @@ where
|
||||
info: &DispatchInfoOf<Self::Call>,
|
||||
len: usize,
|
||||
) -> Result<Self::Pre, TransactionValidityError> {
|
||||
Ok(self.validate(who, call, info, len).map(|_| ())?)
|
||||
self.validate(who, call, info, len).map(|_| ())
|
||||
}
|
||||
|
||||
fn validate(
|
||||
|
||||
@@ -327,18 +327,12 @@ pub mod pallet {
|
||||
#[pallet::getter(fn session_for_set)]
|
||||
pub(super) type SetIdSession<T: Config> = StorageMap<_, Twox64Concat, SetId, SessionIndex>;
|
||||
|
||||
#[cfg_attr(feature = "std", derive(Default))]
|
||||
#[pallet::genesis_config]
|
||||
pub struct GenesisConfig {
|
||||
pub authorities: AuthorityList,
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl Default for GenesisConfig {
|
||||
fn default() -> Self {
|
||||
Self { authorities: Default::default() }
|
||||
}
|
||||
}
|
||||
|
||||
#[pallet::genesis_build]
|
||||
impl<T: Config> GenesisBuild<T> for GenesisConfig {
|
||||
fn build(&self) {
|
||||
|
||||
@@ -341,7 +341,7 @@ fn should_not_send_a_report_if_already_online() {
|
||||
UintAuthorityId::set_all_keys(vec![1, 2, 3]);
|
||||
// we expect error, since the authority is already online.
|
||||
let mut res = ImOnline::send_heartbeats(4).unwrap();
|
||||
assert_eq!(res.next().unwrap().unwrap(), ());
|
||||
res.next().unwrap().unwrap();
|
||||
assert_eq!(res.next().unwrap().unwrap_err(), OffchainErr::AlreadyOnline(1));
|
||||
assert_eq!(res.next().unwrap().unwrap_err(), OffchainErr::AlreadyOnline(2));
|
||||
assert_eq!(res.next(), None);
|
||||
|
||||
@@ -153,7 +153,6 @@ pub fn new_test_ext() -> sp_io::TestExternalities {
|
||||
pallet_scored_pool::GenesisConfig::<Test> {
|
||||
pool: vec![(5, None), (10, Some(1)), (20, Some(2)), (31, Some(2)), (40, Some(3))],
|
||||
member_count: 2,
|
||||
..Default::default()
|
||||
}
|
||||
.assimilate_storage(&mut t)
|
||||
.unwrap();
|
||||
|
||||
@@ -480,11 +480,11 @@ pub mod pallet {
|
||||
let queued_keys: Vec<_> = initial_validators_1
|
||||
.iter()
|
||||
.cloned()
|
||||
.filter_map(|v| {
|
||||
Some((
|
||||
.map(|v| {
|
||||
(
|
||||
v.clone(),
|
||||
Pallet::<T>::load_keys(&v).expect("Validator in session 1 missing keys!"),
|
||||
))
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
|
||||
|
||||
@@ -1290,7 +1290,7 @@ fn pick_item<'a, R: RngCore, T>(rng: &mut R, items: &'a [T]) -> Option<&'a T> {
|
||||
}
|
||||
|
||||
/// Pick a new PRN, in the range [0, `max`] (inclusive).
|
||||
fn pick_usize<'a, R: RngCore>(rng: &mut R, max: usize) -> usize {
|
||||
fn pick_usize<R: RngCore>(rng: &mut R, max: usize) -> usize {
|
||||
(rng.next_u32() % (max as u32 + 1)) as usize
|
||||
}
|
||||
|
||||
@@ -1316,9 +1316,9 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
|
||||
// Skip ahead to the suggested position
|
||||
.skip(pos)
|
||||
// Keep skipping ahead until the position changes
|
||||
.skip_while(|(_, x)| x.value <= bids[pos].value)
|
||||
// Get the element when things changed
|
||||
.next();
|
||||
.find(|(_, x)| x.value > bids[pos].value);
|
||||
|
||||
// If the element is not at the end of the list, insert the new element
|
||||
// in the spot.
|
||||
if let Some((p, _)) = different_bid {
|
||||
@@ -1351,7 +1351,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
|
||||
/// Check a user is a bid.
|
||||
fn is_bid(bids: &Vec<Bid<T::AccountId, BalanceOf<T, I>>>, who: &T::AccountId) -> bool {
|
||||
// Bids are ordered by `value`, so we cannot binary search for a user.
|
||||
bids.iter().find(|bid| bid.who == *who).is_some()
|
||||
bids.iter().any(|bid| bid.who == *who)
|
||||
}
|
||||
|
||||
/// Check a user is a candidate.
|
||||
|
||||
@@ -412,7 +412,7 @@ impl<AccountId> Default for RewardDestination<AccountId> {
|
||||
}
|
||||
|
||||
/// Preference of what happens regarding validation.
|
||||
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, TypeInfo)]
|
||||
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, TypeInfo, Default)]
|
||||
pub struct ValidatorPrefs {
|
||||
/// Reward that validator takes up-front; only the rest is split between themselves and
|
||||
/// nominators.
|
||||
@@ -424,12 +424,6 @@ pub struct ValidatorPrefs {
|
||||
pub blocked: bool,
|
||||
}
|
||||
|
||||
impl Default for ValidatorPrefs {
|
||||
fn default() -> Self {
|
||||
ValidatorPrefs { commission: Default::default(), blocked: false }
|
||||
}
|
||||
}
|
||||
|
||||
/// Just a Balance/BlockNumber tuple to encode when a chunk of funds will be unlocked.
|
||||
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, TypeInfo)]
|
||||
pub struct UnlockChunk<Balance: HasCompact> {
|
||||
|
||||
@@ -224,7 +224,7 @@ impl<T: Config> Pallet<T> {
|
||||
let dest = Self::payee(stash);
|
||||
match dest {
|
||||
RewardDestination::Controller => Self::bonded(stash)
|
||||
.and_then(|controller| Some(T::Currency::deposit_creating(&controller, amount))),
|
||||
.map(|controller| T::Currency::deposit_creating(&controller, amount)),
|
||||
RewardDestination::Stash => T::Currency::deposit_into_existing(stash, amount).ok(),
|
||||
RewardDestination::Staked => Self::bonded(stash)
|
||||
.and_then(|c| Self::ledger(&c).map(|l| (c, l)))
|
||||
@@ -1160,7 +1160,7 @@ where
|
||||
add_db_reads_writes(1, 0);
|
||||
|
||||
// Reverse because it's more likely to find reports from recent eras.
|
||||
match eras.iter().rev().filter(|&&(_, ref sesh)| sesh <= &slash_session).next() {
|
||||
match eras.iter().rev().find(|&&(_, ref sesh)| sesh <= &slash_session) {
|
||||
Some(&(ref slash_era, _)) => *slash_era,
|
||||
// Before bonding period. defensive - should be filtered out.
|
||||
None => return consumed_weight,
|
||||
|
||||
@@ -2262,7 +2262,7 @@ fn slash_in_old_span_does_not_deselect() {
|
||||
);
|
||||
|
||||
// the validator doesn't get chilled again
|
||||
assert!(<Staking as Store>::Validators::iter().find(|(stash, _)| *stash == 11).is_some());
|
||||
assert!(<Staking as Store>::Validators::iter().any(|(stash, _)| stash == 11));
|
||||
|
||||
// but we are still forcing a new era
|
||||
assert_eq!(Staking::force_era(), Forcing::ForceNew);
|
||||
@@ -2279,7 +2279,7 @@ fn slash_in_old_span_does_not_deselect() {
|
||||
);
|
||||
|
||||
// the validator doesn't get chilled again
|
||||
assert!(<Staking as Store>::Validators::iter().find(|(stash, _)| *stash == 11).is_some());
|
||||
assert!(<Staking as Store>::Validators::iter().any(|(stash, _)| stash == 11));
|
||||
|
||||
// but it's disabled
|
||||
assert!(is_disabled(10));
|
||||
@@ -4003,8 +4003,7 @@ mod election_data_provider {
|
||||
assert!(<Validators<Test>>::iter().map(|(x, _)| x).all(|v| Staking::voters(None)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.find(|(w, _, t)| { v == *w && t[0] == *w })
|
||||
.is_some()))
|
||||
.any(|(w, _, t)| { v == w && t[0] == w })))
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -704,11 +704,11 @@ impl StorageDef {
|
||||
})
|
||||
.unwrap_or(Some(QueryKind::OptionQuery)); // This value must match the default generic.
|
||||
|
||||
if query_kind.is_none() && getter.is_some() {
|
||||
if let (None, Some(getter)) = (query_kind.as_ref(), getter.as_ref()) {
|
||||
let msg = "Invalid pallet::storage, cannot generate getter because QueryKind is not \
|
||||
identifiable. QueryKind must be `OptionQuery`, `ValueQuery`, or default one to be \
|
||||
identifiable.";
|
||||
return Err(syn::Error::new(getter.unwrap().span(), msg))
|
||||
return Err(syn::Error::new(getter.span(), msg))
|
||||
}
|
||||
|
||||
Ok(StorageDef {
|
||||
|
||||
@@ -1546,7 +1546,7 @@ macro_rules! decl_module {
|
||||
<Self as $crate::traits::GetStorageVersion>::current_storage_version(),
|
||||
);
|
||||
|
||||
(|| { $( $impl )* })()
|
||||
{ $( $impl )* }
|
||||
}
|
||||
|
||||
#[cfg(feature = "try-runtime")]
|
||||
|
||||
@@ -181,8 +181,8 @@ pub fn storage_iter_with_suffix<T: Decode + Sized>(
|
||||
prefix.extend_from_slice(&storage_prefix);
|
||||
prefix.extend_from_slice(suffix);
|
||||
let previous_key = prefix.clone();
|
||||
let closure = |raw_key_without_prefix: &[u8], raw_value: &[u8]| {
|
||||
let value = T::decode(&mut &raw_value[..])?;
|
||||
let closure = |raw_key_without_prefix: &[u8], mut raw_value: &[u8]| {
|
||||
let value = T::decode(&mut raw_value)?;
|
||||
Ok((raw_key_without_prefix.to_vec(), value))
|
||||
};
|
||||
|
||||
@@ -213,10 +213,10 @@ pub fn storage_key_iter_with_suffix<
|
||||
prefix.extend_from_slice(&storage_prefix);
|
||||
prefix.extend_from_slice(suffix);
|
||||
let previous_key = prefix.clone();
|
||||
let closure = |raw_key_without_prefix: &[u8], raw_value: &[u8]| {
|
||||
let closure = |raw_key_without_prefix: &[u8], mut raw_value: &[u8]| {
|
||||
let mut key_material = H::reverse(raw_key_without_prefix);
|
||||
let key = K::decode(&mut key_material)?;
|
||||
let value = T::decode(&mut &raw_value[..])?;
|
||||
let value = T::decode(&mut raw_value)?;
|
||||
Ok((key, value))
|
||||
};
|
||||
PrefixIterator { prefix, previous_key, drain: false, closure, phantom: Default::default() }
|
||||
|
||||
@@ -1018,8 +1018,8 @@ impl<T: Decode + Sized> ChildTriePrefixIterator<(Vec<u8>, T)> {
|
||||
pub fn with_prefix(child_info: &ChildInfo, prefix: &[u8]) -> Self {
|
||||
let prefix = prefix.to_vec();
|
||||
let previous_key = prefix.clone();
|
||||
let closure = |raw_key_without_prefix: &[u8], raw_value: &[u8]| {
|
||||
let value = T::decode(&mut &raw_value[..])?;
|
||||
let closure = |raw_key_without_prefix: &[u8], mut raw_value: &[u8]| {
|
||||
let value = T::decode(&mut raw_value)?;
|
||||
Ok((raw_key_without_prefix.to_vec(), value))
|
||||
};
|
||||
|
||||
@@ -1045,10 +1045,10 @@ impl<K: Decode + Sized, T: Decode + Sized> ChildTriePrefixIterator<(K, T)> {
|
||||
) -> Self {
|
||||
let prefix = prefix.to_vec();
|
||||
let previous_key = prefix.clone();
|
||||
let closure = |raw_key_without_prefix: &[u8], raw_value: &[u8]| {
|
||||
let closure = |raw_key_without_prefix: &[u8], mut raw_value: &[u8]| {
|
||||
let mut key_material = H::reverse(raw_key_without_prefix);
|
||||
let key = K::decode(&mut key_material)?;
|
||||
let value = T::decode(&mut &raw_value[..])?;
|
||||
let value = T::decode(&mut raw_value)?;
|
||||
Ok((key, value))
|
||||
};
|
||||
|
||||
|
||||
@@ -30,15 +30,9 @@ pub mod pallet {
|
||||
pub trait Config: frame_system::Config {}
|
||||
|
||||
#[pallet::genesis_config]
|
||||
#[cfg_attr(feature = "std", derive(Default))]
|
||||
pub struct GenesisConfig {}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl Default for GenesisConfig {
|
||||
fn default() -> Self {
|
||||
Self {}
|
||||
}
|
||||
}
|
||||
|
||||
#[pallet::genesis_build]
|
||||
impl<T: Config> GenesisBuild<T> for GenesisConfig {
|
||||
fn build(&self) {}
|
||||
|
||||
@@ -40,5 +40,5 @@ impl Config for Test {}
|
||||
|
||||
#[test]
|
||||
fn init_genesis_config() {
|
||||
GenesisConfig::<Test> { t: Default::default() };
|
||||
GenesisConfig::<Test>::default();
|
||||
}
|
||||
|
||||
@@ -184,7 +184,9 @@ frame_support::construct_runtime!(
|
||||
|
||||
#[test]
|
||||
fn create_genesis_config() {
|
||||
GenesisConfig {
|
||||
let config = GenesisConfig {
|
||||
module: module::GenesisConfig { request_life_time: 0, enable_storage_role: true },
|
||||
};
|
||||
assert_eq!(config.module.request_life_time, 0);
|
||||
assert!(config.module.enable_storage_role);
|
||||
}
|
||||
|
||||
@@ -881,7 +881,7 @@ fn pallet_expand_deposit_event() {
|
||||
|
||||
#[test]
|
||||
fn pallet_new_call_variant() {
|
||||
Call::Example(pallet::Call::new_call_variant_foo(3, 4));
|
||||
pallet::Call::<Runtime>::new_call_variant_foo(3, 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -70,6 +70,6 @@ impl<T: Config + Send + Sync> SignedExtension for CheckGenesis<T> {
|
||||
info: &DispatchInfoOf<Self::Call>,
|
||||
len: usize,
|
||||
) -> Result<Self::Pre, TransactionValidityError> {
|
||||
Ok(self.validate(who, call, info, len).map(|_| ())?)
|
||||
self.validate(who, call, info, len).map(|_| ())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,7 +93,7 @@ impl<T: Config + Send + Sync> SignedExtension for CheckMortality<T> {
|
||||
info: &DispatchInfoOf<Self::Call>,
|
||||
len: usize,
|
||||
) -> Result<Self::Pre, TransactionValidityError> {
|
||||
Ok(self.validate(who, call, info, len).map(|_| ())?)
|
||||
self.validate(who, call, info, len).map(|_| ())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -72,7 +72,7 @@ where
|
||||
info: &DispatchInfoOf<Self::Call>,
|
||||
len: usize,
|
||||
) -> Result<Self::Pre, TransactionValidityError> {
|
||||
Ok(self.validate(who, call, info, len).map(|_| ())?)
|
||||
self.validate(who, call, info, len).map(|_| ())
|
||||
}
|
||||
|
||||
fn validate(
|
||||
|
||||
@@ -70,6 +70,6 @@ impl<T: Config + Send + Sync> SignedExtension for CheckSpecVersion<T> {
|
||||
info: &DispatchInfoOf<Self::Call>,
|
||||
len: usize,
|
||||
) -> Result<Self::Pre, TransactionValidityError> {
|
||||
Ok(self.validate(who, call, info, len).map(|_| ())?)
|
||||
self.validate(who, call, info, len).map(|_| ())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,6 +69,6 @@ impl<T: Config + Send + Sync> SignedExtension for CheckTxVersion<T> {
|
||||
info: &DispatchInfoOf<Self::Call>,
|
||||
len: usize,
|
||||
) -> Result<Self::Pre, TransactionValidityError> {
|
||||
Ok(self.validate(who, call, info, len).map(|_| ())?)
|
||||
self.validate(who, call, info, len).map(|_| ())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -637,19 +637,13 @@ pub mod pallet {
|
||||
#[pallet::storage]
|
||||
pub(super) type ExecutionPhase<T: Config> = StorageValue<_, Phase>;
|
||||
|
||||
#[cfg_attr(feature = "std", derive(Default))]
|
||||
#[pallet::genesis_config]
|
||||
pub struct GenesisConfig {
|
||||
#[serde(with = "sp_core::bytes")]
|
||||
pub code: Vec<u8>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl Default for GenesisConfig {
|
||||
fn default() -> Self {
|
||||
Self { code: Default::default() }
|
||||
}
|
||||
}
|
||||
|
||||
#[pallet::genesis_build]
|
||||
impl<T: Config> GenesisBuild<T> for GenesisConfig {
|
||||
fn build(&self) {
|
||||
|
||||
@@ -39,7 +39,7 @@ fn assets() -> Vec<(u64, u32, u32)> {
|
||||
Some(Some(item))
|
||||
}
|
||||
})
|
||||
.filter_map(|item| item)
|
||||
.flatten()
|
||||
{
|
||||
let details = Class::<Test>::get(class).unwrap();
|
||||
let instances = Asset::<Test>::iter_prefix(class).count() as u32;
|
||||
|
||||
@@ -572,14 +572,13 @@ impl<T: Config> Pallet<T> {
|
||||
let mut total_locked_now: BalanceOf<T> = Zero::zero();
|
||||
let filtered_schedules = action
|
||||
.pick_schedules::<T>(schedules)
|
||||
.filter_map(|schedule| {
|
||||
.filter(|schedule| {
|
||||
let locked_now = schedule.locked_at::<T::BlockNumberToBalance>(now);
|
||||
if locked_now.is_zero() {
|
||||
None
|
||||
} else {
|
||||
let keep = !locked_now.is_zero();
|
||||
if keep {
|
||||
total_locked_now = total_locked_now.saturating_add(locked_now);
|
||||
Some(schedule)
|
||||
}
|
||||
keep
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
|
||||
@@ -235,9 +235,7 @@ fn generate_native_call_generators(decl: &ItemTrait) -> Result<TokenStream> {
|
||||
// compatible. To ensure that we forward it by ref/value, we use the value given by the
|
||||
// the user. Otherwise if it is not using the block, we don't need to add anything.
|
||||
let input_borrows =
|
||||
params
|
||||
.iter()
|
||||
.map(|v| if type_is_using_block(&v.1) { v.2.clone() } else { None });
|
||||
params.iter().map(|v| if type_is_using_block(&v.1) { v.2 } else { None });
|
||||
|
||||
// Replace all `Block` with `NodeBlock`, add `'a` lifetime to references and collect
|
||||
// all the function inputs.
|
||||
@@ -380,7 +378,6 @@ fn generate_call_api_at_calls(decl: &ItemTrait) -> Result<TokenStream> {
|
||||
// Generate the generator function
|
||||
result.push(quote!(
|
||||
#[cfg(any(feature = "std", test))]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn #fn_name<
|
||||
R: #crate_::Encode + #crate_::Decode + PartialEq,
|
||||
NC: FnOnce() -> std::result::Result<R, #crate_::ApiError> + std::panic::UnwindSafe,
|
||||
|
||||
@@ -88,13 +88,13 @@ impl<H: HeaderT> sp_inherents::InherentDataProvider for InherentDataProvider<H>
|
||||
async fn try_handle_error(
|
||||
&self,
|
||||
identifier: &InherentIdentifier,
|
||||
error: &[u8],
|
||||
mut error: &[u8],
|
||||
) -> Option<Result<(), Error>> {
|
||||
if *identifier != INHERENT_IDENTIFIER {
|
||||
return None
|
||||
}
|
||||
|
||||
let error = InherentError::decode(&mut &error[..]).ok()?;
|
||||
let error = InherentError::decode(&mut error).ok()?;
|
||||
|
||||
Some(Err(Error::Application(Box::from(format!("{:?}", error)))))
|
||||
}
|
||||
|
||||
@@ -101,7 +101,7 @@ mod implementation {
|
||||
}
|
||||
}
|
||||
|
||||
fn derive_fields<'a>(name_str: &str, fields: Fields) -> TokenStream {
|
||||
fn derive_fields(name_str: &str, fields: Fields) -> TokenStream {
|
||||
match fields {
|
||||
Fields::Named { names, this } => {
|
||||
let names_str: Vec<_> = names.iter().map(|x| x.to_string()).collect();
|
||||
|
||||
@@ -482,9 +482,7 @@ mod tests {
|
||||
assert!(res.is_none());
|
||||
|
||||
// insert key, sign again
|
||||
let res =
|
||||
SyncCryptoStore::insert_unknown(&store, ECDSA, suri, pair.public().as_ref()).unwrap();
|
||||
assert_eq!((), res);
|
||||
SyncCryptoStore::insert_unknown(&store, ECDSA, suri, pair.public().as_ref()).unwrap();
|
||||
|
||||
let res =
|
||||
SyncCryptoStore::ecdsa_sign_prehashed(&store, ECDSA, &pair.public(), &msg).unwrap();
|
||||
|
||||
@@ -11,7 +11,7 @@ fn main() {
|
||||
loop {
|
||||
fuzz!(|fuzzer_data: &[u8]| {
|
||||
let result_decoded: Result<InnerTestSolutionCompact, Error> =
|
||||
<InnerTestSolutionCompact as codec::Decode>::decode(&mut &fuzzer_data[..]);
|
||||
<InnerTestSolutionCompact as codec::Decode>::decode(&mut &*fuzzer_data);
|
||||
// Ignore errors as not every random sequence of bytes can be decoded as
|
||||
// InnerTestSolutionCompact
|
||||
if let Ok(decoded) = result_decoded {
|
||||
|
||||
@@ -90,7 +90,7 @@ fn generate_random_phragmen_assignment(
|
||||
.map(|_| {
|
||||
let target =
|
||||
targets_to_chose_from.remove(rng.gen_range(0, targets_to_chose_from.len()));
|
||||
if winners.iter().find(|w| **w == target).is_none() {
|
||||
if winners.iter().all(|w| *w != target) {
|
||||
winners.push(target.clone());
|
||||
}
|
||||
(target, rng.gen_range(1 * KSM, 100 * KSM))
|
||||
|
||||
@@ -275,9 +275,8 @@ fn reduce_4<A: IdentifierT>(assignments: &mut Vec<StakedAssignment<A>>) -> u32 {
|
||||
});
|
||||
|
||||
// remove either one of them.
|
||||
let who_removed = remove_indices.iter().find(|i| **i < 2usize).is_some();
|
||||
let other_removed =
|
||||
remove_indices.into_iter().find(|i| *i >= 2usize).is_some();
|
||||
let who_removed = remove_indices.iter().any(|i| *i < 2usize);
|
||||
let other_removed = remove_indices.into_iter().any(|i| i >= 2usize);
|
||||
|
||||
match (who_removed, other_removed) {
|
||||
(false, true) => {
|
||||
|
||||
@@ -62,17 +62,17 @@ fn call_wasm_method<HF: HostFunctionsT>(binary: &[u8], method: &str) -> TestExte
|
||||
|
||||
#[test]
|
||||
fn test_return_data() {
|
||||
call_wasm_method::<HostFunctions>(&wasm_binary_unwrap()[..], "test_return_data");
|
||||
call_wasm_method::<HostFunctions>(wasm_binary_unwrap(), "test_return_data");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_return_option_data() {
|
||||
call_wasm_method::<HostFunctions>(&wasm_binary_unwrap()[..], "test_return_option_data");
|
||||
call_wasm_method::<HostFunctions>(wasm_binary_unwrap(), "test_return_option_data");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_set_storage() {
|
||||
let mut ext = call_wasm_method::<HostFunctions>(&wasm_binary_unwrap()[..], "test_set_storage");
|
||||
let mut ext = call_wasm_method::<HostFunctions>(wasm_binary_unwrap(), "test_set_storage");
|
||||
|
||||
let expected = "world";
|
||||
assert_eq!(expected.as_bytes(), &ext.ext().storage("hello".as_bytes()).unwrap()[..]);
|
||||
@@ -81,30 +81,30 @@ fn test_set_storage() {
|
||||
#[test]
|
||||
fn test_return_value_into_mutable_reference() {
|
||||
call_wasm_method::<HostFunctions>(
|
||||
&wasm_binary_unwrap()[..],
|
||||
wasm_binary_unwrap(),
|
||||
"test_return_value_into_mutable_reference",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_and_return_array() {
|
||||
call_wasm_method::<HostFunctions>(&wasm_binary_unwrap()[..], "test_get_and_return_array");
|
||||
call_wasm_method::<HostFunctions>(wasm_binary_unwrap(), "test_get_and_return_array");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_array_as_mutable_reference() {
|
||||
call_wasm_method::<HostFunctions>(&wasm_binary_unwrap()[..], "test_array_as_mutable_reference");
|
||||
call_wasm_method::<HostFunctions>(wasm_binary_unwrap(), "test_array_as_mutable_reference");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_return_input_public_key() {
|
||||
call_wasm_method::<HostFunctions>(&wasm_binary_unwrap()[..], "test_return_input_public_key");
|
||||
call_wasm_method::<HostFunctions>(wasm_binary_unwrap(), "test_return_input_public_key");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_function_not_found() {
|
||||
let err = call_wasm_method_with_result::<()>(&wasm_binary_unwrap()[..], "test_return_data")
|
||||
.unwrap_err();
|
||||
let err =
|
||||
call_wasm_method_with_result::<()>(wasm_binary_unwrap(), "test_return_data").unwrap_err();
|
||||
|
||||
assert!(err.contains("Instantiation: Export "));
|
||||
assert!(err.contains(" not found"));
|
||||
@@ -114,7 +114,7 @@ fn host_function_not_found() {
|
||||
#[should_panic(expected = "Invalid utf8 data provided")]
|
||||
fn test_invalid_utf8_data_should_return_an_error() {
|
||||
call_wasm_method::<HostFunctions>(
|
||||
&wasm_binary_unwrap()[..],
|
||||
wasm_binary_unwrap(),
|
||||
"test_invalid_utf8_data_should_return_an_error",
|
||||
);
|
||||
}
|
||||
@@ -122,7 +122,7 @@ fn test_invalid_utf8_data_should_return_an_error() {
|
||||
#[test]
|
||||
fn test_overwrite_native_function_implementation() {
|
||||
call_wasm_method::<HostFunctions>(
|
||||
&wasm_binary_unwrap()[..],
|
||||
wasm_binary_unwrap(),
|
||||
"test_overwrite_native_function_implementation",
|
||||
);
|
||||
}
|
||||
@@ -130,7 +130,7 @@ fn test_overwrite_native_function_implementation() {
|
||||
#[test]
|
||||
fn test_u128_i128_as_parameter_and_return_value() {
|
||||
call_wasm_method::<HostFunctions>(
|
||||
&wasm_binary_unwrap()[..],
|
||||
wasm_binary_unwrap(),
|
||||
"test_u128_i128_as_parameter_and_return_value",
|
||||
);
|
||||
}
|
||||
@@ -138,7 +138,7 @@ fn test_u128_i128_as_parameter_and_return_value() {
|
||||
#[test]
|
||||
fn test_vec_return_value_memory_is_freed() {
|
||||
call_wasm_method::<HostFunctions>(
|
||||
&wasm_binary_unwrap()[..],
|
||||
wasm_binary_unwrap(),
|
||||
"test_vec_return_value_memory_is_freed",
|
||||
);
|
||||
}
|
||||
@@ -146,7 +146,7 @@ fn test_vec_return_value_memory_is_freed() {
|
||||
#[test]
|
||||
fn test_encoded_return_value_memory_is_freed() {
|
||||
call_wasm_method::<HostFunctions>(
|
||||
&wasm_binary_unwrap()[..],
|
||||
wasm_binary_unwrap(),
|
||||
"test_encoded_return_value_memory_is_freed",
|
||||
);
|
||||
}
|
||||
@@ -154,7 +154,7 @@ fn test_encoded_return_value_memory_is_freed() {
|
||||
#[test]
|
||||
fn test_array_return_value_memory_is_freed() {
|
||||
call_wasm_method::<HostFunctions>(
|
||||
&wasm_binary_unwrap()[..],
|
||||
wasm_binary_unwrap(),
|
||||
"test_array_return_value_memory_is_freed",
|
||||
);
|
||||
}
|
||||
@@ -162,14 +162,11 @@ fn test_array_return_value_memory_is_freed() {
|
||||
#[test]
|
||||
fn test_versionining_with_new_host_works() {
|
||||
// We call to the new wasm binary with new host function.
|
||||
call_wasm_method::<HostFunctions>(&wasm_binary_unwrap()[..], "test_versionning_works");
|
||||
call_wasm_method::<HostFunctions>(wasm_binary_unwrap(), "test_versionning_works");
|
||||
|
||||
// we call to the old wasm binary with a new host functions
|
||||
// old versions of host functions should be called and test should be ok!
|
||||
call_wasm_method::<HostFunctions>(
|
||||
&wasm_binary_deprecated_unwrap()[..],
|
||||
"test_versionning_works",
|
||||
);
|
||||
call_wasm_method::<HostFunctions>(wasm_binary_deprecated_unwrap(), "test_versionning_works");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -224,7 +221,7 @@ fn test_tracing() {
|
||||
let _guard = tracing::subscriber::set_default(subscriber.clone());
|
||||
|
||||
// Call some method to generate a trace
|
||||
call_wasm_method::<HostFunctions>(&wasm_binary_unwrap()[..], "test_return_data");
|
||||
call_wasm_method::<HostFunctions>(wasm_binary_unwrap(), "test_return_data");
|
||||
|
||||
let inner = subscriber.0.lock().unwrap();
|
||||
assert!(inner.spans.contains("return_input_version_1"));
|
||||
@@ -232,5 +229,5 @@ fn test_tracing() {
|
||||
|
||||
#[test]
|
||||
fn test_return_input_as_tuple() {
|
||||
call_wasm_method::<HostFunctions>(&wasm_binary_unwrap()[..], "test_return_input_as_tuple");
|
||||
call_wasm_method::<HostFunctions>(wasm_binary_unwrap(), "test_return_input_as_tuple");
|
||||
}
|
||||
|
||||
@@ -33,19 +33,13 @@ use crate::{
|
||||
use sp_core::RuntimeDebug;
|
||||
|
||||
/// Generic header digest.
|
||||
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, TypeInfo)]
|
||||
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, TypeInfo, Default)]
|
||||
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, parity_util_mem::MallocSizeOf))]
|
||||
pub struct Digest {
|
||||
/// A list of logs in the digest.
|
||||
pub logs: Vec<DigestItem>,
|
||||
}
|
||||
|
||||
impl Default for Digest {
|
||||
fn default() -> Self {
|
||||
Self { logs: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
impl Digest {
|
||||
/// Get reference to all digest items.
|
||||
pub fn logs(&self) -> &[DigestItem] {
|
||||
|
||||
@@ -395,7 +395,7 @@ mod tests {
|
||||
info: &DispatchInfoOf<Self::Call>,
|
||||
len: usize,
|
||||
) -> Result<Self::Pre, TransactionValidityError> {
|
||||
Ok(self.validate(who, call, info, len).map(|_| ())?)
|
||||
self.validate(who, call, info, len).map(|_| ())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1074,7 +1074,7 @@ impl SignedExtension for () {
|
||||
info: &DispatchInfoOf<Self::Call>,
|
||||
len: usize,
|
||||
) -> Result<Self::Pre, TransactionValidityError> {
|
||||
Ok(self.validate(who, call, info, len).map(|_| ())?)
|
||||
self.validate(who, call, info, len).map(|_| ())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -208,7 +208,7 @@ pub trait Backend<H: Hasher>: sp_std::fmt::Debug {
|
||||
}
|
||||
let (root, parent_txs) = self.storage_root(
|
||||
delta
|
||||
.map(|(k, v)| (&k[..], v.as_ref().map(|v| &v[..])))
|
||||
.map(|(k, v)| (k, v.as_ref().map(|v| &v[..])))
|
||||
.chain(child_roots.iter().map(|(k, v)| (&k[..], v.as_ref().map(|v| &v[..])))),
|
||||
state_version,
|
||||
);
|
||||
|
||||
@@ -581,7 +581,7 @@ where
|
||||
target: "state",
|
||||
method = "ChildStorageRoot",
|
||||
ext_id = %HexDisplay::from(&self.id.to_le_bytes()),
|
||||
child_info = %HexDisplay::from(&storage_key.as_ref()),
|
||||
child_info = %HexDisplay::from(&storage_key),
|
||||
storage_root = %HexDisplay::from(&root.as_ref()),
|
||||
cached = false,
|
||||
);
|
||||
@@ -599,7 +599,7 @@ where
|
||||
target: "state",
|
||||
method = "ChildStorageRoot",
|
||||
ext_id = %HexDisplay::from(&self.id.to_le_bytes()),
|
||||
child_info = %HexDisplay::from(&storage_key.as_ref()),
|
||||
child_info = %HexDisplay::from(&storage_key),
|
||||
storage_root = %HexDisplay::from(&root.as_ref()),
|
||||
cached = false,
|
||||
);
|
||||
|
||||
@@ -203,7 +203,7 @@ where
|
||||
///
|
||||
/// This implementation will wipe the proof recorded in between calls. Consecutive calls will
|
||||
/// get their own proof from scratch.
|
||||
pub fn execute_and_prove<'a, R>(&mut self, execute: impl FnOnce() -> R) -> (R, StorageProof) {
|
||||
pub fn execute_and_prove<R>(&mut self, execute: impl FnOnce() -> R) -> (R, StorageProof) {
|
||||
let proving_backend = InMemoryProvingBackend::new(&self.backend);
|
||||
let mut proving_ext = Ext::new(
|
||||
&mut self.overlay,
|
||||
|
||||
@@ -138,9 +138,9 @@ impl IsFatalError for InherentError {
|
||||
impl InherentError {
|
||||
/// Try to create an instance ouf of the given identifier and data.
|
||||
#[cfg(feature = "std")]
|
||||
pub fn try_from(id: &InherentIdentifier, data: &[u8]) -> Option<Self> {
|
||||
pub fn try_from(id: &InherentIdentifier, mut data: &[u8]) -> Option<Self> {
|
||||
if id == &INHERENT_IDENTIFIER {
|
||||
<InherentError as codec::Decode>::decode(&mut &data[..]).ok()
|
||||
<InherentError as codec::Decode>::decode(&mut data).ok()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
@@ -227,7 +227,7 @@ impl sp_inherents::InherentDataProvider for InherentDataProvider {
|
||||
&self,
|
||||
inherent_data: &mut InherentData,
|
||||
) -> Result<(), sp_inherents::Error> {
|
||||
inherent_data.put_data(INHERENT_IDENTIFIER, &InherentType::from(self.timestamp))
|
||||
inherent_data.put_data(INHERENT_IDENTIFIER, &self.timestamp)
|
||||
}
|
||||
|
||||
async fn try_handle_error(
|
||||
|
||||
@@ -67,7 +67,7 @@ pub trait TransactionStorageProofInherentData {
|
||||
|
||||
impl TransactionStorageProofInherentData for InherentData {
|
||||
fn storage_proof(&self) -> Result<Option<TransactionStorageProof>, Error> {
|
||||
Ok(self.get_data(&INHERENT_IDENTIFIER)?)
|
||||
self.get_data(&INHERENT_IDENTIFIER)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,13 +98,13 @@ impl sp_inherents::InherentDataProvider for InherentDataProvider {
|
||||
async fn try_handle_error(
|
||||
&self,
|
||||
identifier: &InherentIdentifier,
|
||||
error: &[u8],
|
||||
mut error: &[u8],
|
||||
) -> Option<Result<(), Error>> {
|
||||
if *identifier != INHERENT_IDENTIFIER {
|
||||
return None
|
||||
}
|
||||
|
||||
let error = InherentError::decode(&mut &error[..]).ok()?;
|
||||
let error = InherentError::decode(&mut error).ok()?;
|
||||
|
||||
Some(Err(Error::Application(Box::from(format!("{:?}", error)))))
|
||||
}
|
||||
|
||||
@@ -281,7 +281,7 @@ where
|
||||
L: TrieConfiguration,
|
||||
DB: hash_db::HashDBRef<L::Hash, trie_db::DBValue>,
|
||||
{
|
||||
Ok(TrieDB::<L>::new(&*db, root)?.get(key).map(|x| x.map(|val| val.to_vec()))?)
|
||||
TrieDB::<L>::new(&*db, root)?.get(key).map(|x| x.map(|val| val.to_vec()))
|
||||
}
|
||||
|
||||
/// Read a value from the trie with given Query.
|
||||
@@ -296,9 +296,9 @@ where
|
||||
Q: Query<L::Hash, Item = DBValue>,
|
||||
DB: hash_db::HashDBRef<L::Hash, trie_db::DBValue>,
|
||||
{
|
||||
Ok(TrieDB::<L>::new(&*db, root)?
|
||||
TrieDB::<L>::new(&*db, root)?
|
||||
.get_with(key, query)
|
||||
.map(|x| x.map(|val| val.to_vec()))?)
|
||||
.map(|x| x.map(|val| val.to_vec()))
|
||||
}
|
||||
|
||||
/// Determine the empty trie root.
|
||||
|
||||
@@ -665,13 +665,7 @@ fn code_using_trie() -> u64 {
|
||||
|
||||
if let Ok(trie) = TrieDB::<Hashing>::new(&mdb, &root) {
|
||||
if let Ok(iter) = trie.iter() {
|
||||
let mut iter_pairs = Vec::new();
|
||||
for pair in iter {
|
||||
if let Ok((key, value)) = pair {
|
||||
iter_pairs.push((key, value.to_vec()));
|
||||
}
|
||||
}
|
||||
iter_pairs.len() as u64
|
||||
iter.flatten().count() as u64
|
||||
} else {
|
||||
102
|
||||
}
|
||||
|
||||
@@ -176,9 +176,7 @@ impl BenchmarkCmd {
|
||||
.filter(|item| pallet.is_empty() || pallet == &b"*"[..] || pallet == &item.pallet[..])
|
||||
.for_each(|item| {
|
||||
for benchmark in &item.benchmarks {
|
||||
if extrinsic.is_empty() ||
|
||||
&extrinsic[..] == &b"*"[..] ||
|
||||
extrinsic == benchmark.name
|
||||
if extrinsic.is_empty() || extrinsic == &b"*"[..] || extrinsic == benchmark.name
|
||||
{
|
||||
benchmarks_to_run.push((
|
||||
item.pallet.clone(),
|
||||
|
||||
@@ -496,7 +496,6 @@ impl State {
|
||||
state_snapshot: snapshot_path.as_ref().map(SnapshotConfig::new),
|
||||
pallets: pallets.clone().unwrap_or_default(),
|
||||
at,
|
||||
..Default::default()
|
||||
}))
|
||||
.inject_hashed_key(
|
||||
&[twox_128(b"System"), twox_128(b"LastRuntimeUpgrade")].concat(),
|
||||
|
||||
@@ -18,8 +18,11 @@
|
||||
//! Utils for parsing user input
|
||||
|
||||
pub(crate) fn hash(block_hash: &str) -> Result<String, String> {
|
||||
let (block_hash, offset) =
|
||||
if block_hash.starts_with("0x") { (&block_hash[2..], 2) } else { (block_hash, 0) };
|
||||
let (block_hash, offset) = if let Some(block_hash) = block_hash.strip_prefix("0x") {
|
||||
(block_hash, 2)
|
||||
} else {
|
||||
(block_hash, 0)
|
||||
};
|
||||
|
||||
if let Some(pos) = block_hash.chars().position(|c| !c.is_ascii_hexdigit()) {
|
||||
Err(format!(
|
||||
|
||||
Reference in New Issue
Block a user