Skip to content

Commit

Permalink
Fix clippy warnings (#310)
Browse files Browse the repository at this point in the history
* Use variables directly in the format! & write! strings

* Remove `clippy::large_enum_variant`, `clippy::ptr_arg`, `clippy::wrong_self_convention`

* Fix lint issues identified by clippy 0.1.67

* Replace Box<ValidatorSet> with Vec<Validator>

* Add changelog entry
  • Loading branch information
Farhad-Shabani authored Dec 23, 2022
1 parent cec7c31 commit 4c16095
Show file tree
Hide file tree
Showing 29 changed files with 72 additions and 116 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
- Change type of `trusted_validator_set` field in
`MisbehaviourTrustedValidatorHashMismatch` error variant from `ValidatorSet` to
`Vec<Validator>` to avoid clippy catches
([#309](https://github.com/cosmos/ibc-rs/issues/309))
2 changes: 2 additions & 0 deletions .changelog/unreleased/improvements/309-fix-clippy-warnings.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
- Improve clippy catches and fix lint issues identified by clippy 0.1.67
([#309](https://github.com/cosmos/ibc-rs/issues/309))
7 changes: 4 additions & 3 deletions crates/ibc/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,29 +3,30 @@
[![Crate][crate-image]][crate-link]
[![Docs][docs-image]][docs-link]
[![Build Status][build-image]][build-link]
[![End to End testing][e2e-image]][e2e-link]
[![Apache 2.0 Licensed][license-image]][license-link]
![Rust Stable][rustc-image]
![Rust 1.60+][rustc-version]


Implementation of the Inter-Blockchain Communication Protocol ([IBC]) in Rust.

## Documentation

See documentation on [docs.rs][docs-link].

## Divergence from the Interchain Standards (ICS)

This crate diverges from the [ICS specification](https://github.com/cosmos/ibc) in a number of ways. See below for more details.

### Module system: no support for untrusted modules

ICS 24 (Host Requirements) gives the [following requirement](https://github.com/cosmos/ibc/blob/master/spec/core/ics-024-host-requirements/README.md#module-system) about the module system that the host state machine must support:

> The host state machine must support a module system, whereby self-contained, potentially mutually distrusted packages of code can safely execute on the same ledger [...].
**This crate currently does not support mutually distrusted packages**. That is, modules on the host state machine are assumed to be fully trusted. In practice, this means that every module has either been written by the host state machine developers, or fully vetted by them.

### Port system: No object capability system

ICS 5 (Port Allocation) requires the host system to support either object-capability reference or source authentication for modules.

> In the former object-capability case, the IBC handler must have the ability to generate object-capabilities, unique, opaque references which can be passed to a module and will not be duplicable by other modules. [...]
Expand All @@ -36,6 +37,7 @@ ICS 5 (Port Allocation) requires the host system to support either object-capabi
For more background on this, see [this issue](https://github.com/informalsystems/ibc-rs/issues/2159).

### Port system: transferring and releasing a port

ICS 5 (Port Allocation) requires the IBC handler to permit [transferring ownership of a port](https://github.com/cosmos/ibc/tree/master/spec/core/ics-005-port-allocation#transferring-ownership-of-a-port) and [releasing a port](https://github.com/cosmos/ibc/tree/master/spec/core/ics-005-port-allocation#releasing-a-port).

We currently support neither.
Expand Down Expand Up @@ -65,5 +67,4 @@ Unless required by applicable law or agreed to in writing, software distributed

[//]: # (general links)

[ibc-rs]: https://github.com/cosmos/ibc-rs
[IBC]: https://github.com/cosmos/ibc
6 changes: 3 additions & 3 deletions crates/ibc/src/applications/transfer/acknowledgement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ impl Acknowledgement {
}

pub fn from_error(err: TokenTransferError) -> Self {
Self::Error(format!("{}: {}", ACK_ERR_STR, err))
Self::Error(format!("{ACK_ERR_STR}: {err}"))
}
}

Expand All @@ -53,8 +53,8 @@ impl AsRef<[u8]> for Acknowledgement {
impl Display for Acknowledgement {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
match self {
Acknowledgement::Success(_) => write!(f, "{}", ACK_SUCCESS_B64),
Acknowledgement::Error(err_str) => write!(f, "{}", err_str),
Acknowledgement::Success(_) => write!(f, "{ACK_SUCCESS_B64}"),
Acknowledgement::Error(err_str) => write!(f, "{err_str}"),
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion crates/ibc/src/applications/transfer/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ where

// https://github.com/cosmos/cosmos-sdk/blob/master/docs/architecture/adr-028-public-key-addresses.md
pub fn cosmos_adr028_escrow_address(port_id: &PortId, channel_id: &ChannelId) -> Vec<u8> {
let contents = format!("{}/{}", port_id, channel_id);
let contents = format!("{port_id}/{channel_id}");

let mut hasher = Sha256::new();
hasher.update(VERSION.as_bytes());
Expand Down
2 changes: 1 addition & 1 deletion crates/ibc/src/applications/transfer/denom.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ impl Display for TracePath {
.map(|prefix| prefix.to_string())
.collect::<Vec<String>>()
.join("/");
write!(f, "{}", path)
write!(f, "{path}")
}
}

Expand Down
2 changes: 1 addition & 1 deletion crates/ibc/src/applications/transfer/msgs/transfer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ impl TryFrom<RawMsgTransfer> for MsgTransfer {

let timeout_height: TimeoutHeight = raw_msg.timeout_height.try_into().map_err(|e| {
TokenTransferError::InvalidPacketTimeoutHeight {
context: format!("invalid timeout height {}", e),
context: format!("invalid timeout height {e}"),
}
})?;

Expand Down
16 changes: 6 additions & 10 deletions crates/ibc/src/clients/ics07_tendermint/client_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,26 +117,23 @@ impl ClientState {
if trusting_period <= Duration::new(0, 0) {
return Err(Error::InvalidTrustThreshold {
reason: format!(
"ClientState trusting period ({:?}) must be greater than zero",
trusting_period
"ClientState trusting period ({trusting_period:?}) must be greater than zero"
),
});
}

if unbonding_period <= Duration::new(0, 0) {
return Err(Error::InvalidTrustThreshold {
reason: format!(
"ClientState unbonding period ({:?}) must be greater than zero",
unbonding_period
"ClientState unbonding period ({unbonding_period:?}) must be greater than zero"
),
});
}

if trusting_period >= unbonding_period {
return Err(Error::InvalidTrustThreshold {
reason: format!(
"ClientState trusting period ({:?}) must be smaller than unbonding period ({:?})",
trusting_period, unbonding_period,
"ClientState trusting period ({trusting_period:?}) must be smaller than unbonding period ({unbonding_period:?})"
),
});
}
Expand Down Expand Up @@ -166,8 +163,7 @@ impl ClientState {
if key.trim().is_empty() {
return Err(Error::Validation {
reason: format!(
"ClientState upgrade-path key at index {:?} cannot be empty",
idx
"ClientState upgrade-path key at index {idx:?} cannot be empty"
),
});
}
Expand Down Expand Up @@ -286,7 +282,7 @@ impl ClientState {

if trusted_consensus_state.next_validators_hash != trusted_val_hash {
return Err(Error::MisbehaviourTrustedValidatorHashMismatch {
trusted_validator_set: header.trusted_validator_set.clone(),
trusted_validator_set: header.trusted_validator_set.validators().clone(),
next_validators_hash: trusted_consensus_state.next_validators_hash,
trusted_val_hash,
}
Expand Down Expand Up @@ -1207,7 +1203,7 @@ impl TryFrom<RawTmClientState> for ClientState {
trust_level
.try_into()
.map_err(|e| Error::InvalidTrustThreshold {
reason: format!("{}", e),
reason: format!("{e}"),
})?
};

Expand Down
2 changes: 1 addition & 1 deletion crates/ibc/src/clients/ics07_tendermint/consensus_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ impl TryFrom<RawConsensusState> for ConsensusState {
let timestamp = proto_timestamp
.try_into()
.map_err(|e| Error::InvalidRawClientState {
reason: format!("invalid timestamp: {}", e),
reason: format!("invalid timestamp: {e}"),
})?;

Ok(Self {
Expand Down
4 changes: 2 additions & 2 deletions crates/ibc/src/clients/ics07_tendermint/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use tendermint::account::Id;
use tendermint::{Error as TendermintError, Hash};
use tendermint_light_client_verifier::errors::VerificationErrorDetail as LightClientErrorDetail;
use tendermint_light_client_verifier::operations::VotingPowerTally;
use tendermint_light_client_verifier::types::ValidatorSet;
use tendermint_light_client_verifier::types::Validator;
use tendermint_light_client_verifier::Verdict;

#[derive(Debug, Display)]
Expand Down Expand Up @@ -105,7 +105,7 @@ pub enum Error {
},
/// trusted validators `{trusted_validator_set:?}`, does not hash to latest trusted validators. Expected: `{next_validators_hash}`, got: `{trusted_val_hash}`
MisbehaviourTrustedValidatorHashMismatch {
trusted_validator_set: ValidatorSet,
trusted_validator_set: Vec<Validator>,
next_validators_hash: Hash,
trusted_val_hash: Hash,
},
Expand Down
3 changes: 1 addition & 2 deletions crates/ibc/src/core/ics02_client/handler/create_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -176,8 +176,7 @@ pub fn process(
)));

output.log(format!(
"success: generated new client identifier: {}",
client_id
"success: generated new client identifier: {client_id}"
));

Ok(output.with_result(result))
Expand Down
1 change: 0 additions & 1 deletion crates/ibc/src/core/ics02_client/msgs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ pub mod misbehaviour;
pub mod update_client;
pub mod upgrade_client;

#[allow(clippy::large_enum_variant)]
#[derive(Clone, Debug)]
pub enum ClientMsg {
CreateClient(MsgCreateClient),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,8 +133,7 @@ pub(crate) fn process(
};

output.log(format!(
"success: conn_open_init: generated new connection identifier: {}",
conn_id_on_a
"success: conn_open_init: generated new connection identifier: {conn_id_on_a}",
));

{
Expand Down
1 change: 0 additions & 1 deletion crates/ibc/src/core/ics04_channel/channel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,6 @@ impl ChannelEnd {
self.ordering.eq(other)
}

#[allow(clippy::ptr_arg)]
pub fn connection_hops_matches(&self, other: &Vec<ConnectionId>) -> bool {
self.connection_hops.eq(other)
}
Expand Down
3 changes: 1 addition & 2 deletions crates/ibc/src/core/ics04_channel/handler/chan_open_init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,7 @@ pub(crate) fn process<Ctx: ChannelReader>(
let chan_id_on_a = ChannelId::new(ctx_a.channel_counter()?);

output.log(format!(
"success: channel open init with channel identifier: {}",
chan_id_on_a
"success: channel open init with channel identifier: {chan_id_on_a}"
));

let result = ChannelResult {
Expand Down
3 changes: 1 addition & 2 deletions crates/ibc/src/core/ics04_channel/handler/chan_open_try.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,7 @@ pub(crate) fn process<Ctx: ChannelReader>(
let chan_id_on_b = ChannelId::new(ctx_b.channel_counter()?);

output.log(format!(
"success: channel open try with channel identifier: {}",
chan_id_on_b
"success: channel open try with channel identifier: {chan_id_on_b}"
));

let result = ChannelResult {
Expand Down
2 changes: 1 addition & 1 deletion crates/ibc/src/core/ics04_channel/timeout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ impl From<Height> for TimeoutHeight {
impl Display for TimeoutHeight {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
match self {
TimeoutHeight::At(timeout_height) => write!(f, "{}", timeout_height),
TimeoutHeight::At(timeout_height) => write!(f, "{timeout_height}"),
TimeoutHeight::Never => write!(f, "no timeout"),
}
}
Expand Down
4 changes: 2 additions & 2 deletions crates/ibc/src/core/ics23_commitment/commitment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ impl fmt::Debug for CommitmentPrefix {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let converted = core::str::from_utf8(self.as_bytes());
match converted {
Ok(s) => write!(f, "{}", s),
Ok(s) => write!(f, "{s}"),
Err(_e) => write!(f, "<not valid UTF8: {:?}>", self.as_bytes()),
}
}
Expand All @@ -163,7 +163,7 @@ impl Serialize for CommitmentPrefix {
where
S: serde::Serializer,
{
format!("{:?}", self).serialize(serializer)
format!("{self:?}").serialize(serializer)
}
}

Expand Down
2 changes: 1 addition & 1 deletion crates/ibc/src/core/ics23_commitment/merkle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use crate::core::ics23_commitment::error::CommitmentError;
use crate::core::ics23_commitment::specs::ProofSpecs;

pub fn apply_prefix(prefix: &CommitmentPrefix, mut path: Vec<String>) -> MerklePath {
let mut key_path: Vec<String> = vec![format!("{:?}", prefix)];
let mut key_path: Vec<String> = vec![format!("{prefix:?}")];
key_path.append(&mut path);
MerklePath { key_path }
}
Expand Down
4 changes: 2 additions & 2 deletions crates/ibc/src/core/ics24_host/identifier.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ impl ChainId {
/// ```
pub fn new(name: String, version: u64) -> Self {
Self {
id: format!("{}-{}", name, version),
id: format!("{name}-{version}"),
version,
}
}
Expand Down Expand Up @@ -203,7 +203,7 @@ impl ClientId {
/// ```
pub fn new(client_type: ClientType, counter: u64) -> Result<Self, ValidationError> {
let prefix = client_type.as_str();
let id = format!("{}-{}", prefix, counter);
let id = format!("{prefix}-{counter}");
Self::from_str(id.as_str())
}

Expand Down
Loading

0 comments on commit 4c16095

Please sign in to comment.