Kaynağa Gözat

general clean up and run cargo clippy for all bins

ghassmo 4 yıl önce
ebeveyn
işleme
9f819b0dba

+ 5 - 5
bin/dnetview/src/model.rs

@@ -8,7 +8,7 @@ use darkfi::util::NanoTimestamp;
 type MsgLog = Vec<(NanoTimestamp, String, String)>;
 type MsgMap = Mutex<FxHashMap<String, MsgLog>>;
 
-#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
+#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Eq)]
 pub enum Session {
     Inbound,
     Outbound,
@@ -16,7 +16,7 @@ pub enum Session {
     Offline,
 }
 
-#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
+#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Eq)]
 pub enum SelectableObject {
     Node(NodeInfo),
     Session(SessionInfo),
@@ -43,7 +43,7 @@ impl Model {
     }
 }
 
-#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
+#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Eq)]
 pub struct NodeInfo {
     pub id: String,
     pub name: String,
@@ -66,7 +66,7 @@ impl NodeInfo {
     }
 }
 
-#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
+#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Eq)]
 pub struct SessionInfo {
     // TODO: make all values optional to handle empty sessions
     pub id: String,
@@ -90,7 +90,7 @@ impl SessionInfo {
     }
 }
 
-#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
+#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Eq)]
 pub struct ConnectInfo {
     // TODO: make all values optional to handle empty connections
     pub id: String,

+ 10 - 9
bin/dnetview/src/view.rs

@@ -1,4 +1,3 @@
-use async_std::sync::Mutex;
 use fxhash::FxHashMap;
 use tui::widgets::ListState;
 
@@ -125,7 +124,7 @@ impl<'a> View {
 
         self.render_ids(f, slice.clone())?;
 
-        if self.id_list.ids.is_empty() {
+        if !self.id_list.ids.is_empty() {
             // we have not received any data
             Ok(())
         } else {
@@ -133,7 +132,8 @@ impl<'a> View {
             match self.id_list.state.selected() {
                 Some(i) => match self.id_list.ids.get(i) {
                     Some(i) => {
-                        self.render_info(f, slice.clone(), i.to_string())?;
+                        let id = i.clone();
+                        self.render_info(f, slice, id)?;
                         Ok(())
                     }
                     None => Err(DnetViewError::NoIdAtIndex),
@@ -217,7 +217,7 @@ impl<'a> View {
         Ok(())
     }
 
-    fn parse_msg_list<'_a>(&self, connect: &ConnectInfo) -> DnetViewResult<List<'a>> {
+    fn parse_msg_list(&self, connect: &ConnectInfo) -> DnetViewResult<List<'a>> {
         let send_style = Style::default().fg(Color::LightCyan);
         let recv_style = Style::default().fg(Color::DarkGray);
         let mut texts = Vec::new();
@@ -225,8 +225,8 @@ impl<'a> View {
         let log = self.msg_list.msg_map.get(&connect.id);
         match log {
             Some(values) => {
-                for (i, (t, k, v)) in values.into_iter().enumerate() {
-                    lines.push(Span::from(match k.as_str() {
+                for (i, (t, k, v)) in values.iter().enumerate() {
+                    lines.push(match k.as_str() {
                         "send" => {
                             Span::styled(format!("{}  {}             S: {}", i, t, v), send_style)
                         }
@@ -234,7 +234,7 @@ impl<'a> View {
                             Span::styled(format!("{}  {}             R: {}", i, t, v), recv_style)
                         }
                         data => return Err(DnetViewError::UnexpectedData(data.to_string())),
-                    }));
+                    });
                 }
             }
             None => return Err(DnetViewError::CannotFindId),
@@ -272,7 +272,7 @@ impl<'a> View {
                             lines.push(Spans::from(node_info));
                         }
                         None => {
-                            let node_info = Span::styled(format!("External addr: Null"), style);
+                            let node_info = Span::styled("External addr: Null".to_string(), style);
                             lines.push(Spans::from(node_info));
                         }
                     }
@@ -397,7 +397,8 @@ impl MsgList {
             Some(i) => i + self.msg_len,
             None => 0,
         };
-        Ok(self.state.select(Some(i)))
+        self.state.select(Some(i));
+        Ok(())
     }
 
     pub fn unselect(&mut self) {

+ 1 - 2
bin/ircd/src/main.rs

@@ -69,10 +69,9 @@ impl Ircd {
 
     fn start_p2p_receive_loop(&self, executor: Arc<Executor<'_>>, p2p_receiver: Receiver<Privmsg>) {
         let senders = self.senders.clone();
-        let p2p_receiver_cloned = p2p_receiver.clone();
         executor
             .spawn(async move {
-                while let Ok(msg) = p2p_receiver_cloned.recv().await {
+                while let Ok(msg) = p2p_receiver.recv().await {
                     senders.notify(msg).await;
                 }
             })

+ 1 - 1
bin/ircd/src/protocol_privmsg.rs

@@ -49,7 +49,7 @@ impl ProtocolPrivmsg {
 
     async fn handle_receive_msg(self: Arc<Self>) -> Result<()> {
         debug!(target: "ircd", "ProtocolPrivmsg::handle_receive_msg() [START]");
-        let exclude_list = vec![self.channel.address().clone()];
+        let exclude_list = vec![self.channel.address()];
 
         // once a channel get started
         let msgs_buffer = self.msgs.lock().await;

+ 1 - 0
bin/ircd/src/server.rs

@@ -41,6 +41,7 @@ pub struct IrcServerConnection {
 }
 
 impl IrcServerConnection {
+    #[allow(clippy::too_many_arguments)]
     pub fn new(
         write_stream: WriteHalf<TcpStream>,
         peer_address: SocketAddr,

+ 1 - 1
bin/tau/tau-cli/src/util.rs

@@ -12,7 +12,7 @@ use darkfi::{util::Timestamp, Result};
 
 /// Parse due date (e.g. "1503" for 15 March) as i64 timestamp.
 pub fn due_as_timestamp(due: &str) -> Option<i64> {
-    if due.len() != 4 || !due.parse::<u32>().is_ok() {
+    if due.len() != 4 || due.parse::<u32>().is_err() {
         error!("Due date must be digits of length 4 (e.g. \"1503\" for 15 March)");
         return None
     }

+ 4 - 2
bin/tau/tau-cli/src/view.rs

@@ -1,3 +1,5 @@
+use std::fmt::Write;
+
 use prettytable::{
     cell,
     format::{consts::FORMAT_NO_COLSEP, FormatBuilder, LinePosition, LineSeparator},
@@ -114,7 +116,7 @@ pub fn print_task_info(taskinfo: TaskInfo) -> Result<()> {
 pub fn comments_as_string(comments: Vec<Comment>) -> String {
     let mut comments_str = String::new();
     for comment in comments {
-        comments_str.push_str(&format!("{}\n", comment));
+        writeln!(comments_str, "{}", comment).unwrap();
     }
     comments_str.pop();
     comments_str
@@ -123,7 +125,7 @@ pub fn comments_as_string(comments: Vec<Comment>) -> String {
 pub fn events_as_string(events: Vec<TaskEvent>) -> String {
     let mut events_str = String::new();
     for event in events {
-        events_str.push_str(&format!("State changed to {} at {}\n", event.action, event.timestamp));
+        writeln!(events_str, "State changed to {} at {}", event.action, event.timestamp).unwrap();
     }
     events_str
 }

+ 1 - 1
bin/tau/taud/src/month_tasks.rs

@@ -15,7 +15,7 @@ use crate::{
     util::{load, save},
 };
 
-#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
 pub struct MonthTasks {
     created_at: Timestamp,
     task_tks: Vec<String>,

+ 4 - 4
bin/tau/taud/src/task_info.rs

@@ -29,7 +29,7 @@ impl TaskEvent {
     }
 }
 
-#[derive(Clone, Debug, Serialize, Deserialize, SerialDecodable, SerialEncodable, PartialEq)]
+#[derive(Clone, Debug, Serialize, Deserialize, SerialDecodable, SerialEncodable, PartialEq, Eq)]
 pub struct Comment {
     content: String,
     author: String,
@@ -48,11 +48,11 @@ impl Comment {
 
 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
 pub struct TaskEvents(Vec<TaskEvent>);
-#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
 pub struct TaskComments(Vec<Comment>);
-#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
 pub struct TaskProjects(Vec<String>);
-#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
 pub struct TaskAssigns(Vec<String>);
 
 #[derive(Clone, Debug, Serialize, Deserialize, SerialEncodable, SerialDecodable, PartialEq)]

+ 2 - 2
src/consensus/block.rs

@@ -21,7 +21,7 @@ use crate::{
 };
 
 /// This struct represents a tuple of the form (version, state, epoch, slot, timestamp, merkle_root).
-#[derive(Debug, Clone, PartialEq, SerialEncodable, SerialDecodable)]
+#[derive(Debug, Clone, PartialEq, Eq, SerialEncodable, SerialDecodable)]
 pub struct Header {
     /// Block version
     pub version: u8,
@@ -200,7 +200,7 @@ impl fmt::Display for BlockProposal {
     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
         formatter.write_fmt(format_args!(
             "BlockProposal {{ leader: {}, hash: {}, epoch: {}, slot: {}, txs: {} }}",
-            self.address.to_string(),
+            self.address,
             self.block.header.headerhash(),
             self.block.header.epoch,
             self.block.header.slot,

+ 1 - 1
src/consensus/metadata.rs

@@ -3,7 +3,7 @@ use crate::util::serial::{SerialDecodable, SerialEncodable};
 
 /// This struct represents [`Block`](super::Block) information used by the Ouroboros
 /// Praos consensus protocol.
-#[derive(Debug, Clone, PartialEq, SerialEncodable, SerialDecodable)]
+#[derive(Debug, Clone, PartialEq, Eq, SerialEncodable, SerialDecodable)]
 pub struct Metadata {
     /// Proof that the stakeholder is the block owner
     pub proof: String,

+ 1 - 1
src/consensus/participant.rs

@@ -9,7 +9,7 @@ use crate::{
 
 /// This struct represents a tuple of the form:
 /// (`node_address`, `slot_joined`, `last_slot_voted`, `slot_quarantined`)
-#[derive(Debug, Clone, PartialEq, SerialEncodable, SerialDecodable)]
+#[derive(Debug, Clone, PartialEq, Eq, SerialEncodable, SerialDecodable)]
 pub struct Participant {
     /// Node wallet address
     pub address: Address,

+ 1 - 1
src/consensus/vote.rs

@@ -8,7 +8,7 @@ use crate::{
 };
 
 /// This struct represents a `Vote` used by the Streamlet consensus
-#[derive(Debug, Clone, PartialEq, SerialDecodable, SerialEncodable)]
+#[derive(Debug, Clone, PartialEq, Eq, SerialDecodable, SerialEncodable)]
 pub struct Vote {
     /// Node public key
     pub public_key: PublicKey,

+ 1 - 1
src/crypto/burn_proof.rs

@@ -23,7 +23,7 @@ use crate::{
     Result,
 };
 
-#[derive(Debug, Clone, PartialEq, SerialEncodable, SerialDecodable)]
+#[derive(Debug, Clone, PartialEq, Eq, SerialEncodable, SerialDecodable)]
 pub struct BurnRevealedValues {
     pub value_commit: DrkValueCommit,
     pub token_commit: DrkValueCommit,

+ 1 - 1
src/crypto/coin.rs

@@ -7,7 +7,7 @@ use crate::{
     Result,
 };
 
-#[derive(Clone, Copy, PartialEq, Debug)]
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
 pub struct Coin(pub pallas::Base);
 
 impl Coin {

+ 3 - 3
src/crypto/keypair.rs

@@ -16,7 +16,7 @@ use crate::{
     Error, Result,
 };
 
-#[derive(Copy, Clone, PartialEq, Debug)]
+#[derive(Copy, Clone, PartialEq, Eq, Debug)]
 #[cfg(feature = "serde")]
 #[derive(serde::Deserialize, serde::Serialize)]
 pub struct Keypair {
@@ -36,7 +36,7 @@ impl Keypair {
     }
 }
 
-#[derive(Copy, Clone, PartialEq, Debug, SerialDecodable, SerialEncodable)]
+#[derive(Copy, Clone, PartialEq, Eq, Debug, SerialDecodable, SerialEncodable)]
 pub struct SecretKey(pub pallas::Base);
 
 impl SecretKey {
@@ -57,7 +57,7 @@ impl SecretKey {
     }
 }
 
-#[derive(Copy, Clone, PartialEq, Debug, SerialDecodable, SerialEncodable)]
+#[derive(Copy, Clone, PartialEq, Eq, Debug, SerialDecodable, SerialEncodable)]
 pub struct PublicKey(pub pallas::Point);
 
 impl PublicKey {

+ 1 - 1
src/crypto/mint_proof.rs

@@ -19,7 +19,7 @@ use crate::{
     Result,
 };
 
-#[derive(Debug, Clone, PartialEq, SerialEncodable, SerialDecodable)]
+#[derive(Debug, Clone, PartialEq, Eq, SerialEncodable, SerialDecodable)]
 pub struct MintRevealedValues {
     pub value_commit: DrkValueCommit,
     pub token_commit: DrkValueCommit,

+ 1 - 1
src/crypto/mod.rs

@@ -26,7 +26,7 @@ pub use proof::Proof;
 
 use keypair::SecretKey;
 
-#[derive(Copy, Clone, Debug, PartialEq)]
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
 pub struct OwnCoin {
     pub coin: coin::Coin,
     pub note: note::Note,

+ 2 - 2
src/crypto/note.rs

@@ -16,7 +16,7 @@ pub const NOTE_PLAINTEXT_SIZE: usize = 32 + 8 + 32 + 32 + 32 + 32;
 pub const AEAD_TAG_SIZE: usize = 16;
 pub const ENC_CIPHERTEXT_SIZE: usize = NOTE_PLAINTEXT_SIZE + AEAD_TAG_SIZE;
 
-#[derive(Copy, Clone, Debug, PartialEq, SerialEncodable, SerialDecodable)]
+#[derive(Copy, Clone, Debug, PartialEq, Eq, SerialEncodable, SerialDecodable)]
 pub struct Note {
     pub serial: DrkSerial,
     pub value: u64,
@@ -48,7 +48,7 @@ impl Note {
     }
 }
 
-#[derive(Debug, Clone, PartialEq, SerialEncodable, SerialDecodable)]
+#[derive(Debug, Clone, PartialEq, Eq, SerialEncodable, SerialDecodable)]
 pub struct EncryptedNote {
     ciphertext: [u8; ENC_CIPHERTEXT_SIZE],
     ephem_public: PublicKey,

+ 1 - 1
src/crypto/nullifier.rs

@@ -9,7 +9,7 @@ use crate::{
     Result,
 };
 
-#[derive(Clone, Copy, Debug, PartialEq)]
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 pub struct Nullifier(pub(crate) pallas::Base);
 
 impl Nullifier {

+ 1 - 1
src/crypto/proof.rs

@@ -44,7 +44,7 @@ impl ProvingKey {
     }
 }
 
-#[derive(Clone, Debug, PartialEq)]
+#[derive(Clone, Debug, PartialEq, Eq)]
 pub struct Proof(Vec<u8>);
 
 impl AsRef<[u8]> for Proof {

+ 1 - 1
src/crypto/schnorr.rs

@@ -17,7 +17,7 @@ use crate::{
     Result,
 };
 
-#[derive(Debug, Clone, PartialEq)]
+#[derive(Debug, Clone, PartialEq, Eq)]
 pub struct Signature {
     commit: pallas::Point,
     response: pallas::Scalar,

+ 2 - 4
src/net/channel.rs

@@ -117,10 +117,8 @@ impl Channel {
     /// the channel has been closed.
     pub async fn stop(&self) {
         debug!(target: "net", "Channel::stop() [START, address={}]", self.address());
-        let mut stopped = *self.stopped.lock().await;
-        if !stopped {
-            stopped = true;
-            drop(stopped);
+        if !(*self.stopped.lock().await) {
+            *self.stopped.lock().await = true;
 
             self.stop_subscriber.notify(Error::ChannelStopped).await;
             self.receive_task.stop().await;

+ 1 - 2
src/net/session/outbound_session.rs

@@ -224,8 +224,7 @@ impl OutboundSession {
 
             warn!(target: "net", "Hosts address pool is empty. Retrying connect slot #{}", slot_number);
 
-            let retry_time = p2p.settings().outbound_retry_seconds.clone();
-            async_util::sleep(retry_time).await;
+            async_util::sleep(p2p.settings().outbound_retry_seconds).await;
         }
     }
 

+ 4 - 4
src/tx/mod.rs

@@ -25,7 +25,7 @@ pub mod builder;
 mod partial;
 
 /// A DarkFi transaction
-#[derive(Debug, Clone, PartialEq, SerialEncodable, SerialDecodable)]
+#[derive(Debug, Clone, PartialEq, Eq, SerialEncodable, SerialDecodable)]
 pub struct Transaction {
     /// Clear inputs
     pub clear_inputs: Vec<TransactionClearInput>,
@@ -36,7 +36,7 @@ pub struct Transaction {
 }
 
 /// A transaction's clear input
-#[derive(Debug, Clone, PartialEq, SerialEncodable, SerialDecodable)]
+#[derive(Debug, Clone, PartialEq, Eq, SerialEncodable, SerialDecodable)]
 pub struct TransactionClearInput {
     /// Input's value (amount)
     pub value: u64,
@@ -53,7 +53,7 @@ pub struct TransactionClearInput {
 }
 
 /// A transaction's anonymous input
-#[derive(Debug, Clone, PartialEq, SerialEncodable, SerialDecodable)]
+#[derive(Debug, Clone, PartialEq, Eq, SerialEncodable, SerialDecodable)]
 pub struct TransactionInput {
     /// Zero-knowledge proof for the input
     pub burn_proof: Proof,
@@ -64,7 +64,7 @@ pub struct TransactionInput {
 }
 
 /// A transaction's anonymous output
-#[derive(Debug, Clone, PartialEq, SerialEncodable, SerialDecodable)]
+#[derive(Debug, Clone, PartialEq, Eq, SerialEncodable, SerialDecodable)]
 pub struct TransactionOutput {
     /// Zero-knowledge proof for the output
     pub mint_proof: Proof,

+ 2 - 0
src/util/time.rs

@@ -28,6 +28,7 @@ use crate::{
     SerialDecodable,
     PartialEq,
     PartialOrd,
+    Eq,
 )]
 pub struct Timestamp(pub i64);
 
@@ -68,6 +69,7 @@ impl std::fmt::Display for Timestamp {
     SerialDecodable,
     PartialEq,
     PartialOrd,
+    Eq,
 )]
 pub struct NanoTimestamp(pub i64);
 

+ 1 - 1
src/zk/gadget/cmp.rs

@@ -47,7 +47,7 @@ impl<F: FieldExt> IsZeroChip<F> {
             let q_enable = q_enable(meta);
             let value_inv = meta.query_advice(value_inv, Rotation::cur());
 
-            is_zero_expr = Expression::Constant(F::one()) - value.clone() * value_inv.clone();
+            is_zero_expr = Expression::Constant(F::one()) - value.clone() * value_inv;
             vec![q_enable * value * is_zero_expr.clone()]
         });
 

+ 1 - 1
src/zk/vm.rs

@@ -26,7 +26,7 @@ use pasta_curves::{group::Curve, pallas, Fp};
 
 use super::gadget::{
     arithmetic::{ArithChip, ArithConfig, ArithInstruction},
-    even_bits::{EvenBitsChip, EvenBitsConfig, EvenBitsLookup},
+    even_bits::{EvenBitsChip, EvenBitsConfig},
 };
 
 use super::assign_free_advice;

+ 1 - 1
src/zkas/ast.rs

@@ -2,7 +2,7 @@ use indexmap::IndexMap;
 
 use super::{lexer::Token, opcode::Opcode, types::Type};
 
-#[derive(Copy, PartialEq, Clone, Debug)]
+#[derive(Copy, PartialEq, Eq, Clone, Debug)]
 #[repr(u8)]
 pub enum StatementType {
     Assignment = 0x00,

+ 1 - 1
src/zkas/types.rs

@@ -1,5 +1,5 @@
 /// Types supported by the VM
-#[derive(Copy, Clone, PartialEq, Debug)]
+#[derive(Copy, Clone, PartialEq, Eq, Debug)]
 #[repr(u8)]
 pub enum Type {
     /// Elliptic curve point