Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

clippy: Fix cargo clippy #57

Closed
wants to merge 9 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ bytes = "1.4.0"
cid = "0.10.1"
ed25519-dalek = "1.0.1"
futures = "0.3.27"
futures-rustls = "0.22.2"
futures-timer = "3.0.2"
hex-literal = "0.4.1"
indexmap = { version = "2.0.0", features = ["std"] }
Expand Down
9 changes: 3 additions & 6 deletions examples/custom_executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,12 +144,9 @@ async fn main() {
tokio::select! {
_ = executor2.next() => {}
_ = litep2p2.next_event() => {},
event = ping_event_stream2.next() => match event {
Some(PingEvent::Ping { peer, ping }) => tracing::info!(
"ping time with {peer:?}: {ping:?}"
),
_ => {}
}
event = ping_event_stream2.next() => if let Some(PingEvent::Ping { peer, ping }) = event { tracing::info!(
"ping time with {peer:?}: {ping:?}"
) }
}
}
}
2 changes: 1 addition & 1 deletion examples/custom_protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ async fn main() {
}
});

for message in vec![
for message in [
b"hello, world".to_vec(),
b"testing 123".to_vec(),
b"goodbye, world".to_vec(),
Expand Down
12 changes: 3 additions & 9 deletions examples/echo_notification.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,22 +50,16 @@ async fn client_event_loop(mut litep2p: Litep2p, mut handle: NotificationHandle,
loop {
tokio::select! {
_ = litep2p.next_event() => {}
event = handle.next() => match event.unwrap() {
NotificationEvent::NotificationStreamOpened { .. } => break,
_ => {},
}
event = handle.next() => if let NotificationEvent::NotificationStreamOpened { .. } = event.unwrap() { break }
}
}

// after the substream is open, send notification to server and print the response to stdout
loop {
tokio::select! {
_ = litep2p.next_event() => {}
event = handle.next() => match event.unwrap() {
NotificationEvent::NotificationReceived { peer, notification } => {
println!("received response from server ({peer:?}): {notification:?}");
}
_ => {},
event = handle.next() => if let NotificationEvent::NotificationReceived { peer, notification } = event.unwrap() {
println!("received response from server ({peer:?}): {notification:?}");
},
_ = tokio::time::sleep(Duration::from_secs(3)) => {
handle.send_sync_notification(peer, vec![1, 3, 3, 7]).unwrap();
Expand Down
8 changes: 4 additions & 4 deletions examples/gossiping.rs
Original file line number Diff line number Diff line change
Expand Up @@ -243,10 +243,10 @@ async fn main() {
litep2p3.add_known_address(peer2, vec![listen_address.clone()].into_iter());
litep2p4.add_known_address(peer2, vec![listen_address].into_iter());

tokio::spawn(async move { while let Some(_) = litep2p1.next_event().await {} });
tokio::spawn(async move { while let Some(_) = litep2p2.next_event().await {} });
tokio::spawn(async move { while let Some(_) = litep2p3.next_event().await {} });
tokio::spawn(async move { while let Some(_) = litep2p4.next_event().await {} });
tokio::spawn(async move { while (litep2p1.next_event().await).is_some() {} });
tokio::spawn(async move { while (litep2p2.next_event().await).is_some() {} });
tokio::spawn(async move { while (litep2p3.next_event().await).is_some() {} });
tokio::spawn(async move { while (litep2p4.next_event().await).is_some() {} });

// open substreams
tx1.tx_handle.open_substream(peer2).await.unwrap();
Expand Down
5 changes: 2 additions & 3 deletions examples/syncing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,8 +135,7 @@ async fn main() {

// poll `litep2p` to allow connection-related activity to make progress
loop {
match litep2p.next_event().await.unwrap() {
_ => {}
}
litep2p.next_event().await.unwrap();
{}
}
}
4 changes: 2 additions & 2 deletions src/codec/unsigned_varint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,14 +59,14 @@ impl UnsignedVarint {

let mut bytes = BytesMut::with_capacity(payload.len() + 4);
let mut codec = Self::new(None);
codec.encode(payload.into(), &mut bytes)?;
codec.encode(payload, &mut bytes)?;

Ok(bytes.into())
}

/// Decode `payload` into `BytesMut`.
pub fn decode(payload: &mut BytesMut) -> crate::Result<BytesMut> {
Ok(UviBytes::<Bytes>::default().decode(payload)?.ok_or(Error::InvalidData)?)
UviBytes::<Bytes>::default().decode(payload)?.ok_or(Error::InvalidData)
}
}

Expand Down
6 changes: 6 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,12 @@ pub struct ConfigBuilder {
max_parallel_dials: usize,
}

impl Default for ConfigBuilder {
fn default() -> Self {
Self::new()
}
}

impl ConfigBuilder {
/// Create empty [`ConfigBuilder`].
pub fn new() -> Self {
Expand Down
5 changes: 3 additions & 2 deletions src/crypto/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,9 @@ impl TryFrom<keys_proto::PublicKey> for PublicKey {
.ok_or_else(|| Error::Other(format!("Unknown key type: {}", pubkey.r#type)))?;

match key_type {
keys_proto::KeyType::Ed25519 =>
Ok(ed25519::PublicKey::decode(&pubkey.data).map(PublicKey::Ed25519)?),
keys_proto::KeyType::Ed25519 => {
Ok(ed25519::PublicKey::decode(&pubkey.data).map(PublicKey::Ed25519)?)
}
_ => unimplemented!("unsupported key type"),
}
}
Expand Down
18 changes: 8 additions & 10 deletions src/crypto/noise/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ impl NoiseContext {

/// Get remote public key from the received Noise payload.
// TODO: refactor
pub fn get_remote_public_key(&mut self, reply: &Vec<u8>) -> crate::Result<PublicKey> {
pub fn get_remote_public_key(&mut self, reply: &[u8]) -> crate::Result<PublicKey> {
if reply.len() <= 2 {
return Err(error::Error::InvalidData);
}
Expand All @@ -192,10 +192,8 @@ impl NoiseContext {

let payload = handshake_schema::NoiseHandshakePayload::decode(inner.as_slice())?;

Ok(PublicKey::from_protobuf_encoding(
&payload.identity_key.ok_or(error::Error::NegotiationError(
error::NegotiationError::PeerIdMissing,
))?,
PublicKey::from_protobuf_encoding(&payload.identity_key.ok_or(
error::Error::NegotiationError(error::NegotiationError::PeerIdMissing),
)?)
}

Expand Down Expand Up @@ -600,7 +598,7 @@ impl<S: AsyncRead + AsyncWrite + Unpin> AsyncWrite for NoiseSocket<S> {
return Poll::Ready(Err(io::ErrorKind::InvalidData.into()));
}
Ok(nwritten) => {
this.encrypt_buffer[offset + 0] = (nwritten >> 8) as u8;
this.encrypt_buffer[offset] = (nwritten >> 8) as u8;
this.encrypt_buffer[offset + 1] = (nwritten & 0xff) as u8;

if let Some(next_chunk) = chunks.peek() {
Expand Down Expand Up @@ -691,15 +689,15 @@ pub async fn handshake<S: AsyncRead + AsyncWrite + Unpin>(
// write initial message
let first_message = noise.first_message(Role::Dialer);
let _ = io.write(&first_message).await?;
let _ = io.flush().await?;
io.flush().await?;

// read back response which contains the remote peer id
let message = noise.read_handshake_message(&mut io).await?;

// send the final message which contains local peer id
let second_message = noise.second_message();
let _ = io.write(&second_message).await?;
let _ = io.flush().await?;
io.flush().await?;

parse_peer_id(&message)?
}
Expand All @@ -710,7 +708,7 @@ pub async fn handshake<S: AsyncRead + AsyncWrite + Unpin>(
// send local peer id.
let second_message = noise.second_message();
let _ = io.write(&second_message).await?;
let _ = io.flush().await?;
io.flush().await?;

// read remote's second message which contains their peer id
let message = noise.read_handshake_message(&mut io).await?;
Expand Down Expand Up @@ -795,7 +793,7 @@ mod tests {

#[test]
fn invalid_peer_id_schema() {
match parse_peer_id(&vec![1, 2, 3, 4]).unwrap_err() {
match parse_peer_id(&[1, 2, 3, 4]).unwrap_err() {
crate::Error::ParseError(_) => {}
_ => panic!("invalid error"),
}
Expand Down
5 changes: 3 additions & 2 deletions src/crypto/tls/verifier.rs
Original file line number Diff line number Diff line change
Expand Up @@ -248,8 +248,9 @@ impl From<certificate::VerificationError> for rustls::Error {
use webpki::Error::*;
match e {
InvalidSignatureForPublicKey => rustls::Error::InvalidCertificateSignature,
UnsupportedSignatureAlgorithm | UnsupportedSignatureAlgorithmForPublicKey =>
rustls::Error::InvalidCertificateSignatureType,
UnsupportedSignatureAlgorithm | UnsupportedSignatureAlgorithmForPublicKey => {
rustls::Error::InvalidCertificateSignatureType
}
e => rustls::Error::InvalidCertificateData(format!("invalid peer certificate: {e}")),
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,11 @@ pub(crate) struct DefaultExecutor;

impl Executor for DefaultExecutor {
fn run(&self, future: Pin<Box<dyn Future<Output = ()> + Send>>) {
let _ = tokio::spawn(future);
tokio::spawn(future);
}

fn run_with_name(&self, _: &'static str, future: Pin<Box<dyn Future<Output = ()> + Send>>) {
let _ = tokio::spawn(future);
tokio::spawn(future);
}
}

Expand Down
12 changes: 10 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,14 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

#![allow(clippy::large_enum_variant)]
#![allow(clippy::result_large_err)]
#![allow(clippy::result_unit_err)]
#![allow(clippy::too_many_arguments)]
#![allow(clippy::should_implement_trait)]
#![allow(clippy::assign_op_pattern)]
#![allow(clippy::derived_hash_with_manual_eq)]

use crate::{
config::Litep2pConfig,
protocol::{
Expand Down Expand Up @@ -219,7 +227,7 @@ impl Litep2p {
);

let main_protocol =
kademlia_config.protocol_names.get(0).expect("protocol name to exist");
kademlia_config.protocol_names.first().expect("protocol name to exist");
let fallback_names = kademlia_config.protocol_names.iter().skip(1).cloned().collect();

let service = transport_manager.register_protocol(
Expand All @@ -245,7 +253,7 @@ impl Litep2p {
let service = transport_manager.register_protocol(
identify_config.protocol.clone(),
Vec::new(),
identify_config.codec.clone(),
identify_config.codec,
);
identify_config.public = Some(litep2p_config.keypair.public().into());

Expand Down
8 changes: 4 additions & 4 deletions src/multistream_select/dialer_select.rs
Original file line number Diff line number Diff line change
Expand Up @@ -272,18 +272,18 @@ impl DialerState {
// encode `/multistream-select/1.0.0` header
let mut bytes = BytesMut::with_capacity(64);
let message = Message::Header(HeaderLine::V1);
let _ = message.encode(&mut bytes).map_err(|_| Error::InvalidData)?;
message.encode(&mut bytes).map_err(|_| Error::InvalidData)?;
let mut header = UnsignedVarint::encode(bytes)?;

// encode proposed protocol
let mut proto_bytes = BytesMut::with_capacity(512);
let message = Message::Protocol(Protocol::try_from(protocol.as_bytes()).unwrap());
let _ = message.encode(&mut proto_bytes).map_err(|_| Error::InvalidData)?;
let proto_bytes = UnsignedVarint::encode(proto_bytes)?;
message.encode(&mut proto_bytes).map_err(|_| Error::InvalidData)?;
let mut proto_bytes = UnsignedVarint::encode(proto_bytes)?;

// TODO: add fallback names

header.append(&mut proto_bytes.into());
header.append(&mut proto_bytes);

Ok((
Self {
Expand Down
20 changes: 12 additions & 8 deletions src/multistream_select/length_delimited.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,11 +128,12 @@ impl<R> LengthDelimited<R> {
while !this.write_buffer.is_empty() {
match this.inner.as_mut().poll_write(cx, this.write_buffer) {
Poll::Pending => return Poll::Pending,
Poll::Ready(Ok(0)) =>
Poll::Ready(Ok(0)) => {
return Poll::Ready(Err(io::Error::new(
io::ErrorKind::WriteZero,
"Failed to write buffered frame.",
))),
)))
}
Poll::Ready(Ok(n)) => this.write_buffer.advance(n),
Poll::Ready(Err(err)) => return Poll::Ready(Err(err)),
}
Expand All @@ -155,12 +156,13 @@ where
match this.read_state {
ReadState::ReadLength { buf, pos } => {
match this.inner.as_mut().poll_read(cx, &mut buf[*pos..*pos + 1]) {
Poll::Ready(Ok(0)) =>
Poll::Ready(Ok(0)) => {
if *pos == 0 {
return Poll::Ready(None);
} else {
return Poll::Ready(Some(Err(io::ErrorKind::UnexpectedEof.into())));
},
}
}
Poll::Ready(Ok(n)) => {
debug_assert_eq!(n, 1);
*pos += n;
Expand Down Expand Up @@ -195,8 +197,9 @@ where
}
ReadState::ReadData { len, pos } => {
match this.inner.as_mut().poll_read(cx, &mut this.read_buffer[*pos..]) {
Poll::Ready(Ok(0)) =>
return Poll::Ready(Some(Err(io::ErrorKind::UnexpectedEof.into()))),
Poll::Ready(Ok(0)) => {
return Poll::Ready(Some(Err(io::ErrorKind::UnexpectedEof.into())))
}
Poll::Ready(Ok(n)) => *pos += n,
Poll::Pending => return Poll::Pending,
Poll::Ready(Err(err)) => return Poll::Ready(Some(Err(err))),
Expand Down Expand Up @@ -242,11 +245,12 @@ where

let len = match u16::try_from(item.len()) {
Ok(len) if len <= MAX_FRAME_SIZE => len,
_ =>
_ => {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Maximum frame size exceeded.",
)),
))
}
};

let mut uvi_buf = unsigned_varint::encode::u16_buffer();
Expand Down
13 changes: 7 additions & 6 deletions src/multistream_select/listener_select.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,8 +138,9 @@ where
Poll::Ready(Some(Ok(Message::Header(h)))) => match h {
HeaderLine::V1 => *this.state = State::SendHeader { io },
},
Poll::Ready(Some(Ok(_))) =>
return Poll::Ready(Err(ProtocolError::InvalidMessage.into())),
Poll::Ready(Some(Ok(_))) => {
return Poll::Ready(Err(ProtocolError::InvalidMessage.into()))
}
Poll::Ready(Some(Err(err))) => return Poll::Ready(Err(From::from(err))),
// Treat EOF error as [`NegotiationError::Failed`], not as
// [`NegotiationError::ProtocolError`], allowing dropping or closing an I/O
Expand Down Expand Up @@ -356,16 +357,16 @@ pub fn listener_negotiate<'a>(
// encode `/multistream-select/1.0.0` header
let mut bytes = BytesMut::with_capacity(64);
let message = Message::Header(HeaderLine::V1);
let _ = message.encode(&mut bytes).map_err(|_| Error::InvalidData)?;
message.encode(&mut bytes).map_err(|_| Error::InvalidData)?;
let mut header = UnsignedVarint::encode(bytes)?;

// encode negotiated protocol
let mut proto_bytes = BytesMut::with_capacity(512);
let message = Message::Protocol(protocol);
let _ = message.encode(&mut proto_bytes).map_err(|_| Error::InvalidData)?;
let proto_bytes = UnsignedVarint::encode(proto_bytes)?;
message.encode(&mut proto_bytes).map_err(|_| Error::InvalidData)?;
let mut proto_bytes = UnsignedVarint::encode(proto_bytes)?;

header.append(&mut proto_bytes.into());
header.append(&mut proto_bytes);

return Ok((supported.clone(), BytesMut::from(&header[..])));
}
Expand Down
5 changes: 3 additions & 2 deletions src/multistream_select/negotiated.rs
Original file line number Diff line number Diff line change
Expand Up @@ -388,8 +388,9 @@ impl Error for NegotiationError {
impl fmt::Display for NegotiationError {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
match self {
NegotiationError::ProtocolError(p) =>
fmt.write_fmt(format_args!("Protocol error: {p}")),
NegotiationError::ProtocolError(p) => {
fmt.write_fmt(format_args!("Protocol error: {p}"))
}
NegotiationError::Failed => fmt.write_str("Protocol negotiation failed."),
}
}
Expand Down
5 changes: 3 additions & 2 deletions src/peer_id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,9 @@ impl PeerId {
pub fn from_multihash(multihash: Multihash) -> Result<PeerId, Multihash> {
match Code::try_from(multihash.code()) {
Ok(Code::Sha2_256) => Ok(PeerId { multihash }),
Ok(Code::Identity) if multihash.digest().len() <= MAX_INLINE_KEY_LENGTH =>
Ok(PeerId { multihash }),
Ok(Code::Identity) if multihash.digest().len() <= MAX_INLINE_KEY_LENGTH => {
Ok(PeerId { multihash })
}
_ => Err(multihash),
}
}
Expand Down
Loading