Skip to content

Commit

Permalink
[refactor]: Fix CI lints after bump of toolchain version (hyperledger…
Browse files Browse the repository at this point in the history
…-iroha#4201)

Signed-off-by: Marin Veršić <marin.versic101@gmail.com>
  • Loading branch information
mversic committed Jan 18, 2024
1 parent 66072b4 commit 47f1c87
Show file tree
Hide file tree
Showing 42 changed files with 146 additions and 217 deletions.
6 changes: 1 addition & 5 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -144,12 +144,10 @@ rust.nonstandard_style = "deny"
rust.rust_2018_idioms = "deny"
rust.trivial_casts = "deny"
rust.trivial_numeric_casts = "deny"
rust.unconditional_recursion = "deny"
rust.unsafe_code = "deny"
rust.unused = "deny"
rust.unused_import_braces = "deny"
rust.variant_size_differences = "deny"
rust.unused_tuple_struct_fields = "deny"
rust.explicit_outlives_requirements = "deny"
rust.non_ascii_idents = "deny"
rust.elided_lifetimes_in_paths = "allow"
Expand All @@ -159,9 +157,6 @@ rust.unused_lifetimes = "warn"
# TODO: reenable
# rust.unsafe_op_in_unsafe_fn = "deny"

# lower the priority to allow overriding later
clippy.all = { level = "deny", priority = -1 }

# pedantic
clippy.pedantic = { level = "warn", priority = -1 }
clippy.match_wildcard_for_single_variants = "allow"
Expand All @@ -171,6 +166,7 @@ clippy.manual_let_else = "allow"
clippy.enum_glob_use = "allow"
clippy.module_name_repetitions = "allow"
clippy.must_use_candidate = "allow"
clippy.missing_panics_doc = "allow"

# restriction
clippy.dbg_macro = "deny"
Expand Down
8 changes: 6 additions & 2 deletions cli/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ impl NetworkRelay {
async fn run(mut self) {
let (sender, mut receiver) = mpsc::channel(1);
self.network.subscribe_to_peers_messages(sender);
// NOTE: Triggered by tokio::select
#[allow(clippy::redundant_pub_crate)]
loop {
tokio::select! {
Expand Down Expand Up @@ -406,7 +407,6 @@ impl Iroha {
Ok(TelemetryStartStatus::NotStarted)
}

#[allow(clippy::redundant_pub_crate)]
fn start_listening_signal(notify_shutdown: Arc<Notify>) -> Result<task::JoinHandle<()>> {
let (mut sigint, mut sigterm) = signal::unix::signal(signal::unix::SignalKind::interrupt())
.and_then(|sigint| {
Expand All @@ -416,6 +416,8 @@ impl Iroha {
})
.wrap_err("Failed to start listening for OS signals")?;

// NOTE: Triggered by tokio::select
#[allow(clippy::redundant_pub_crate)]
let handle = task::spawn(async move {
tokio::select! {
_ = sigint.recv() => {
Expand Down Expand Up @@ -447,6 +449,8 @@ impl Iroha {
// FIXME: don't like neither the message nor inability to throw Result to the outside
.expect("Cannot proceed without working subscriptions");

// NOTE: Triggered by tokio::select
#[allow(clippy::redundant_pub_crate)]
loop {
tokio::select! {
Ok(()) = log_level_update.changed() => {
Expand Down Expand Up @@ -528,7 +532,7 @@ pub fn read_config(
let mut cfg = config.override_with(ConfigurationProxy::from_path(&*actual_config_path));
let config_dir = actual_config_path
.parent()
.expect("If config file was read, than it should has a parent. It is a bug.");
.expect("If config file was read, than it should have a parent. It is a bug.");

// careful here: `genesis.file` might be a path relative to the config file.
// we need to resolve it before proceeding
Expand Down
59 changes: 58 additions & 1 deletion client/tests/integration/events/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,65 @@ use parity_scale_codec::Encode as _;
use serde_json::json;
use test_network::*;

use crate::wasm::utils::wasm_template;
/// Return string containing exported memory, dummy allocator, and
/// host function imports which you can embed into your wasm module.
///
/// Memory is initialized with the given hex encoded string value
// NOTE: It's expected that hex value is of even length
#[allow(clippy::integer_division)]
pub fn wasm_template(hex_val: &str) -> String {
format!(
r#"
;; Import host function to execute instruction
(import "iroha" "{execute_instruction}"
(func $exec_isi (param i32 i32) (result i32)))
;; Import host function to execute query
(import "iroha" "{execute_query}"
(func $exec_query (param i32 i32) (result i32)))
;; Embed ISI into WASM binary memory
(memory (export "{memory_name}") 1)
(data (i32.const 0) "{hex_val}")
;; Variable which tracks total allocated size
(global $mem_size (mut i32) i32.const {hex_len})
;; Export mock allocator to host. This allocator never frees!
(func (export "{alloc_fn_name}") (param $size i32) (result i32)
global.get $mem_size
(global.set $mem_size
(i32.add (global.get $mem_size) (local.get $size)))
)
;; Export mock deallocator to host. This allocator does nothing!
(func (export "{dealloc_fn_name}") (param $size i32) (param $len i32)
nop)
"#,
memory_name = "memory",
alloc_fn_name = "_iroha_smart_contract_alloc",
dealloc_fn_name = "_iroha_smart_contract_dealloc",
execute_instruction = "execute_instruction",
execute_query = "execute_query",
hex_val = escape_hex(hex_val),
hex_len = hex_val.len() / 2,
)
}

fn escape_hex(hex_val: &str) -> String {
let mut isi_hex = String::with_capacity(3 * hex_val.len());

for (i, c) in hex_val.chars().enumerate() {
if i % 2 == 0 {
isi_hex.push('\\');
}

isi_hex.push(c);
}

isi_hex
}
fn produce_instructions() -> Vec<InstructionBox> {
let domains = (0..4)
.map(|domain_index: usize| Domain::new(domain_index.to_string().parse().expect("Valid")));
Expand Down
2 changes: 0 additions & 2 deletions client/tests/integration/events/pipeline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ use iroha_config::iroha::Configuration;
use test_network::*;

// Needed to re-enable ignored tests.
#[allow(dead_code)]
const PEER_COUNT: usize = 7;

#[ignore = "ignore, more in #2851"]
Expand All @@ -33,7 +32,6 @@ fn transaction_with_fail_instruction_should_be_rejected() -> Result<()> {
)
}

#[allow(dead_code, clippy::needless_range_loop, clippy::needless_pass_by_value)]
fn test_with_instruction_and_status_and_port(
instruction: Option<InstructionBox>,
should_be: PipelineStatusKind,
Expand Down
13 changes: 5 additions & 8 deletions client/tests/integration/unregister_peer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,14 +112,11 @@ fn init() -> Result<(
let asset_definition_id: AssetDefinitionId = "xor#domain".parse()?;
let create_asset =
Register::asset_definition(AssetDefinition::quantity(asset_definition_id.clone()));
let instructions = parameters.into_iter().chain(
[
create_domain.into(),
create_account.into(),
create_asset.into(),
]
.into_iter(),
);
let instructions = parameters.into_iter().chain([
create_domain.into(),
create_account.into(),
create_asset.into(),
]);
client.submit_all_blocking(instructions)?;
iroha_logger::info!("Init");
Ok((
Expand Down
1 change: 0 additions & 1 deletion client/tests/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
#[cfg(not(coverage))]
mod integration;
mod wasm;
1 change: 0 additions & 1 deletion client/tests/wasm/mod.rs

This file was deleted.

59 changes: 0 additions & 59 deletions client/tests/wasm/utils.rs

This file was deleted.

2 changes: 1 addition & 1 deletion client_cli/pytests/common/consts.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class Stderr(Enum):
CANNOT_BE_EMPTY = 'cannot be empty\n\nFor more information, try \'--help\'.\n'
REPETITION = 'Repetition'
TOO_LONG = 'Name length violation'
FAILED_TO_FIND_DOMAIN = 'Entity missing'
FAILED_TO_FIND_DOMAIN = 'Failed to find domain'
INVALID_CHARACTER = 'Invalid character'
INVALID_VALUE_TYPE = 'Matching variant not found'
RESERVED_CHARACTER = 'The `@` character is reserved for `account@domain` constructs,' \
Expand Down
2 changes: 1 addition & 1 deletion client_cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ impl FromStr for ValueArg {
.or_else(|_| s.parse::<Ipv6Addr>().map(Value::Ipv6Addr))
.or_else(|_| s.parse::<NumericValue>().map(Value::Numeric))
.or_else(|_| s.parse::<PublicKey>().map(Value::PublicKey))
.or_else(|_| serde_json::from_str::<Value>(s).map_err(std::convert::Into::into))
.or_else(|_| serde_json::from_str::<Value>(s).map_err(Into::into))
.map(ValueArg)
}
}
Expand Down
7 changes: 4 additions & 3 deletions config/src/path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,10 @@ impl Path {
/// If the path has an extension.
pub fn default(path: impl AsRef<std::path::Path>) -> Self {
let path = path.as_ref().to_path_buf();
if path.extension().is_some() {
panic!("Default config path is not supposed to have an extension. It is a bug.")
}
assert!(
path.extension().is_none(),
"Default config path is not supposed to have an extension. It is a bug."
);
Self(Default(path))
}

Expand Down
2 changes: 1 addition & 1 deletion core/src/block_sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ pub mod message {
.take(1 + block_sync.block_batch_size as usize)
.map_while(|height| block_sync.kura.get_block_by_height(height))
.skip_while(|block| Some(block.hash()) == *latest_hash)
.map(|block| SignedBlock::clone(&block))
.map(|block| (*block).clone())
.collect::<Vec<_>>();

if blocks.is_empty() {
Expand Down
1 change: 0 additions & 1 deletion core/src/kiso.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,6 @@ impl Actor {
}

#[cfg(test)]
#[allow(unused)]
mod tests {
use std::time::Duration;

Expand Down
1 change: 0 additions & 1 deletion core/src/kura.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ const SIZE_OF_BLOCK_HASH: u64 = Hash::LENGTH as u64;
#[derive(Debug)]
pub struct Kura {
/// The mode of initialisation of [`Kura`].
#[allow(dead_code)]
mode: Mode,
/// The block storage
block_store: Mutex<BlockStore>,
Expand Down
6 changes: 2 additions & 4 deletions core/src/queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,6 @@ impl Queue {
///
/// # Errors
/// See [`enum@Error`]
#[allow(clippy::missing_panics_doc)] // NOTE: It's a system invariant, should never happen
pub fn push(&self, tx: AcceptedTransaction, wsv: &WorldStateView) -> Result<(), Failure> {
trace!(?tx, "Pushing to the queue");
if let Err(err) = self.check_tx(&tx, wsv) {
Expand Down Expand Up @@ -250,9 +249,8 @@ impl Queue {
expired_transactions: &mut Vec<AcceptedTransaction>,
) -> Option<AcceptedTransaction> {
loop {
let Some(hash) = self.tx_hashes.pop() else {
return None;
};
let hash = self.tx_hashes.pop()?;

let entry = match self.accepted_txs.entry(hash) {
Entry::Occupied(entry) => entry,
// FIXME: Reachable under high load. Investigate, see if it's a problem.
Expand Down
2 changes: 1 addition & 1 deletion core/src/smartcontracts/isi/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -581,7 +581,7 @@ pub mod query {
let id = &self.id;
let key = &self.key;
iroha_logger::trace!(%id, %key);
wsv.map_account(id, |account| account.metadata.get(key).map(Clone::clone))?
wsv.map_account(id, |account| account.metadata.get(key).cloned())?
.ok_or_else(|| FindError::MetadataKey(key.clone()).into())
.map(Into::into)
}
Expand Down
4 changes: 1 addition & 3 deletions core/src/smartcontracts/isi/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,7 @@ impl ValidQuery for FindAllBlocks {
wsv: &'wsv WorldStateView,
) -> Result<Box<dyn Iterator<Item = SignedBlock> + 'wsv>, QueryExecutionFail> {
Ok(Box::new(
wsv.all_blocks()
.rev()
.map(|block| SignedBlock::clone(&block)),
wsv.all_blocks().rev().map(|block| (*block).clone()),
))
}
}
Expand Down
2 changes: 1 addition & 1 deletion core/src/smartcontracts/isi/domain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -334,7 +334,7 @@ pub mod query {
let id = &self.id;
let key = &self.key;
iroha_logger::trace!(%id, %key);
wsv.map_domain(id, |domain| domain.metadata.get(key).map(Clone::clone))?
wsv.map_domain(id, |domain| domain.metadata.get(key).cloned())?
.ok_or_else(|| FindError::MetadataKey(key.clone()).into())
.map(Into::into)
}
Expand Down
14 changes: 6 additions & 8 deletions core/src/tx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,7 @@ impl AcceptedTransaction {
match &transaction.payload().instructions {
Executable::Instructions(instructions) => {
let instruction_count = instructions.len();
if u64::try_from(instruction_count).expect("`usize` should always fit into `u64`")
> limits.max_instruction_number
{
if Self::len_u64(instruction_count) > limits.max_instruction_number {
return Err(AcceptTransactionFail::TransactionLimit(
TransactionLimitError {
reason: format!(
Expand All @@ -76,13 +74,9 @@ impl AcceptedTransaction {
//
// Should we allow infinite instructions in wasm? And deny only based on fuel and size
Executable::Wasm(smart_contract) => {
let size_bytes = Self::len_u64(smart_contract.size_bytes());
let max_wasm_size_bytes = limits.max_wasm_size_bytes;

let size_bytes: u64 = smart_contract
.size_bytes()
.try_into()
.expect("`u64` should always fit in `u64`");

if size_bytes > max_wasm_size_bytes {
return Err(AcceptTransactionFail::TransactionLimit(
TransactionLimitError {
Expand Down Expand Up @@ -113,6 +107,10 @@ impl AcceptedTransaction {
pub(crate) fn merge_signatures(&mut self, other: Self) -> bool {
self.0.merge_signatures(other.0)
}

fn len_u64(instruction_count: usize) -> u64 {
u64::try_from(instruction_count).expect("`usize` should always fit into `u64`")
}
}

impl From<AcceptedTransaction> for SignedTransaction {
Expand Down
Loading

0 comments on commit 47f1c87

Please sign in to comment.