Explorar o código

cargo clippy over all projects

ghassmo %!s(int64=4) %!d(string=hai) anos
pai
achega
6e6c240891

+ 1 - 1
bin/darkfid/src/rpc_wallet.rs

@@ -326,6 +326,6 @@ impl Darkfid {
             }
         }
 
-        return server_error(RpcError::DecryptionFailed, id)
+        server_error(RpcError::DecryptionFailed, id)
     }
 }

+ 2 - 2
bin/darkotc/src/main.rs

@@ -603,7 +603,7 @@ async fn main() -> Result<()> {
             let mut buf = String::new();
             stdin().read_to_string(&mut buf)?;
 
-            inspect_partial(&buf.trim())
+            inspect_partial(buf.trim())
         }
         Subcmd::Join { data0, data1 } => {
             let d0 = std::fs::read_to_string(data0)?;
@@ -622,7 +622,7 @@ async fn main() -> Result<()> {
             let mut buf = String::new();
             stdin().read_to_string(&mut buf)?;
 
-            let tx = sign_tx(args.endpoint, &buf.trim()).await?;
+            let tx = sign_tx(args.endpoint, buf.trim()).await?;
 
             println!("{}", bs58::encode(&serialize(&tx)).into_string());
             eprintln!("Successfully signed transaction");

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

@@ -165,11 +165,12 @@ fn is_delete_patch(patch: &Patch) -> bool {
         }
     }
 
-    return false
+    false
 }
 
 struct Darkwiki {
     settings: DarkWikiSettings,
+    #[allow(clippy::type_complexity)]
     rpc: (
         async_channel::Sender<Vec<Vec<(String, String)>>>,
         async_channel::Receiver<(String, bool, Vec<String>)>,

+ 2 - 2
bin/dnetview/src/main.rs

@@ -136,8 +136,8 @@ async fn main() -> DnetViewResult<()> {
     let ex = Arc::new(Executor::new());
     let ex2 = ex.clone();
 
-    let mut dnetview = DnetView::new(model.clone(), view.clone());
-    let parser = DataParser::new(model.clone(), config);
+    let mut dnetview = DnetView::new(model.clone(), view);
+    let parser = DataParser::new(model, config);
 
     let nthreads = num_cpus::get();
     let (signal, shutdown) = async_channel::unbounded::<()>();

+ 1 - 1
bin/dnetview/src/parser.rs

@@ -205,7 +205,7 @@ impl DataParser {
         sessions: Vec<SessionInfo>,
         node: NodeInfo,
     ) -> DnetViewResult<()> {
-        if node.is_offline == true {
+        if node.is_offline {
             let node_obj = SelectableObject::Node(node.clone());
             self.model.selectables.lock().await.insert(node.id.clone(), node_obj.clone());
         } else {

+ 74 - 77
bin/dnetview/src/view.rs

@@ -29,15 +29,21 @@ pub struct View {
     pub ordered_list: Vec<String>,
 }
 
+impl Default for View {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
 impl<'a> View {
-    pub fn new() -> View {
+    pub fn new() -> Self {
         let msg_map = FxHashMap::default();
-        let msg_list = MsgList::new(msg_map.clone(), 0);
+        let msg_list = MsgList::new(msg_map, 0);
         let selectables = FxHashMap::default();
         let id_menu = IdMenu::new(Vec::new());
         let ordered_list = Vec::new();
 
-        View { id_menu, msg_list, selectables, ordered_list }
+        Self { id_menu, msg_list, selectables, ordered_list }
     }
 
     pub fn update(&mut self, msg_map: MsgMap, selectables: FxHashMap<String, SelectableObject>) {
@@ -64,35 +70,30 @@ impl<'a> View {
 
     fn make_ordered_list(&mut self) {
         for obj in self.selectables.values() {
-            match obj {
-                SelectableObject::Node(node) => match node.is_offline {
-                    true => {
-                        if !self.ordered_list.iter().any(|i| i == &node.id) {
-                            self.ordered_list.push(node.id.clone());
-                        }
+            if let SelectableObject::Node(node) = obj {
+                if node.is_offline {
+                    if !self.ordered_list.iter().any(|i| i == &node.id) {
+                        self.ordered_list.push(node.id.clone());
                     }
-                    false => {
-                        if !self.ordered_list.iter().any(|i| i == &node.id) {
-                            self.ordered_list.push(node.id.clone());
-                        }
-                        for session in &node.children {
-                            if !session.is_empty {
-                                if !self.ordered_list.iter().any(|i| i == &session.id) {
-                                    self.ordered_list.push(session.id.clone());
-                                }
-                                for connection in &session.children {
-                                    if !self.ordered_list.iter().any(|i| i == &connection.id) {
-                                        self.ordered_list.push(connection.id.clone());
-                                    }
+                } else {
+                    if !self.ordered_list.iter().any(|i| i == &node.id) {
+                        self.ordered_list.push(node.id.clone());
+                    }
+                    for session in &node.children {
+                        if !session.is_empty {
+                            if !self.ordered_list.iter().any(|i| i == &session.id) {
+                                self.ordered_list.push(session.id.clone());
+                            }
+                            for connection in &session.children {
+                                if !self.ordered_list.iter().any(|i| i == &connection.id) {
+                                    self.ordered_list.push(connection.id.clone());
                                 }
                             }
                         }
                     }
-                },
-                _ => {}
+                }
             }
         }
-
         //debug!(target: "dnetview", "render_ids()::ordered_list: {:?}", self.ordered_list);
     }
 
@@ -164,63 +165,59 @@ impl<'a> View {
         let mut nodes = Vec::new();
 
         for obj in self.selectables.values() {
-            match obj {
-                SelectableObject::Node(node) => match node.is_offline {
-                    true => {
-                        let style = Style::default().fg(Color::Blue).add_modifier(Modifier::ITALIC);
-                        let mut name = String::new();
-                        name.push_str(&node.name);
-                        name.push_str("(Offline)");
-                        let name_span = Span::styled(name, style);
-                        let lines = vec![Spans::from(name_span)];
-                        let names = ListItem::new(lines);
-                        nodes.push(names);
-                    }
-                    false => {
-                        let name_span = Span::raw(&node.name);
-                        let lines = vec![Spans::from(name_span)];
-                        let names = ListItem::new(lines);
-                        nodes.push(names);
-                        for session in &node.children {
-                            if !session.is_empty {
-                                let name = Span::styled(format!("    {}", session.name), style);
-                                let lines = vec![Spans::from(name)];
-                                let names = ListItem::new(lines);
-                                nodes.push(names);
-                                for connection in &session.children {
-                                    let mut info = Vec::new();
-                                    match connection.addr.as_str() {
-                                        "Null" => {
-                                            let style = Style::default()
-                                                .fg(Color::Blue)
-                                                .add_modifier(Modifier::ITALIC);
-                                            let name = Span::styled(
-                                                format!("        {} ", connection.addr),
-                                                style,
-                                            );
-                                            info.push(name);
-                                        }
-                                        addr => {
-                                            let name = Span::styled(
-                                                format!(
-                                                    "        {} ({})",
-                                                    addr, connection.remote_node_id
-                                                ),
-                                                style,
-                                            );
-                                            info.push(name);
-                                        }
+            if let SelectableObject::Node(node) = obj {
+                if node.is_offline {
+                    let style = Style::default().fg(Color::Blue).add_modifier(Modifier::ITALIC);
+                    let mut name = String::new();
+                    name.push_str(&node.name);
+                    name.push_str("(Offline)");
+                    let name_span = Span::styled(name, style);
+                    let lines = vec![Spans::from(name_span)];
+                    let names = ListItem::new(lines);
+                    nodes.push(names);
+                } else {
+                    let name_span = Span::raw(&node.name);
+                    let lines = vec![Spans::from(name_span)];
+                    let names = ListItem::new(lines);
+                    nodes.push(names);
+                    for session in &node.children {
+                        if !session.is_empty {
+                            let name = Span::styled(format!("    {}", session.name), style);
+                            let lines = vec![Spans::from(name)];
+                            let names = ListItem::new(lines);
+                            nodes.push(names);
+                            for connection in &session.children {
+                                let mut info = Vec::new();
+                                match connection.addr.as_str() {
+                                    "Null" => {
+                                        let style = Style::default()
+                                            .fg(Color::Blue)
+                                            .add_modifier(Modifier::ITALIC);
+                                        let name = Span::styled(
+                                            format!("        {} ", connection.addr),
+                                            style,
+                                        );
+                                        info.push(name);
+                                    }
+                                    addr => {
+                                        let name = Span::styled(
+                                            format!(
+                                                "        {} ({})",
+                                                addr, connection.remote_node_id
+                                            ),
+                                            style,
+                                        );
+                                        info.push(name);
                                     }
-
-                                    let lines = vec![Spans::from(info)];
-                                    let names = ListItem::new(lines);
-                                    nodes.push(names);
                                 }
+
+                                let lines = vec![Spans::from(info)];
+                                let names = ListItem::new(lines);
+                                nodes.push(names);
                             }
                         }
                     }
-                },
-                _ => {}
+                }
             }
         }
         let nodes =

+ 3 - 3
bin/tau/tau-cli/src/drawdown.rs

@@ -54,7 +54,7 @@ pub fn drawdown(date: String, tasks: Vec<TaskInfo>, assignee: Option<String>) ->
 
     let mut naivedate = to_naivedate(date.clone())?;
 
-    println!("log drawdown for {} in {}", asgn, naivedate.format("%b %Y").to_string());
+    println!("log drawdown for {} in {}", asgn, naivedate.format("%b %Y"));
 
     let fdow = if naivedate.month() == 2 && !is_leap_year(naivedate.year()) {
         ["   ", "1 ", "8 ", "15", "22", " "]
@@ -84,7 +84,7 @@ pub fn drawdown(date: String, tasks: Vec<TaskInfo>, assignee: Option<String>) ->
             let dow = naivedate.weekday().to_string();
             let wcell = Cell::from(dow);
             grid.add(wcell);
-            naivedate = naivedate + Duration::days(1);
+            naivedate += Duration::days(1);
         }
         for day in 1..=days_in_month {
             let owner_stopped_tasks = ret.get(&asgn).unwrap().to_owned();
@@ -118,7 +118,7 @@ pub fn drawdown(date: String, tasks: Vec<TaskInfo>, assignee: Option<String>) ->
 }
 
 fn is_leap_year(year: i32) -> bool {
-    return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
+    year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
 }
 
 fn helper_parse_func(date: String) -> Result<(u32, i32)> {

+ 2 - 2
bin/tau/tau-cli/src/main.rs

@@ -204,7 +204,7 @@ async fn main() -> Result<()> {
             }
 
             TauSubcommand::Export { path } => {
-                let path = path.unwrap_or(DEFAULT_PATH.into());
+                let path = path.unwrap_or_else(|| DEFAULT_PATH.into());
                 let res = tau.export_to(path.clone()).await?;
 
                 if res {
@@ -217,7 +217,7 @@ async fn main() -> Result<()> {
             }
 
             TauSubcommand::Import { path } => {
-                let path = path.unwrap_or(DEFAULT_PATH.into());
+                let path = path.unwrap_or_else(|| DEFAULT_PATH.into());
                 let res = tau.import_from(path.clone()).await?;
 
                 if res {

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

@@ -123,7 +123,7 @@ pub fn task_from_cli(values: Vec<String>) -> Result<BaseTask> {
     for val in values {
         let field: Vec<&str> = val.split(':').collect();
         if field.len() == 1 {
-            title.push_str(field[0].into());
+            title.push_str(field[0]);
             title.push(' ');
             continue
         }

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

@@ -177,7 +177,7 @@ pub fn events_as_string(events: Vec<TaskEvent>) -> (String, String) {
                 let ev_content =
                     fill(&event.content, textwrap::Options::new(width).subsequent_indent("  "));
                 // skip wrapped lines to align timestamp with the first line
-                for _ in 1..ev_content.lines().collect::<Vec<&str>>().len() {
+                for _ in 1..ev_content.lines().count() {
                     writeln!(timestamps_str, " ").unwrap();
                 }
                 writeln!(events_str, "- {} made a comment: {}", event.author, ev_content).unwrap();
@@ -187,7 +187,7 @@ pub fn events_as_string(events: Vec<TaskEvent>) -> (String, String) {
                 let ev_content =
                     fill(&event.content, textwrap::Options::new(width).subsequent_indent("  "));
                 // skip wrapped lines to align timestamp with the first line
-                for _ in 1..ev_content.lines().collect::<Vec<&str>>().len() {
+                for _ in 1..ev_content.lines().count() {
                     writeln!(timestamps_str, " ").unwrap();
                 }
                 writeln!(events_str, "- {} changed description to: {}", event.author, ev_content)

+ 6 - 7
bin/tau/taud/src/jsonrpc.rs

@@ -385,8 +385,7 @@ impl JsonRpcInterface {
             let description = fields.get("desc");
             if let Some(description) = description {
                 let description: Option<String> = serde_json::from_value(description.clone())?;
-                if description.is_some() {
-                    let desc = description.unwrap();
+                if let Some(desc) = description {
                     task.set_desc(&desc);
                     task.set_event("desc", &self.nickname, &desc);
                 }
@@ -397,9 +396,9 @@ impl JsonRpcInterface {
             let rank_opt = fields.get("rank");
             if let Some(rank) = rank_opt {
                 let rank: Option<f32> = serde_json::from_value(rank.clone())?;
-                if rank.is_some() {
-                    task.set_rank(rank);
-                    task.set_event("rank", &self.nickname, &rank.unwrap().to_string());
+                if let Some(rank) = rank {
+                    task.set_rank(Some(rank));
+                    task.set_event("rank", &self.nickname, &rank.to_string());
                 }
             }
         }
@@ -409,8 +408,8 @@ impl JsonRpcInterface {
             let due: Option<Option<Timestamp>> = serde_json::from_value(due)?;
             if let Some(d) = due {
                 task.set_due(d);
-                if d.is_some() {
-                    task.set_event("due", &self.nickname, &d.unwrap().0.to_string());
+                if let Some(d) = d {
+                    task.set_event("due", &self.nickname, &d.0.to_string());
                 }
             }
         }

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

@@ -195,7 +195,7 @@ impl TaskInfo {
 
     pub fn set_comment(&mut self, c: Comment) {
         debug!(target: "tau", "TaskInfo::set_comment()");
-        self.comments.0.push(c.clone());
+        self.comments.0.push(c);
     }
 
     pub fn set_rank(&mut self, r: Option<f32>) {

+ 1 - 1
example/dchat/src/main.rs

@@ -193,7 +193,7 @@ async fn main() -> Result<()> {
 
     let settings = settings?.clone();
 
-    let p2p = net::P2p::new(settings.net.into()).await;
+    let p2p = net::P2p::new(settings.net).await;
 
     let nthreads = num_cpus::get();
     let (signal, shutdown) = async_channel::unbounded::<()>();

+ 1 - 1
src/consensus/state.rs

@@ -975,7 +975,7 @@ impl ValidatorState {
     pub async fn receive_sync_blocks(&mut self, blocks: &[BlockInfo]) -> Result<()> {
         let mut new_blocks = vec![];
         for block in blocks {
-            match self.blockchain.has_block(&block) {
+            match self.blockchain.has_block(block) {
                 Ok(v) => {
                     if v {
                         debug!("receive_sync_blocks(): Existing block received");

+ 0 - 2
src/crypto/burn_proof.rs

@@ -128,8 +128,6 @@ impl BurnRevealedValues {
             *sig_coords.x(),
             *sig_coords.y(),
         ]
-        .try_into()
-        .unwrap()
     }
 }
 

+ 1 - 2
src/crypto/mint_proof.rs

@@ -30,6 +30,7 @@ pub struct MintRevealedValues {
 }
 
 impl MintRevealedValues {
+    #[allow(clippy::too_many_arguments)]
     pub fn compute(
         value: u64,
         token_id: DrkTokenId,
@@ -74,8 +75,6 @@ impl MintRevealedValues {
             *token_coords.x(),
             *token_coords.y(),
         ]
-        .try_into()
-        .unwrap()
     }
 }
 

+ 12 - 14
src/dht/dht.rs

@@ -104,14 +104,14 @@ impl Dht {
         key: blake3::Hash,
         value: Vec<u8>,
     ) -> Result<Option<blake3::Hash>> {
-        self.map.insert(key.clone(), value);
+        self.map.insert(key, value);
 
         if let Err(e) = self.lookup_insert(key, self.id) {
             error!("Failed to insert record to lookup map: {}", e);
             return Err(e)
         };
 
-        let request = LookupRequest::new(self.id, key.clone(), 0);
+        let request = LookupRequest::new(self.id, key, 0);
         if let Err(e) = self.p2p.broadcast(request).await {
             error!("Failed broadcasting request: {}", e);
             return Err(e)
@@ -126,13 +126,13 @@ impl Dht {
         match self.map.remove(&key) {
             Some(_) => {
                 debug!("Key removed: {}", key);
-                let request = LookupRequest::new(self.id, key.clone(), 1);
+                let request = LookupRequest::new(self.id, key, 1);
                 if let Err(e) = self.p2p.broadcast(request).await {
                     error!("Failed broadcasting request: {}", e);
                     return Err(e)
                 }
 
-                self.lookup_remove(key.clone(), self.id)
+                self.lookup_remove(key, self.id)
             }
             None => Ok(None),
         }
@@ -150,7 +150,7 @@ impl Dht {
         };
 
         lookup_set.insert(node_id);
-        self.lookup.insert(key.clone(), lookup_set);
+        self.lookup.insert(key, lookup_set);
 
         Ok(Some(key))
     }
@@ -167,7 +167,7 @@ impl Dht {
             if lookup_set.is_empty() {
                 self.lookup.remove(&key);
             } else {
-                self.lookup.insert(key.clone(), lookup_set);
+                self.lookup.insert(key, lookup_set);
             }
         }
 
@@ -207,7 +207,7 @@ impl Dht {
 
         // We create a key request, and broadcast it to the network
         // We choose last known peer as request recipient
-        let peer = peers.iter().last().unwrap().clone();
+        let peer = *peers.iter().last().unwrap();
         let request = KeyRequest::new(self.id, peer, key);
         // TODO: ask connected peers directly, not broadcast
         if let Err(e) = self.p2p.broadcast(request).await {
@@ -277,15 +277,13 @@ pub async fn waiting_for_response(dht: DhtPtr) -> Result<Option<KeyResponse>> {
     })
     .detach();
 
-    loop {
-        select! {
-            msg = p2p_recv_channel.recv().fuse() => {
+    select! {
+        msg = p2p_recv_channel.recv().fuse() => {
                 let response = msg?;
                 return Ok(Some(response))
-            },
-            _ = stop_signal.recv().fuse() => break,
-            _ = timeout_r.recv().fuse() => break,
-        }
+        },
+        _ = stop_signal.recv().fuse() => {},
+        _ = timeout_r.recv().fuse() => {},
     }
     Ok(None)
 }

+ 6 - 14
src/dht/protocol.rs

@@ -85,7 +85,7 @@ impl Protocol {
                     continue
                 }
 
-                dht.seen.insert(req_copy.id.clone(), Utc::now().timestamp());
+                dht.seen.insert(req_copy.id, Utc::now().timestamp());
             }
 
             let daemon = self.dht.read().await.id;
@@ -138,7 +138,7 @@ impl Protocol {
                     continue
                 }
 
-                dht.seen.insert(resp_copy.id.clone(), Utc::now().timestamp());
+                dht.seen.insert(resp_copy.id, Utc::now().timestamp());
             }
 
             if self.dht.read().await.id != resp_copy.to {
@@ -183,20 +183,12 @@ impl Protocol {
                     continue
                 }
 
-                dht.seen.insert(req_copy.id.clone(), Utc::now().timestamp());
+                dht.seen.insert(req_copy.id, Utc::now().timestamp());
             }
 
             let result = match req_copy.req_type {
-                0 => self
-                    .dht
-                    .write()
-                    .await
-                    .lookup_insert(req_copy.key.clone(), req_copy.daemon.clone()),
-                _ => self
-                    .dht
-                    .write()
-                    .await
-                    .lookup_remove(req_copy.key.clone(), req_copy.daemon.clone()),
+                0 => self.dht.write().await.lookup_insert(req_copy.key, req_copy.daemon),
+                _ => self.dht.write().await.lookup_remove(req_copy.key, req_copy.daemon),
             };
 
             if let Err(e) = result {
@@ -232,7 +224,7 @@ impl Protocol {
                     continue
                 }
 
-                dht.seen.insert(req.id.clone(), Utc::now().timestamp());
+                dht.seen.insert(req.id, Utc::now().timestamp());
             }
 
             // Extra validations can be added here.

+ 1 - 1
src/net/protocol/protocol_seed.rs

@@ -49,7 +49,7 @@ impl ProtocolSeed {
         let addrs = self.settings.external_addr.clone();
         debug!(target: "net", "ProtocolSeed::send_own_address() addrs={:?}", addrs);
         let addrs = message::AddrsMessage { addrs };
-        Ok(self.channel.clone().send(addrs).await?)
+        self.channel.clone().send(addrs).await
     }
 }
 

+ 1 - 1
src/tx/builder.rs

@@ -131,7 +131,7 @@ impl TransactionBuilder {
         let mut outputs = vec![];
         let mut output_blinds = vec![];
         // This value_blind calc assumes there will always be at least a single output
-        assert!(self.outputs.len() > 0);
+        assert!(!self.outputs.is_empty());
 
         for (i, output) in self.outputs.iter().enumerate() {
             let value_blind = if i == self.outputs.len() - 1 {

+ 1 - 1
src/tx/mod.rs

@@ -81,7 +81,7 @@ impl Transaction {
             error!("tx::verify(): Missing inputs");
             return Err(VerifyFailed::LackingInputs)
         }
-        if self.outputs.len() == 0 {
+        if self.outputs.is_empty() {
             error!("tx::verify(): Missing outputs");
             return Err(VerifyFailed::LackingOutputs)
         }

+ 1 - 1
src/util/async_util.rs

@@ -10,7 +10,7 @@ pub async fn sleep(seconds: u64) {
 /// Auxillary function to reduce boilerplate of sending
 /// a message to an optional channel, to notify caller.
 pub fn notify_caller(signal: Option<async_channel::Sender<()>>) {
-    if let Some(sender) = signal.clone() {
+    if let Some(sender) = signal {
         if let Err(err) = sender.try_send(()) {
             error!(target: "net", "Init signal send error: {}", err);
         }

+ 1 - 1
src/zk/circuit/burn_contract.rs

@@ -426,7 +426,7 @@ impl Circuit<pallas::Base> for BurnContract {
             let value = ScalarFixedShort::new(
                 ecc_chip.clone(),
                 layouter.namespace(|| "value"),
-                (value, one.clone()),
+                (value, one),
             )?;
             value_commit_v.mul(layouter.namespace(|| "[value] ValueCommitV"), value)?
         };

+ 1 - 1
src/zk/circuit/mint_contract.rs

@@ -276,7 +276,7 @@ impl Circuit<pallas::Base> for MintContract {
             let value = ScalarFixedShort::new(
                 ecc_chip.clone(),
                 layouter.namespace(|| "value"),
-                (value, one.clone()),
+                (value, one),
             )?;
             value_commit_v.mul(layouter.namespace(|| "[value] ValueCommitV"), value)?
         };