parazyd 3 лет назад
Родитель
Сommit
905586a638

+ 0 - 51
Cargo.lock

@@ -1112,57 +1112,6 @@ dependencies = [
  "syn",
 ]
 
-[[package]]
-name = "dao"
-version = "0.3.0"
-dependencies = [
- "async-channel",
- "async-executor",
- "async-std",
- "async-trait",
- "clap 4.0.29",
- "darkfi",
- "futures",
- "log",
- "num_cpus",
- "prettytable-rs",
- "serde_json",
- "simplelog",
- "smol",
- "url",
-]
-
-[[package]]
-name = "daod"
-version = "0.3.0"
-dependencies = [
- "async-channel",
- "async-executor",
- "async-std",
- "async-trait",
- "bs58",
- "chacha20poly1305",
- "darkfi",
- "darkfi-sdk",
- "darkfi-serial",
- "easy-parallel",
- "futures",
- "fxhash",
- "halo2_gadgets",
- "halo2_proofs",
- "incrementalmerkletree",
- "lazy_static",
- "log",
- "num_cpus",
- "pasta_curves",
- "rand",
- "serde_json",
- "simplelog",
- "smol",
- "thiserror",
- "url",
-]
-
 [[package]]
 name = "darkfi"
 version = "0.3.0"

+ 2 - 2
Cargo.toml

@@ -29,8 +29,8 @@ members = [
     "bin/ircd",
     "bin/ircd2",
     "bin/dnetview",
-    "bin/dao/daod",
-    "bin/dao/dao-cli",
+    #"bin/dao/daod",
+    #"bin/dao/dao-cli",
     "bin/tau/taud",
     "bin/tau/tau-cli",
     "bin/darkwiki/darkwikid",

+ 3 - 12
bin/darkwiki/darkwikid/src/main.rs

@@ -547,17 +547,8 @@ async fn realmain(args: Args, executor: Arc<smol::Executor<'_>>) -> Result<()> {
             let mut workspace = String::new();
             stdin().read_line(&mut workspace)?;
             // Non-exhaustive
-            let workspace = workspace
-                .replace('\n', "")
-                .replace('\t', "_")
-                .replace('\r', "_")
-                .replace(' ', "_")
-                .replace('/', "_")
-                .replace('\\', "_")
-                .replace('\'', "_")
-                .replace('&', "_")
-                .replace('~', "_")
-                .replace(':', "_");
+            let workspace =
+                workspace.replace(['\t', '\r', ' ', '/', '\\', '\'', '&', '~', ':'], "_");
 
             if workspace.is_empty() || workspace.len() < 3 {
                 eprintln!("Error: Workspace name is empty or less than 3 characters. Try again.");
@@ -574,7 +565,7 @@ async fn realmain(args: Args, executor: Arc<smol::Executor<'_>>) -> Result<()> {
     }
 
     // Signal handling for config reload and graceful termination.
-    let signals = Signals::new(&[SIGHUP, SIGTERM, SIGINT, SIGQUIT])?;
+    let signals = Signals::new([SIGHUP, SIGTERM, SIGINT, SIGQUIT])?;
     let handle = signals.handle();
     let (term_tx, term_rx) = smol::channel::bounded::<()>(1);
     let signals_task = task::spawn(handle_signals(signals, cfg_path.clone(), term_tx));

+ 1 - 1
bin/darkwiki/darkwikid/src/util.rs

@@ -136,7 +136,7 @@ pub fn decrypt_patch(patch: &EncryptedPatch, key: &Key) -> Result<Patch> {
 /// FIXME: There's checking of file extensions here. Take care that the rest of the code
 /// is robust against this attack.
 pub fn get_docs_paths(files: &mut Vec<PathBuf>, path: &Path, parent: Option<&Path>) -> Result<()> {
-    let docs = read_dir(&path)?;
+    let docs = read_dir(path)?;
     let docs = docs.filter(|d| d.is_ok()).map(|d| d.unwrap().path()).collect::<Vec<PathBuf>>();
 
     for doc in docs {

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

@@ -21,7 +21,7 @@ use darkfi::cli_desc;
 #[derive(clap::Parser)]
 #[clap(name = "dnetview", about = cli_desc!(), version)]
 pub struct Args {
-    #[clap(short, parse(from_occurrences))]
+    #[clap(short, action = clap::ArgAction::Count)]
     /// Increase verbosity (-vvv supported)
     pub verbose: u8,
 

+ 6 - 6
bin/dnetview/src/util.rs

@@ -44,13 +44,13 @@ pub fn make_session_id(node_id: &str, session: &Session) -> Result<String> {
         num += i as u64
     }
 
-    let mut id = hex::encode(&num.to_ne_bytes());
+    let mut id = hex::encode(num.to_ne_bytes());
     id.insert_str(0, "SESSION");
     Ok(id)
 }
 
 pub fn make_connect_id(id: &u64) -> Result<String> {
-    let mut id = hex::encode(&id.to_ne_bytes());
+    let mut id = hex::encode(id.to_ne_bytes());
     id.insert_str(0, "CONNECT");
     Ok(id)
 }
@@ -70,7 +70,7 @@ pub fn make_empty_id(node_id: &str, session: &Session, count: u64) -> Result<Str
                 num += i as u64
             }
             num += count;
-            let mut id = hex::encode(&num.to_ne_bytes());
+            let mut id = hex::encode(num.to_ne_bytes());
             id.insert_str(0, "EMPTYIN");
             id
         }
@@ -83,7 +83,7 @@ pub fn make_empty_id(node_id: &str, session: &Session, count: u64) -> Result<Str
                 num += i as u64
             }
             num += count;
-            let mut id = hex::encode(&num.to_ne_bytes());
+            let mut id = hex::encode(num.to_ne_bytes());
             id.insert_str(0, "EMPTYOUT");
             id
         }
@@ -96,7 +96,7 @@ pub fn make_empty_id(node_id: &str, session: &Session, count: u64) -> Result<Str
                 num += i as u64
             }
             num += count;
-            let mut id = hex::encode(&num.to_ne_bytes());
+            let mut id = hex::encode(num.to_ne_bytes());
             id.insert_str(0, "EMPTYMAN");
             id
         }
@@ -109,7 +109,7 @@ pub fn make_empty_id(node_id: &str, session: &Session, count: u64) -> Result<Str
                 num += i as u64
             }
             num += count;
-            let mut id = hex::encode(&num.to_ne_bytes());
+            let mut id = hex::encode(num.to_ne_bytes());
             id.insert_str(0, "EMPTYOFF");
             id
         }

+ 1 - 1
bin/drk/src/main.rs

@@ -330,7 +330,7 @@ async fn main() -> Result<()> {
             let drk = Drk { rpc_client };
             drk.unspend_coin(&coin).await.with_context(|| "Failed to mark coin as unspent")?;
 
-            return Ok(())
+            Ok(())
         }
 
         Subcmd::Airdrop { faucet_endpoint, amount, token, address } => {

+ 1 - 1
bin/drk/src/rpc_blockchain.rs

@@ -311,7 +311,7 @@ impl Drk {
         eprintln!("Last known slot number reported by darkfid: {}", last);
 
         // We set this up to handle an interrupt
-        let mut signals = Signals::new(&[SIGTERM, SIGINT, SIGQUIT])?;
+        let mut signals = Signals::new([SIGTERM, SIGINT, SIGQUIT])?;
         let handle = signals.handle();
         let (term_tx, _term_rx) = smol::channel::bounded::<()>(1);
 

+ 3 - 3
bin/drk/src/rpc_wallet.rs

@@ -73,7 +73,7 @@ impl Drk {
         // the future we should actually check it?
         // TODO: The RPC needs a better variant for errors so detailed inspection
         //       can be done with error codes and all that.
-        if let Err(_) = self.rpc_client.request(req).await {
+        if (self.rpc_client.request(req).await).is_err() {
             tree_needs_init = true;
         }
 
@@ -84,7 +84,7 @@ impl Drk {
             println!("Successfully initialized Merkle tree");
         }
 
-        if let Err(_) = self.wallet_last_scanned_slot().await {
+        if (self.wallet_last_scanned_slot().await).is_err() {
             let query = format!(
                 "INSERT INTO {} ({}) VALUES (?1);",
                 MONEY_INFO_TABLE, MONEY_INFO_COL_LAST_SCANNED_SLOT
@@ -197,7 +197,7 @@ impl Drk {
             let coin: Coin = deserialize(&coin_bytes)?;
 
             let is_spent: u64 = serde_json::from_value(row[1].clone())?;
-            let is_spent = if is_spent > 0 { true } else { false };
+            let is_spent = is_spent > 0;
 
             let serial_bytes: Vec<u8> = serde_json::from_value(row[2].clone())?;
             let serial: pallas::Base = deserialize(&serial_bytes)?;

+ 1 - 1
bin/fud/fu/src/main.rs

@@ -33,7 +33,7 @@ use darkfi::{
 #[clap(name = "fu", about = cli_desc!(), version)]
 #[clap(arg_required_else_help(true))]
 struct Args {
-    #[clap(short, parse(from_occurrences))]
+    #[clap(short, action = clap::ArgAction::Count)]
     /// Increase verbosity (-vvv supported)
     verbose: u8,
 

+ 3 - 3
bin/ircd/src/model.rs

@@ -424,11 +424,11 @@ impl Model {
     fn _debug(&self) {
         for (event_id, event_node) in &self.event_map {
             let depth = self.find_depth(*event_id, &self.current_root);
-            println!("{}: {:?} [depth={}]", hex::encode(&event_id), event_node.event, depth);
+            println!("{}: {:?} [depth={}]", hex::encode(event_id), event_node.event, depth);
         }
 
-        println!("root: {}", hex::encode(&self.current_root));
-        println!("head: {}", hex::encode(&self.find_head()));
+        println!("root: {}", hex::encode(self.current_root));
+        println!("head: {}", hex::encode(self.find_head()));
     }
 }
 

+ 3 - 3
bin/ircd2/src/model.rs

@@ -377,11 +377,11 @@ impl Model {
     fn _debug(&self) {
         for (event_id, event_node) in &self.event_map {
             let depth = self.find_depth(*event_id, &self.current_root);
-            println!("{}: {:?} [depth={}]", hex::encode(&event_id), event_node.event, depth);
+            println!("{}: {:?} [depth={}]", hex::encode(event_id), event_node.event, depth);
         }
 
-        println!("root: {}", hex::encode(&self.current_root));
-        println!("head: {}", hex::encode(&self.find_head()));
+        println!("root: {}", hex::encode(self.current_root));
+        println!("head: {}", hex::encode(self.find_head()));
     }
 }
 

+ 8 - 6
bin/tau/tau-cli/src/drawdown.rs

@@ -110,10 +110,11 @@ pub fn drawdown(date: String, tasks: Vec<TaskInfo>, assignee: Option<String>) ->
                 .into_iter()
                 .filter(|t| {
                     // last event is always state stop
-                    let event_date = NaiveDateTime::from_timestamp(
+                    let event_date = NaiveDateTime::from_timestamp_opt(
                         t.events.last().unwrap_or(&TaskEvent::default()).timestamp.0,
                         0,
-                    );
+                    )
+                    .unwrap();
                     event_date.day() == day
                 })
                 .collect();
@@ -144,20 +145,20 @@ fn helper_parse_func(date: String) -> Result<(u32, i32)> {
         return Err(Error::MalformedPacket)
     }
     let (month, year) = (date[..2].parse::<u32>().unwrap(), date[2..].parse::<i32>().unwrap());
-    let year = year + (Utc::today().year() / 100) * 100;
+    let year = year + (Utc::now().year() / 100) * 100;
 
     Ok((month, year))
 }
 
 pub fn to_naivedate(date: String) -> Result<NaiveDate> {
     let (month, year) = helper_parse_func(date)?;
-    Ok(NaiveDate::from_ymd(year, month, 1))
+    Ok(NaiveDate::from_ymd_opt(year, month, 1).unwrap())
 }
 
 fn get_days_from_month(date: String) -> Result<i64> {
     let (month, year) = helper_parse_func(date)?;
 
-    Ok(NaiveDate::from_ymd(
+    Ok(NaiveDate::from_ymd_opt(
         match month {
             12 => year + 1,
             _ => year,
@@ -168,7 +169,8 @@ fn get_days_from_month(date: String) -> Result<i64> {
         },
         1,
     )
-    .signed_duration_since(NaiveDate::from_ymd(year, month, 1))
+    .unwrap()
+    .signed_duration_since(NaiveDate::from_ymd_opt(year, month, 1).unwrap())
     .num_days())
 }
 

+ 5 - 4
bin/tau/tau-cli/src/filter.rs

@@ -69,10 +69,10 @@ pub fn apply_filter(tasks: &mut Vec<TaskInfo>, filter: &str) {
                     let (month, year) =
                         (value[..2].parse::<u32>().unwrap(), value[2..].parse::<i32>().unwrap());
 
-                    let year = year + (Utc::today().year() / 100) * 100;
+                    let year = year + (Utc::now().year() / 100) * 100;
                     tasks.retain(|task| {
                         let date = task.created_at;
-                        let task_date = NaiveDateTime::from_timestamp(date, 0).date();
+                        let task_date = NaiveDateTime::from_timestamp_opt(date, 0).unwrap().date();
                         task_date.month() == month && task_date.year() == year
                     })
                 } else {
@@ -147,12 +147,13 @@ pub fn apply_filter(tasks: &mut Vec<TaskInfo>, filter: &str) {
                             Local::today().naive_local()
                         } else {
                             let due_date = due_as_timestamp(value).unwrap_or(0);
-                            NaiveDateTime::from_timestamp(due_date, 0).date()
+                            NaiveDateTime::from_timestamp_opt(due_date, 0).unwrap().date()
                         };
 
                         tasks.retain(|task| {
                             let date = task.due.unwrap_or(0);
-                            let task_date = NaiveDateTime::from_timestamp(date, 0).date();
+                            let task_date =
+                                NaiveDateTime::from_timestamp_opt(date, 0).unwrap().date();
 
                             match due_op {
                                 "not" => task_date != filter_date,

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

@@ -314,7 +314,8 @@ async fn main() -> Result<()> {
             TauSubcommand::Log { month, assignee } => {
                 match month {
                     Some(date) => {
-                        let ts = to_naivedate(date.clone())?.and_hms(12, 0, 0).timestamp();
+                        let ts =
+                            to_naivedate(date.clone())?.and_hms_opt(12, 0, 0).unwrap().timestamp();
                         let tasks = tau.get_stop_tasks(Some(ts)).await?;
                         drawdown(date, tasks, assignee)?;
                     }

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

@@ -41,18 +41,18 @@ pub fn due_as_timestamp(due: &str) -> Option<i64> {
         return None
     }
 
-    let mut year = Local::today().year();
+    let mut year = Local::now().year();
 
     // Ensure the due date is in future
-    if month < Local::today().month() {
+    if month < Local::now().month() {
         year += 1;
     }
 
-    if month == Local::today().month() && day < Local::today().day() {
+    if month == Local::now().month() && day < Local::now().day() {
         year += 1;
     }
 
-    let dt = NaiveDate::from_ymd(year, month, day).and_hms(12, 0, 0);
+    let dt = NaiveDate::from_ymd_opt(year, month, day).unwrap().and_hms_opt(12, 0, 0).unwrap();
     Some(dt.timestamp())
 }
 

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

@@ -91,7 +91,9 @@ impl MonthTasks {
 
     fn get_path(date: &Timestamp, dataset_path: &Path) -> PathBuf {
         debug!(target: "tau", "MonthTasks::get_path()");
-        dataset_path.join("month").join(Utc.timestamp(date.0, 0).format("%m%y").to_string())
+        dataset_path
+            .join("month")
+            .join(Utc.timestamp_opt(date.0, 0).unwrap().format("%m%y").to_string())
     }
 
     pub fn save(&self, dataset_path: &Path) -> TaudResult<()> {

+ 4 - 4
contrib/localnet/darkfid/tmux_sessions.sh

@@ -12,18 +12,18 @@ fi
 
 tmux new-session -d
 tmux send-keys "LOG_TARGETS='!MessageSubsystem::notify' ../../../lilith ${verbose} -c lilith_config.toml" Enter
-sleep 2
+sleep 10
 tmux split-window -v
 tmux send-keys "LOG_TARGETS='!sled' ../../../darkfid ${verbose} -c darkfid0.toml" Enter
-sleep 2
+sleep 10
 tmux select-pane -t 0
 tmux split-window -h
 tmux send-keys "LOG_TARGETS='!sled' ../../../darkfid ${verbose} -c darkfid1.toml" Enter
-sleep 2
+sleep 10
 tmux select-pane -t 1
 tmux split-window -h
 tmux send-keys "LOG_TARGETS='!sled' ../../../darkfid ${verbose} -c darkfid2.toml" Enter
-sleep 2
+sleep 10
 tmux select-pane -t 3
 tmux split-window -h
 tmux send-keys "LOG_TARGETS='!sled,!net' ../../../faucetd ${verbose} -c faucetd.toml" Enter

+ 4 - 0
src/blockchain/blockstore.rs

@@ -327,4 +327,8 @@ impl BlockOrderStore {
     pub fn len(&self) -> usize {
         self.0.len()
     }
+
+    pub fn is_empty(&self) -> bool {
+        self.0.len() == 0
+    }
 }

+ 5 - 1
src/blockchain/mod.rs

@@ -184,6 +184,10 @@ impl Blockchain {
         self.order.len()
     }
 
+    pub fn is_empty(&self) -> bool {
+        self.order.len() == 0
+    }
+
     /// Retrieve the last block slot and hash.
     pub fn last(&self) -> Result<(u64, blake3::Hash)> {
         self.order.get_last()
@@ -201,7 +205,7 @@ impl Blockchain {
 
     pub fn get_proof_hash_by_slot(&self, slot: u64) -> Result<blake3::Hash> {
         let blocks = self.get_blocks_by_slot(&[slot]).unwrap();
-        if blocks.len() == 0 {
+        if blocks.is_empty() {
             return Err(Error::BlockNotFound("block not found".to_string()))
         }
         // Since we used strict get, its safe to unwrap here

+ 4 - 0
src/blockchain/slotcheckpointstore.rs

@@ -136,4 +136,8 @@ impl SlotCheckpointStore {
     pub fn len(&self) -> usize {
         self.0.len()
     }
+
+    pub fn is_empty(&self) -> bool {
+        self.0.len() == 0
+    }
 }

+ 15 - 15
src/consensus/leadcoin.rs

@@ -145,7 +145,7 @@ impl LeadCoin {
         let coin2_commitment = Self::commitment(
             pk,
             pallas::Base::from(value + constants::REWARD),
-            pallas::Base::from(coin2_seed),
+            coin2_seed,
             coin2_blind,
         );
         // Derive election seeds
@@ -163,7 +163,7 @@ impl LeadCoin {
             coin1_commitment_root,
             coin1_sk,
             coin1_sk_root,
-            coin1_sk_pos: u32::try_from(usize::from(coin1_sk_pos)).unwrap(),
+            coin1_sk_pos: u32::try_from(coin1_sk_pos).unwrap(),
             coin1_commitment_merkle_path: coin1_commitment_merkle_path.try_into().unwrap(),
             coin1_sk_merkle_path,
             coin1_blind,
@@ -181,7 +181,7 @@ impl LeadCoin {
             pallas::Base::from(PREFIX_SN),
             self.coin1_sk_root.inner(),
             self.nonce,
-            pallas::Base::from(ZERO),
+            ZERO,
         ];
         poseidon_hash(sn_msg)
     }
@@ -220,7 +220,7 @@ impl LeadCoin {
             pallas::Base::from(PREFIX_SEED),
             self.coin1_sk_root.inner(),
             self.nonce,
-            pallas::Base::from(ZERO),
+            ZERO,
         ];
         let seed = poseidon_hash(seed_msg);
         // y
@@ -250,9 +250,9 @@ impl LeadCoin {
 
     fn util_pk(sk_root: MerkleNode, tau: pallas::Base) -> pallas::Base {
         let pk_msg =
-            [pallas::Base::from(PREFIX_PK), sk_root.inner(), tau, pallas::Base::from(ZERO)];
-        let pk = poseidon_hash(pk_msg);
-        pk
+            [pallas::Base::from(PREFIX_PK), sk_root.inner(), tau, ZERO];
+        
+        poseidon_hash(pk_msg)
     }
     /// calculate coin public key: hash of root coin secret key
     /// and timestmap.
@@ -262,9 +262,9 @@ impl LeadCoin {
 
     fn util_derived_rho(sk_root: MerkleNode, nonce: pallas::Base) -> pallas::Base {
         let rho_msg =
-            [pallas::Base::from(PREFIX_EVL), sk_root.inner(), nonce, pallas::Base::from(ZERO)];
-        let rho = poseidon_hash(rho_msg);
-        rho
+            [pallas::Base::from(PREFIX_EVL), sk_root.inner(), nonce, ZERO];
+        
+        poseidon_hash(rho_msg)
     }
     /// calculate derived coin nonce: hash of root coin secret key
     /// and old nonce
@@ -289,8 +289,8 @@ impl LeadCoin {
         info!("is_leader(): y = {:?}", y);
         info!("is_leader(): T = {:?}", target);
 
-        let first_winning = y < target;
-        first_winning
+        
+        y < target
     }
 
     fn commitment(
@@ -308,7 +308,7 @@ impl LeadCoin {
     pub fn derived_commitment(&self, blind: pallas::Scalar) -> pallas::Point {
         let pk = self.pk();
         let rho = self.derived_rho();
-        Self::commitment(pk, pallas::Base::from(self.value + constants::REWARD.clone()), rho, blind)
+        Self::commitment(pk, pallas::Base::from(self.value + constants::REWARD), rho, blind)
     }
 
     /// the new coin to be minted after the current coin is spent
@@ -390,7 +390,7 @@ impl LeadCoin {
             Witness::Base(Value::known(sigma1)),
             Witness::Base(Value::known(sigma2)),
         ];
-        let circuit = ZkCircuit::new(witnesses, zkbin.clone());
+        let circuit = ZkCircuit::new(witnesses, zkbin);
         let public_inputs = self.public_inputs(sigma1, sigma2);
         (Ok(Proof::create(pk, &[circuit], &public_inputs, &mut OsRng).unwrap()), public_inputs)
     }
@@ -436,7 +436,7 @@ impl LeadCoin {
             Witness::Scalar(Value::known(transfered_coin.opening)),
             Witness::Base(Value::known(xferval)),
         ];
-        let circuit = ZkCircuit::new(witnesses, zkbin.clone());
+        let circuit = ZkCircuit::new(witnesses, zkbin);
         let proof = Proof::create(pk, &[circuit], &self.public_inputs(sigma1, sigma2), &mut OsRng)?;
         let cm3_msg_in = [
             pallas::Base::from(PREFIX_CM),

+ 1 - 1
src/consensus/rcpt.rs

@@ -70,7 +70,7 @@ impl TxRcpt {
     }
 }
 
-#[derive(Debug, Clone, PartialEq, SerialEncodable, SerialDecodable)]
+#[derive(Debug, Clone, PartialEq, Eq, SerialEncodable, SerialDecodable)]
 pub struct EncryptedTxRcpt {
     ciphertext: [u8; CIPHER_SIZE],
     ephem_public: PublicKey,

+ 7 - 7
src/consensus/state.rs

@@ -189,18 +189,18 @@ impl ConsensusState {
     ) -> Result<bool> {
         let epoch = self.current_epoch();
         if epoch <= self.epoch {
-            self.generate_slot_checkpoint(sigma1.clone(), sigma2.clone());
+            self.generate_slot_checkpoint(sigma1, sigma2);
             return Ok(false)
         }
 
         let eta = self.get_eta();
-        if self.coins.len() == 0 {
+        if self.coins.is_empty() {
             self.coins = self.create_coins(eta).await?;
             self.update_forks_checkpoints();
         }
         self.epoch = epoch;
         self.epoch_eta = eta;
-        self.generate_slot_checkpoint(sigma1.clone(), sigma2.clone());
+        self.generate_slot_checkpoint(sigma1, sigma2);
 
         Ok(true)
     }
@@ -403,7 +403,7 @@ impl ConsensusState {
         let history_begin_index = if lead_history_len > 10 { lead_history_len - 10 } else { 0 };
 
         for lf in &self.leaders_history[history_begin_index..] {
-            sum += Float10::try_from(lf.clone()).unwrap().abs();
+            sum += Float10::try_from(*lf).unwrap().abs();
         }
         sum
     }
@@ -421,7 +421,7 @@ impl ConsensusState {
         let hist_len = self.leaders_history.len();
         for i in 1..hist_len {
             if self.leaders_history[hist_len - i] == 0 {
-                count = count + constants::FLOAT10_ONE.clone();
+                count += constants::FLOAT10_ONE.clone();
             } else {
                 break
             }
@@ -449,7 +449,7 @@ impl ConsensusState {
         if self.leaders_history[hist_len - 1] == 0 &&
             self.leaders_history[hist_len - 2] == 0 &&
             self.leaders_history[hist_len - 3] == 0 &&
-            i.clone() == constants::FLOAT10_ZERO.clone()
+            i == constants::FLOAT10_ZERO.clone()
         {
             return f * constants::DEG_RATE.clone().powf(self.zero_leads_len())
         }
@@ -629,7 +629,7 @@ impl ConsensusState {
         }
         // Check if slot is finalized
         if let Ok(slot_checkpoints) = self.blockchain.get_slot_checkpoints_by_slot(&[slot]) {
-            if slot_checkpoints.len() > 0 {
+            if !slot_checkpoints.is_empty() {
                 if let Some(slot_checkpoint) = &slot_checkpoints[0] {
                     return Ok(slot_checkpoint.clone())
                 }

+ 1 - 1
src/consensus/task/proposal.rs

@@ -80,7 +80,7 @@ pub async fn proposal_task(
         match state.write().await.chain_finalization().await {
             Ok((to_broadcast_block, to_broadcast_slot_checkpoints)) => {
                 // Broadcasting in background
-                if to_broadcast_block.len() > 0 || to_broadcast_slot_checkpoints.len() > 0 {
+                if !to_broadcast_block.is_empty() || !to_broadcast_slot_checkpoints.is_empty() {
                     let _sync_p2p = sync_p2p.clone();
                     ex.spawn(async move {
                         // Broadcast finalized blocks info, if any:

+ 10 - 10
src/consensus/validator.rs

@@ -299,7 +299,7 @@ impl ValidatorState {
             coin.eta,
             LeadProof::from(proof?),
             self.consensus.get_current_offset(slot),
-            self.consensus.leaders_history.last().unwrap().clone(),
+            *self.consensus.leaders_history.last().unwrap(),
         );
 
         Ok(Some((BlockProposal::new(header, unproposed_txs, lead_info), coin)))
@@ -521,7 +521,7 @@ impl ValidatorState {
         info!("receive_proposal(): Starting state transition validation");
         if let Err(e) = self.verify_transactions(&proposal.block.txs, false).await {
             error!("receive_proposal(): Transaction verifications failed: {}", e);
-            return Err(e.into())
+            return Err(e)
         };
 
         // TODO: [PLACEHOLDER] Add rewards validation
@@ -868,7 +868,7 @@ impl ValidatorState {
                                 "Failed to instantiate WASM runtime for contract {}",
                                 call.contract_id
                             );
-                            return Err(e.into())
+                            return Err(e)
                         }
                     };
 
@@ -877,7 +877,7 @@ impl ValidatorState {
                     Ok(v) => v,
                     Err(e) => {
                         error!("Failed to execute \"metadata\" call: {}", e);
-                        return Err(e.into())
+                        return Err(e)
                     }
                 };
 
@@ -918,7 +918,7 @@ impl ValidatorState {
                             "Failed to execute \"exec\" call for contract id {}: {}",
                             call.contract_id, e
                         );
-                        return Err(e.into())
+                        return Err(e)
                     }
                 };
                 // At this point we're done with the call and move on to the next one.
@@ -937,7 +937,7 @@ impl ValidatorState {
                 Ok(()) => info!("Signatures verification for tx {} successful", tx_hash),
                 Err(e) => {
                     error!("Signature verification for tx {} failed: {}", tx_hash, e);
-                    return Err(e.into())
+                    return Err(e)
                 }
             };
 
@@ -950,7 +950,7 @@ impl ValidatorState {
                 Ok(()) => info!("ZK proof verification for tx {} successful", tx_hash),
                 Err(e) => {
                     error!("ZK proof verification for tx {} failed: {}", tx_hash, e);
-                    return Err(e.into())
+                    return Err(e)
                 }
             };
 
@@ -986,17 +986,17 @@ impl ValidatorState {
                                     "Failed to instantiate WASM runtime for contract {}",
                                     call.contract_id
                                 );
-                                return Err(e.into())
+                                return Err(e)
                             }
                         };
 
                     info!("Executing \"apply\" call");
-                    match runtime.apply(&update) {
+                    match runtime.apply(update) {
                         // TODO: FIXME: This should be done in an atomic tx/batch
                         Ok(()) => info!("State update applied successfully"),
                         Err(e) => {
                             error!("Failed to apply state update: {}", e);
-                            return Err(e.into())
+                            return Err(e)
                         }
                     };
                 }

+ 2 - 3
src/contract/money/src/client.rs

@@ -530,8 +530,7 @@ pub fn build_half_swap_tx(
         note: coin.note.clone(),
     };
 
-    let mut spent_coins = vec![];
-    spent_coins.push(coin.clone());
+    let spent_coins = vec![coin.clone()];
 
     let output = TransactionBuilderOutputInfo {
         value: value_recv,
@@ -597,7 +596,7 @@ pub fn build_half_swap_tx(
         input.note.coin_blind,
         input.secret,
         input.leaf_position,
-        input.merkle_path.clone(),
+        input.merkle_path,
         signature_secret,
     )?;
 

+ 4 - 4
src/contract/money/tests/harness.rs

@@ -115,8 +115,8 @@ impl MoneyTestHarness {
         let mint_zkbin = db_handle.get(&serialize(&ZKAS_MINT_NS))?.unwrap();
         let burn_zkbin = db_handle.get(&serialize(&ZKAS_BURN_NS))?.unwrap();
         info!("Decoding bincode");
-        let mint_zkbin = ZkBinary::decode(&mint_zkbin.clone())?;
-        let burn_zkbin = ZkBinary::decode(&burn_zkbin.clone())?;
+        let mint_zkbin = ZkBinary::decode(&mint_zkbin)?;
+        let burn_zkbin = ZkBinary::decode(&burn_zkbin)?;
         let mint_witnesses = empty_witnesses(&mint_zkbin);
         let burn_witnesses = empty_witnesses(&burn_zkbin);
         let mint_circuit = ZkCircuit::new(mint_witnesses, mint_zkbin.clone());
@@ -144,8 +144,8 @@ impl MoneyTestHarness {
             bob_state,
             money_contract_id,
             proving_keys,
-            mint_pk: mint_pk.clone(),
-            burn_pk: burn_pk.clone(),
+            mint_pk,
+            burn_pk,
             mint_zkbin,
             burn_zkbin,
             faucet_merkle_tree,

+ 2 - 2
src/contract/money/tests/tx_verification.rs

@@ -106,8 +106,8 @@ async fn init_faucet() -> Result<(
     let mint_zkbin = db_handle.get(&serialize(&ZKAS_MINT_NS))?.unwrap();
     let burn_zkbin = db_handle.get(&serialize(&ZKAS_BURN_NS))?.unwrap();
     info!("Decoding bincode");
-    let mint_zkbin = ZkBinary::decode(&mint_zkbin.clone())?;
-    let burn_zkbin = ZkBinary::decode(&burn_zkbin.clone())?;
+    let mint_zkbin = ZkBinary::decode(&mint_zkbin)?;
+    let burn_zkbin = ZkBinary::decode(&burn_zkbin)?;
     let mint_witnesses = empty_witnesses(&mint_zkbin);
     let burn_witnesses = empty_witnesses(&burn_zkbin);
     let mint_circuit = ZkCircuit::new(mint_witnesses, mint_zkbin.clone());

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

@@ -159,7 +159,7 @@ impl ProtocolVersion {
 
         // Send version acknowledgement
         let verack = message::VerackMessage {
-            app: self.settings.app_version.clone().unwrap_or_else(|| "".to_string()),
+            app: self.settings.app_version.clone().unwrap_or_default(),
         };
         self.channel.clone().send(verack).await?;
 

+ 3 - 3
src/runtime/import/db.rs

@@ -411,14 +411,14 @@ pub(crate) fn db_contains_key(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u
             match db_handle.contains_key(&key) {
                 Ok(v) => {
                     if v {
-                        return 1 // true
+                        1 // true
                     } else {
-                        return 0 // false
+                        0 // false
                     }
                 }
                 Err(e) => {
                     error!(target: "wasm_runtime::db_contains_key", "sled.tree.contains_key failed: {}", e);
-                    return DB_CONTAINS_KEY_FAILED
+                    DB_CONTAINS_KEY_FAILED
                 }
             }
         }

+ 1 - 1
src/tx/mod.rs

@@ -106,7 +106,7 @@ impl Transaction {
         for (i, (sigs, pubkeys)) in self.signatures.iter().zip(pub_table.iter()).enumerate() {
             for (pubkey, signature) in pubkeys.iter().zip(sigs) {
                 debug!("Verifying signature with public key: {}", pubkey);
-                if !pubkey.verify(&data_hash.as_bytes()[..], &signature) {
+                if !pubkey.verify(&data_hash.as_bytes()[..], signature) {
                     error!("tx::verify_sigs[{}] failed to verify", i);
                     return Err(Error::InvalidSignature)
                 }