diff --git a/.github/workflows/cargo-test.yml b/.github/workflows/cargo-test.yml index 2eb39694dc..8c2acbc265 100644 --- a/.github/workflows/cargo-test.yml +++ b/.github/workflows/cargo-test.yml @@ -10,7 +10,7 @@ jobs: - uses: actions/checkout@v1 - uses: actions-rs/toolchain@v1 with: - toolchain: nightly-2019-05-17 + toolchain: nightly-2019-10-13 override: true - run: rustup component add clippy - run: cargo fetch --verbose @@ -23,7 +23,7 @@ jobs: - uses: actions/checkout@v1 - uses: actions-rs/toolchain@v1 with: - toolchain: nightly-2019-05-17 + toolchain: nightly-2019-10-13 override: true - run: rustup component add rustfmt - run: cargo fmt -- --check diff --git a/core/src/blockchain/extras.rs b/core/src/blockchain/extras.rs index 7ef5aea063..8f86d1919c 100644 --- a/core/src/blockchain/extras.rs +++ b/core/src/blockchain/extras.rs @@ -150,7 +150,7 @@ impl Add for TransactionAddresses { type Output = Self; fn add(self, rhs: Self) -> ::Output { - let mut s = self.clone(); + let mut s = self; s += rhs; s } @@ -168,7 +168,7 @@ impl Sub for TransactionAddresses { type Output = Self; fn sub(self, rhs: Self) -> ::Output { - let mut s = self.clone(); + let mut s = self; s -= rhs; s } diff --git a/core/src/blockchain/headerchain.rs b/core/src/blockchain/headerchain.rs index 25dffc4178..31831893c5 100644 --- a/core/src/blockchain/headerchain.rs +++ b/core/src/blockchain/headerchain.rs @@ -276,11 +276,11 @@ impl HeaderChain { }; match route.retracted.len() { 0 => BestHeaderChanged::CanonChainAppended { - best_header: new_best_header.clone(), + best_header: new_best_header, }, _ => BestHeaderChanged::BranchBecomingCanonChain { tree_route: route, - best_header: new_best_header.clone(), + best_header: new_best_header, }, } } else { diff --git a/core/src/client/importer.rs b/core/src/client/importer.rs index e2cca86c7a..d4cd457afc 100644 --- a/core/src/client/importer.rs +++ b/core/src/client/importer.rs @@ -199,7 +199,7 @@ impl Importer { let mut batch = DBTransaction::new(); block.state().journal_under(&mut batch, number).expect("DB commit failed"); - let route = chain.insert_block(&mut batch, block_data, invoices.clone(), self.engine.borrow()); + let route = chain.insert_block(&mut batch, block_data, invoices, self.engine.borrow()); // Final commit to the DB client.db().write_buffered(batch); diff --git a/core/src/consensus/bit_set.rs b/core/src/consensus/bit_set.rs index 4cf096e135..6b552fa20e 100644 --- a/core/src/consensus/bit_set.rs +++ b/core/src/consensus/bit_set.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see . -use std::cmp::PartialEq; +use std::cmp::{Ordering, PartialEq}; use std::convert::TryFrom; use std::fmt; use std::ops::Sub; @@ -126,20 +126,20 @@ impl Decodable for BitSet { rlp.decoder().decode_value(|bytes| { let expected = BITSET_SIZE; let got = bytes.len(); - if got > expected { - Err(DecoderError::RlpIsTooBig { + match got.cmp(&expected) { + Ordering::Greater => Err(DecoderError::RlpIsTooBig { expected, got, - }) - } else if got < expected { - Err(DecoderError::RlpIsTooShort { + }), + Ordering::Less => Err(DecoderError::RlpIsTooShort { expected, got, - }) - } else { - let mut bit_set = BitSet::new(); - bit_set.0.copy_from_slice(bytes); - Ok(bit_set) + }), + Ordering::Equal => { + let mut bit_set = BitSet::new(); + bit_set.0.copy_from_slice(bytes); + Ok(bit_set) + } } }) } diff --git a/core/src/consensus/stake/action_data.rs b/core/src/consensus/stake/action_data.rs index 312e2cbc31..9588f9153b 100644 --- a/core/src/consensus/stake/action_data.rs +++ b/core/src/consensus/stake/action_data.rs @@ -14,6 +14,7 @@ // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see . +use std::cmp::Ordering; use std::collections::btree_map::{BTreeMap, Entry}; use std::collections::btree_set::{self, BTreeSet}; use std::collections::{btree_map, HashMap, HashSet}; @@ -203,12 +204,16 @@ impl<'a> Delegation<'a> { } if let Entry::Occupied(mut entry) = self.delegatees.entry(delegatee) { - if *entry.get() > quantity { - *entry.get_mut() -= quantity; - return Ok(()) - } else if *entry.get() == quantity { - entry.remove(); - return Ok(()) + match entry.get().cmp(&quantity) { + Ordering::Greater => { + *entry.get_mut() -= quantity; + return Ok(()) + } + Ordering::Equal => { + entry.remove(); + return Ok(()) + } + Ordering::Less => {} } } diff --git a/core/src/consensus/tendermint/worker.rs b/core/src/consensus/tendermint/worker.rs index eed20ebe84..c881cc443e 100644 --- a/core/src/consensus/tendermint/worker.rs +++ b/core/src/consensus/tendermint/worker.rs @@ -14,6 +14,7 @@ // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see . +use std::cmp::Ordering; use std::iter::Iterator; use std::mem; use std::sync::{Arc, Weak}; @@ -690,34 +691,33 @@ impl Worker { cinfo!(ENGINE, "move_to_step: Propose."); // If there are multiple proposals, use the first proposal. if let Some(hash) = self.votes.get_block_hashes(&vote_step).first() { - if self.client().block(&BlockId::Hash(*hash)).is_some() { - self.proposal = Proposal::new_imported(*hash); - self.move_to_step(TendermintState::Prevote, is_restoring); - } else { + if self.client().block(&BlockId::Hash(*hash)).is_none() { cwarn!(ENGINE, "Proposal is received but not imported"); // Proposal is received but is not verified yet. // Wait for verification. return } - } else { - let parent_block_hash = self.prev_block_hash(); - if self.is_signer_proposer(&parent_block_hash) { - if let TwoThirdsMajority::Lock(lock_view, locked_block_hash) = self.last_two_thirds_majority { - cinfo!(ENGINE, "I am a proposer, I'll re-propose a locked block"); - match self.locked_proposal_block(lock_view, locked_block_hash) { - Ok(block) => self.repropose_block(block), - Err(error_msg) => cwarn!(ENGINE, "{}", error_msg), - } - } else { - cinfo!(ENGINE, "I am a proposer, I'll create a block"); - self.update_sealing(parent_block_hash); - self.step = TendermintState::ProposeWaitBlockGeneration { - parent_hash: parent_block_hash, - }; - } - } else { - self.request_proposal_to_any(vote_step.height, vote_step.view); + self.proposal = Proposal::new_imported(*hash); + self.move_to_step(TendermintState::Prevote, is_restoring); + return + } + let parent_block_hash = self.prev_block_hash(); + if !self.is_signer_proposer(&parent_block_hash) { + self.request_proposal_to_any(vote_step.height, vote_step.view); + return + } + if let TwoThirdsMajority::Lock(lock_view, locked_block_hash) = self.last_two_thirds_majority { + cinfo!(ENGINE, "I am a proposer, I'll re-propose a locked block"); + match self.locked_proposal_block(lock_view, locked_block_hash) { + Ok(block) => self.repropose_block(block), + Err(error_msg) => cwarn!(ENGINE, "{}", error_msg), } + } else { + cinfo!(ENGINE, "I am a proposer, I'll create a block"); + self.update_sealing(parent_block_hash); + self.step = TendermintState::ProposeWaitBlockGeneration { + parent_hash: parent_block_hash, + }; } } Step::Prevote => { @@ -1562,7 +1562,7 @@ impl Worker { on, }; - self.votes.collect(vote.clone()).expect("Must not attempt double vote on proposal");; + self.votes.collect(vote.clone()).expect("Must not attempt double vote on proposal"); cinfo!(ENGINE, "Voted {:?} as {}th proposer.", vote, signer_index); Ok(vote) } @@ -1811,7 +1811,7 @@ impl Worker { ); } - if let Err(double) = self.votes.collect(message.clone()) { + if let Err(double) = self.votes.collect(message) { cerror!(ENGINE, "Double Vote found {:?}", double); self.report_double_vote(&double); return None @@ -1869,17 +1869,15 @@ impl Worker { let current_step = current_vote_step.step; if current_step == Step::Prevote || current_step == Step::Precommit { - let peer_known_votes = if current_vote_step == peer_vote_step { - peer_known_votes - } else if current_vote_step < peer_vote_step { + let peer_known_votes = match current_vote_step.cmp(&peer_vote_step) { + Ordering::Equal => peer_known_votes, // We don't know which votes peer has. // However the peer knows more than 2/3 of votes. // So request all votes. - BitSet::all_set() - } else { + Ordering::Less => BitSet::all_set(), // If peer's state is less than my state, // the peer does not know any useful votes. - BitSet::new() + Ordering::Greater => BitSet::new(), }; let difference = &peer_known_votes - &self.votes_received; @@ -1969,45 +1967,47 @@ impl Worker { return } - if height == self.height - 1 { - let block = self.client().block(&height.into()).expect("Parent block should exist"); - let block_hash = block.hash(); - let finalized_view = self.finalized_view_of_previous_block; - - let votes = self - .votes - .get_all_votes_in_round(&VoteStep { - height, - view: finalized_view, - step: Step::Precommit, - }) - .into_iter() - .filter(|vote| vote.on.block_hash == Some(block_hash)) - .collect(); - - self.send_commit(block, votes, &result); - } else if height < self.height - 1 { - let block = self.client().block(&height.into()).expect("Parent block should exist"); - let child_block = self.client().block(&(height + 1).into()).expect("Parent block should exist"); - let child_block_header_seal = child_block.header().seal(); - let child_block_seal_view = TendermintSealView::new(&child_block_header_seal); - let parent_block_finalized_view = - child_block_seal_view.parent_block_finalized_view().expect("Verified block"); - let on = VoteOn { - step: VoteStep::new(height, parent_block_finalized_view, Step::Precommit), - block_hash: Some(block.hash()), - }; - let mut votes = Vec::new(); - for (index, signature) in child_block_seal_view.signatures().expect("The block is verified") { - let message = ConsensusMessage { - signature, - signer_index: index, - on: on.clone(), + match height.cmp(&(self.height - 1)) { + Ordering::Equal => { + let block = self.client().block(&height.into()).expect("Parent block should exist"); + let block_hash = block.hash(); + let finalized_view = self.finalized_view_of_previous_block; + + let votes = self + .votes + .get_all_votes_in_round(&VoteStep { + height, + view: finalized_view, + step: Step::Precommit, + }) + .into_iter() + .filter(|vote| vote.on.block_hash == Some(block_hash)) + .collect(); + + self.send_commit(block, votes, &result); + } + Ordering::Less => { + let block = self.client().block(&height.into()).expect("Parent block should exist"); + let child_block = self.client().block(&(height + 1).into()).expect("Parent block should exist"); + let child_block_header_seal = child_block.header().seal(); + let child_block_seal_view = TendermintSealView::new(&child_block_header_seal); + let parent_block_finalized_view = + child_block_seal_view.parent_block_finalized_view().expect("Verified block"); + let on = VoteOn { + step: VoteStep::new(height, parent_block_finalized_view, Step::Precommit), + block_hash: Some(block.hash()), }; - votes.push(message); + let mut votes = Vec::new(); + for (index, signature) in child_block_seal_view.signatures().expect("The block is verified") { + let message = ConsensusMessage { + signature, + signer_index: index, + on: on.clone(), + }; + votes.push(message); + } } - - self.send_commit(block, votes, &result); + Ordering::Greater => {} } } @@ -2049,23 +2049,27 @@ impl Worker { return None } - if commit_height < self.height { - cdebug!( - ENGINE, - "Received commit message is old. Current height is {} but commit messages is for height {}", - self.height, - commit_height, - ); - return None - } else if commit_height > self.height { - cwarn!( - ENGINE, - "Invalid commit message received: precommit on height {} but current height is {}", - commit_height, - self.height - ); - return None - } + match commit_height.cmp(&self.height) { + Ordering::Less => { + cdebug!( + ENGINE, + "Received commit message is old. Current height is {} but commit messages is for height {}", + self.height, + commit_height, + ); + return None + } + Ordering::Greater => { + cwarn!( + ENGINE, + "Invalid commit message received: precommit on height {} but current height is {}", + commit_height, + self.height + ); + return None + } + Ordering::Equal => {} + }; let prev_block_hash = self .client() diff --git a/core/src/miner/mem_pool.rs b/core/src/miner/mem_pool.rs index 65e126388a..d513085a34 100644 --- a/core/src/miner/mem_pool.rs +++ b/core/src/miner/mem_pool.rs @@ -960,7 +960,7 @@ impl MemPool { /// Returns Some(true) if the given transaction is local and None for not found. pub fn is_local_transaction(&self, tx_hash: H256) -> Option { - self.by_hash.get(&tx_hash).and_then(|found_item| Some(found_item.origin.is_local())) + self.by_hash.get(&tx_hash).map(|found_item| found_item.origin.is_local()) } /// Checks the given timelock with the current time/timestamp. @@ -1479,7 +1479,7 @@ pub mod test { inputs.push(create_mempool_input_with_pay(7u64, keypair, no_timelock)); mem_pool.add(inputs, inserted_block_number, inserted_timestamp, &fetch_account); - let mut mem_pool_recovered = MemPool::with_limits(8192, usize::max_value(), 3, db.clone()); + let mut mem_pool_recovered = MemPool::with_limits(8192, usize::max_value(), 3, db); mem_pool_recovered.recover_from_db(&test_client); assert_eq!(mem_pool_recovered.first_seqs, mem_pool.first_seqs); @@ -1549,7 +1549,7 @@ pub mod test { let test_client = TestBlockChainClient::new(); let db = Arc::new(kvdb_memorydb::create(crate::db::NUM_COLUMNS.unwrap_or(0))); - let mut mem_pool = MemPool::with_limits(8192, usize::max_value(), 3, db.clone()); + let mut mem_pool = MemPool::with_limits(8192, usize::max_value(), 3, db); let fetch_account = |p: &Public| -> AccountDetails { let address = public_to_address(p); diff --git a/keystore/src/accounts_dir/disk.rs b/keystore/src/accounts_dir/disk.rs index 17e78c9ac8..8a4ab666be 100644 --- a/keystore/src/accounts_dir/disk.rs +++ b/keystore/src/accounts_dir/disk.rs @@ -329,7 +329,7 @@ mod test { directory.insert_with_filename(account.clone(), "foo".to_string(), dedup).unwrap(); let file1 = directory.insert_with_filename(account.clone(), filename.clone(), dedup).unwrap().filename.unwrap(); let file2 = directory.insert_with_filename(account.clone(), filename.clone(), dedup).unwrap().filename.unwrap(); - let file3 = directory.insert_with_filename(account.clone(), filename.clone(), dedup).unwrap().filename.unwrap(); + let file3 = directory.insert_with_filename(account, filename.clone(), dedup).unwrap().filename.unwrap(); // then // the first file should have the original names diff --git a/keystore/src/json/crypto.rs b/keystore/src/json/crypto.rs index 9585dfcd39..4115ce2b8a 100644 --- a/keystore/src/json/crypto.rs +++ b/keystore/src/json/crypto.rs @@ -88,7 +88,7 @@ impl<'a> Deserialize<'a> for Crypto { fn deserialize(deserializer: D) -> Result where D: Deserializer<'a>, { - static FIELDS: &'static [&'static str] = &["id", "version", "crypto", "Crypto", "address"]; + static FIELDS: &[&str] = &["id", "version", "crypto", "Crypto", "address"]; deserializer.deserialize_struct("Crypto", FIELDS, CryptoVisitor) } } diff --git a/keystore/src/keystore.rs b/keystore/src/keystore.rs index bc46604b7c..a0a9c08bf5 100644 --- a/keystore/src/keystore.rs +++ b/keystore/src/keystore.rs @@ -140,7 +140,7 @@ impl SecretStore for KeyStore { fn meta(&self, account: &Address) -> Result { let account = self.store.get_safe_account(account)?; - Ok(account.meta.clone()) + Ok(account.meta) } fn set_meta(&self, account_ref: &Address, meta: String) -> Result<(), Error> { diff --git a/network/src/client.rs b/network/src/client.rs index 8d94fb15a5..54d1ea81c2 100644 --- a/network/src/client.rs +++ b/network/src/client.rs @@ -119,7 +119,7 @@ impl Client { let cloned_timer = timer.clone(); let p2p_channel = self.p2p_channel.clone(); let (channel, rx) = crossbeam::unbounded(); - let sender = channel.clone().into(); + let sender = channel.into(); let (quit_sender, quit_receiver) = crossbeam::bounded(1); let (init_sender, init_receiver) = crossbeam::bounded(1); diff --git a/network/src/p2p/listener.rs b/network/src/p2p/listener.rs index 8184f4d771..7014464997 100644 --- a/network/src/p2p/listener.rs +++ b/network/src/p2p/listener.rs @@ -38,7 +38,7 @@ impl Listener { Ok(match self.listener.accept() { Ok((stream, socket_address)) => Some((From::from(stream), From::from(socket_address))), Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => None, - Err(e) => Err(e)?, + Err(e) => return Err(e), }) } } diff --git a/network/src/stream.rs b/network/src/stream.rs index d07c107bf3..d2f9ae5fc4 100644 --- a/network/src/stream.rs +++ b/network/src/stream.rs @@ -283,7 +283,7 @@ impl Stream { Ok(stream) => Some(Self::from(stream)), Err(ref e) if e.kind() == io::ErrorKind::NotConnected => None, Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => None, - Err(e) => Err(e)?, + Err(e) => return Err(e.into()), }) } diff --git a/rpc/src/v1/types/mod.rs b/rpc/src/v1/types/mod.rs index 59ab24ad1c..db0e1ceeb8 100644 --- a/rpc/src/v1/types/mod.rs +++ b/rpc/src/v1/types/mod.rs @@ -73,11 +73,13 @@ impl<'de> Deserialize<'de> for TPSTestOption { "transferSingle" => TPSTestOption::TransferSingle, "transferMultiple" => TPSTestOption::TransferMultiple, "payOrTransfer" => TPSTestOption::PayOrTransfer, - v => Err(de::Error::custom(format!( - "Invalid params: unknown variant `{}`, expected one of \ - `payOnly`, `transferSingle`, `transferMultiple`, `payOrTransfer`.", - v - )))?, + v => { + return Err(de::Error::custom(format!( + "Invalid params: unknown variant `{}`, expected one of \ + `payOnly`, `transferSingle`, `transferMultiple`, `payOrTransfer`.", + v + ))) + } }) } } diff --git a/rustfmt.toml b/rustfmt.toml index a3757b4391..f08e9b846b 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -8,7 +8,7 @@ control_brace_style = "AlwaysSameLine" # disable_all_formatting = false error_on_line_overflow = false # true # error_on_unformatted = false -fn_args_density = "Tall" +fn_args_layout = "Tall" brace_style = "PreferSameLine" # "SameLineWhere" empty_item_single_line = true enum_discrim_align_threshold = 0 diff --git a/state/src/impls/shard_level.rs b/state/src/impls/shard_level.rs index 07a9333445..06703628bd 100644 --- a/state/src/impls/shard_level.rs +++ b/state/src/impls/shard_level.rs @@ -821,11 +821,8 @@ mod tests { let parameters = vec![]; let amount = 100; let approver = Address::random(); - let transaction = asset_mint!( - asset_mint_output!(lock_script_hash, parameters.clone(), amount), - metadata.clone(), - approver: approver - ); + let transaction = + asset_mint!(asset_mint_output!(lock_script_hash, parameters, amount), metadata.clone(), approver: approver); let transaction_tracker = transaction.tracker(); let asset_type = Blake::blake(transaction_tracker); @@ -849,7 +846,7 @@ mod tests { let parameters = vec![]; let approver = Address::random(); let transaction = asset_mint!( - asset_mint_output!(lock_script_hash, parameters: parameters.clone()), + asset_mint_output!(lock_script_hash, parameters: parameters), metadata.clone(), approver: approver ); @@ -876,7 +873,7 @@ mod tests { let parameters = vec![]; let approver = Address::random(); let transaction = asset_mint!( - asset_mint_output!(lock_script_hash, parameters: parameters.clone()), + asset_mint_output!(lock_script_hash, parameters: parameters), metadata.clone(), approver: approver ); @@ -1527,7 +1524,7 @@ mod tests { assert_eq!(Ok(()), state.apply(&successful_transfer, &sender, &[sender], &[], &get_test_client(), 0, 0)); check_shard_level_state!(state, [ - (scheme: (asset_type) => { metadata: metadata.clone(), supply: amount }), + (scheme: (asset_type) => { metadata: metadata, supply: amount }), (asset: (mint_tracker, 0)), (asset: (failed_transfer_tracker, 0)), (asset: (successful_transfer_tracker, 0) => { asset_type: asset_type, quantity: 10 }), @@ -1548,7 +1545,7 @@ mod tests { let parameters = vec![]; let approver = Address::random(); let transaction = asset_mint!( - asset_mint_output!(lock_script_hash, parameters: parameters.clone()), + asset_mint_output!(lock_script_hash, parameters: parameters), metadata.clone(), approver: approver ); @@ -1558,7 +1555,7 @@ mod tests { assert_eq!(Ok(()), state.apply(&transaction, &sender, &[sender], &[], &get_test_client(), 0, 0)); check_shard_level_state!(state, [ - (scheme: (asset_type) => { metadata: metadata.clone(), supply: ::std::u64::MAX }), + (scheme: (asset_type) => { metadata: metadata, supply: ::std::u64::MAX }), (asset: (transaction_tracker, 0) => { asset_type: asset_type, quantity: ::std::u64::MAX }) ]); } @@ -1577,11 +1574,8 @@ mod tests { let lock_script_hash = H160::random(); let parameters = vec![]; let approver = Address::random(); - let transaction = asset_mint!( - asset_mint_output!(lock_script_hash, parameters: parameters.clone()), - metadata.clone(), - approver: approver - ); + let transaction = + asset_mint!(asset_mint_output!(lock_script_hash, parameters: parameters), metadata, approver: approver); let transaction_tracker = transaction.tracker(); let asset_type = Blake::blake(transaction_tracker); @@ -1612,7 +1606,7 @@ mod tests { let parameters = vec![]; let approver = Address::random(); let transaction = asset_mint!( - asset_mint_output!(lock_script_hash, parameters: parameters.clone()), + asset_mint_output!(lock_script_hash, parameters: parameters), metadata.clone(), approver: approver ); @@ -1628,7 +1622,7 @@ mod tests { assert_eq!(Ok(()), state.apply(&transaction, &sender, &shard_users, &approvers, &get_test_client(), 0, 0)); check_shard_level_state!(state, [ - (scheme: (asset_type) => { metadata: metadata.clone(), supply: ::std::u64::MAX }), + (scheme: (asset_type) => { metadata: metadata, supply: ::std::u64::MAX }), (asset: (transaction_tracker, 0) => { asset_type: asset_type, quantity: ::std::u64::MAX }) ]); } @@ -1648,7 +1642,7 @@ mod tests { let parameters = vec![]; let approver = Address::random(); let transaction = asset_mint!( - asset_mint_output!(lock_script_hash, parameters: parameters.clone()), + asset_mint_output!(lock_script_hash, parameters: parameters), metadata.clone(), approver: approver ); @@ -1664,7 +1658,7 @@ mod tests { assert_eq!(Ok(()), state.apply(&transaction, &sender, &shard_users, &approvers, &get_test_client(), 0, 0)); check_shard_level_state!(state, [ - (scheme: (asset_type) => { metadata: metadata.clone(), supply: ::std::u64::MAX }), + (scheme: (asset_type) => { metadata: metadata, supply: ::std::u64::MAX }), (asset: (transaction_tracker, 0) => { asset_type: asset_type, quantity: ::std::u64::MAX }) ]); } @@ -1681,7 +1675,7 @@ mod tests { let parameters = vec![]; let approver = Address::random(); let transaction = asset_mint!( - asset_mint_output!(lock_script_hash, parameters: parameters.clone()), + asset_mint_output!(lock_script_hash, parameters: parameters), metadata.clone(), approver: approver ); @@ -1692,7 +1686,7 @@ mod tests { assert_eq!(Ok(()), state.apply(&transaction, &sender, &[], &[], &get_test_client(), 0, 0)); check_shard_level_state!(state, [ - (scheme: (asset_type) => { metadata: metadata.clone(), supply: ::std::u64::MAX, approver: approver }), + (scheme: (asset_type) => { metadata: metadata, supply: ::std::u64::MAX, approver: approver }), (asset: (transaction_tracker, 0) => { asset_type: asset_type, quantity: ::std::u64::MAX }) ]); } @@ -1710,7 +1704,7 @@ mod tests { let amount = 100; let registrar = Address::random(); let mint = asset_mint!( - asset_mint_output!(lock_script_hash, parameters.clone(), amount), + asset_mint_output!(lock_script_hash, parameters, amount), metadata.clone(), registrar: registrar ); @@ -1721,7 +1715,7 @@ mod tests { assert_eq!(Ok(()), state.apply(&mint, &sender, &[sender], &[], &get_test_client(), 0, 0)); check_shard_level_state!(state, [ - (scheme: (asset_type) => { metadata: metadata.clone(), supply: amount, approver, registrar: registrar }), + (scheme: (asset_type) => { metadata: metadata, supply: amount, approver, registrar: registrar }), (asset: (mint_tracker, 0) => { asset_type: asset_type, quantity: amount }) ]); @@ -1757,7 +1751,7 @@ mod tests { let amount = 100; let registrar = Address::random(); let mint = asset_mint!( - asset_mint_output!(lock_script_hash, parameters.clone(), amount), + asset_mint_output!(lock_script_hash, parameters, amount), metadata.clone(), registrar: registrar ); @@ -1768,7 +1762,7 @@ mod tests { assert_eq!(Ok(()), state.apply(&mint, &sender, &[sender], &[], &get_test_client(), 0, 0)); check_shard_level_state!(state, [ - (scheme: (asset_type) => { metadata: metadata.clone(), supply: amount, approver, registrar: registrar }), + (scheme: (asset_type) => { metadata: metadata, supply: amount, approver, registrar: registrar }), (asset: (mint_tracker, 0) => { asset_type: asset_type, quantity: amount }) ]); diff --git a/state/src/impls/top_level.rs b/state/src/impls/top_level.rs index 55cf04cc22..954c9ec527 100644 --- a/state/src/impls/top_level.rs +++ b/state/src/impls/top_level.rs @@ -1026,7 +1026,7 @@ mod tests_state { assert_eq!(Ok(1), state.seq(&a)); let root = state.commit(); assert!(root.is_ok(), "{:?}", root); - state.clone() + state }; assert_eq!(Ok(1), state.seq(&a)); assert_eq!(Ok(()), state.inc_seq(&a)); @@ -1045,7 +1045,7 @@ mod tests_state { assert_eq!(Ok(false), state.account_exists(&a)); assert_eq!(Ok(()), state.inc_seq(&a)); assert_eq!(Ok(1), state.seq(&a)); - state.clone() + state }; assert_eq!(Ok(1), state.seq(&a)); assert_eq!(Ok(()), state.inc_seq(&a)); @@ -1808,7 +1808,7 @@ mod tests_tx { let parameters = vec![]; let amount = 30; let transaction = mint_asset!( - Box::new(asset_mint_output!(lock_script_hash, parameters.clone(), amount)), + Box::new(asset_mint_output!(lock_script_hash, parameters, amount)), metadata.clone(), approver: approver ); @@ -1844,7 +1844,7 @@ mod tests_tx { let lock_script_hash = H160::random(); let parameters = vec![]; let transaction = mint_asset!( - Box::new(asset_mint_output!(lock_script_hash, parameters: parameters.clone())), + Box::new(asset_mint_output!(lock_script_hash, parameters: parameters)), metadata.clone(), approver: approver ); @@ -1909,7 +1909,7 @@ mod tests_tx { check_top_level_state!(state, [ (account: sender => (seq: 2, balance: 120 - 20 - 30)), - (scheme: (shard_id, asset_type) => { metadata: metadata.clone(), supply: 30 }), + (scheme: (shard_id, asset_type) => { metadata: metadata, supply: 30 }), (asset: (mint_tracker, 0, shard_id)), (asset: (transfer_tracker, 0, shard_id) => { asset_type: asset_type, quantity: 10 }), (asset: (transfer_tracker, 1, shard_id) => { asset_type: asset_type, quantity: 5 }), @@ -1937,8 +1937,8 @@ mod tests_tx { let parameters = vec![]; let amount = 30; let transaction = mint_asset!( - Box::new(asset_mint_output!(lock_script_hash, parameters.clone(), amount)), - metadata.clone(), + Box::new(asset_mint_output!(lock_script_hash, parameters, amount)), + metadata, approver: approver ); let tx = transaction!(fee: 11, transaction.clone()); @@ -2226,7 +2226,7 @@ mod tests_tx { let signature = sign(Random.generate().unwrap().private(), &content_hash).unwrap(); - let tx = transaction!(seq: 0, fee: 10, store!(content.clone(), sender, signature)); + let tx = transaction!(seq: 0, fee: 10, store!(content, sender, signature)); assert_eq!( Err(RuntimeError::TextVerificationFail("Certifier and signer are different".to_string()).into()), @@ -2454,8 +2454,8 @@ mod tests_tx { let parameters = vec![]; let amount = 30; let transaction = mint_asset!( - Box::new(asset_mint_output!(lock_script_hash, parameters.clone(), amount)), - metadata.clone(), + Box::new(asset_mint_output!(lock_script_hash, parameters, amount)), + metadata, approver: approver ); let tx = transaction!(fee: 11, transaction); @@ -2662,8 +2662,7 @@ mod tests_tx { let amount = 30; let parameters = vec![]; - let mint = - mint_asset!(Box::new(asset_mint_output!(lock_script_hash, parameters.clone(), amount)), metadata.clone()); + let mint = mint_asset!(Box::new(asset_mint_output!(lock_script_hash, parameters, amount)), metadata.clone()); let mint_tracker = mint.tracker().unwrap(); let asset_type = Blake::blake(mint_tracker); @@ -2673,7 +2672,7 @@ mod tests_tx { check_top_level_state!(state, [ (account: sender => (seq: 1, balance: 100 - 20)), - (scheme: (shard_id, asset_type) => { metadata: metadata.clone(), supply: amount }), + (scheme: (shard_id, asset_type) => { metadata: metadata, supply: amount }), (asset: (mint_tracker, 0, shard_id) => { asset_type: asset_type, quantity: amount }) ]); } @@ -2697,7 +2696,7 @@ mod tests_tx { (metadata: shards: 1) ]); - let tx = transaction!(fee: 5, set_shard_users!(new_users.clone())); + let tx = transaction!(fee: 5, set_shard_users!(new_users)); assert_eq!(Ok(()), state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0)); check_top_level_state!(state, [ @@ -2727,7 +2726,7 @@ mod tests_tx { ]); let new_users = vec![Address::random(), Address::random(), sender]; - let tx = transaction!(fee: 5, set_shard_users!(new_users.clone())); + let tx = transaction!(fee: 5, set_shard_users!(new_users)); assert_eq!( Err(RuntimeError::InsufficientPermission.into()), diff --git a/state/src/item/account.rs b/state/src/item/account.rs index fbec298ad0..7a26d592e2 100644 --- a/state/src/item/account.rs +++ b/state/src/item/account.rs @@ -241,5 +241,4 @@ mod tests { a.inc_seq(); assert!(!a.is_null()); } - } diff --git a/state/src/item/asset.rs b/state/src/item/asset.rs index 70552d2805..3b7aabf824 100644 --- a/state/src/item/asset.rs +++ b/state/src/item/asset.rs @@ -256,5 +256,4 @@ mod tests { quantity: 0, }); } - } diff --git a/sync/src/block/downloader/header.rs b/sync/src/block/downloader/header.rs index d05a40074f..f1d2193ca6 100644 --- a/sync/src/block/downloader/header.rs +++ b/sync/src/block/downloader/header.rs @@ -14,6 +14,7 @@ // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see . +use std::cmp::Ordering; use std::collections::HashMap; use std::sync::Arc; use std::time::Instant; @@ -77,21 +78,21 @@ impl HeaderDownloader { } pub fn update(&mut self, total_score: U256, best_hash: H256) -> bool { - if self.total_score == total_score { - true - } else if self.total_score < total_score { - self.total_score = total_score; - self.best_hash = best_hash; - - if self.client.block_header(&BlockId::Hash(best_hash)).is_some() { - self.pivot = Pivot { - hash: best_hash, - total_score, + match self.total_score.cmp(&total_score) { + Ordering::Equal => true, + Ordering::Less => { + self.total_score = total_score; + self.best_hash = best_hash; + + if self.client.block_header(&BlockId::Hash(best_hash)).is_some() { + self.pivot = Pivot { + hash: best_hash, + total_score, + } } + true } - true - } else { - false + Ordering::Greater => false, } } diff --git a/sync/src/snapshot/snapshot.rs b/sync/src/snapshot/snapshot.rs index d0e03eed00..6180afef59 100644 --- a/sync/src/snapshot/snapshot.rs +++ b/sync/src/snapshot/snapshot.rs @@ -365,7 +365,7 @@ mod tests { let kvdb = Arc::new(kvdb_memorydb::create(1)); snapshot.read_snapshot(kvdb.clone(), &root).unwrap(); - let mut jdb = journaldb::new(kvdb.clone(), Algorithm::Archive, COL_STATE); + let mut jdb = journaldb::new(kvdb, Algorithm::Archive, COL_STATE); let t = TrieDB::try_new(jdb.as_hashdb_mut(), &root).unwrap(); let mut inserted_keys = HashSet::new(); for &(ref key, ref value) in &x { diff --git a/types/src/util/tag.rs b/types/src/util/tag.rs index 9931e549f9..4599576ea2 100644 --- a/types/src/util/tag.rs +++ b/types/src/util/tag.rs @@ -78,7 +78,7 @@ mod tests { assert_eq!(tag.sign_all_inputs, true); assert_eq!(tag.sign_all_outputs, false); assert_eq!(tag.filter_len, 8); - assert_eq!(tag.filter.clone(), vec![ + assert_eq!(tag.filter, vec![ 0b1000_0000, 0b0100_0000, 0b0010_0000, diff --git a/util/kvdb-rocksdb/src/lib.rs b/util/kvdb-rocksdb/src/lib.rs index 3ad47fe882..7b1ba8822c 100644 --- a/util/kvdb-rocksdb/src/lib.rs +++ b/util/kvdb-rocksdb/src/lib.rs @@ -790,12 +790,12 @@ impl KeyValueDB for Database { fn iter(&self, col: Option) -> KeyValueDBIterator { let unboxed = Database::iter(self, col); - Box::new(unboxed.into_iter().flat_map(|inner| inner)) + Box::new(unboxed.into_iter().flatten()) } fn iter_from_prefix<'a>(&'a self, col: Option, prefix: &'a [u8]) -> KeyValueDBIterator { let unboxed = Database::iter_from_prefix(self, col, prefix); - Box::new(unboxed.into_iter().flat_map(|inner| inner)) + Box::new(unboxed.into_iter().flatten()) } fn restore(&self, new_db: &str) -> Result<()> { @@ -833,7 +833,7 @@ mod tests { assert_eq!(&*db.get(None, &key1).unwrap().unwrap(), b"cat"); - let contents: Vec<_> = db.iter(None).into_iter().flat_map(|inner| inner).collect(); + let contents: Vec<_> = db.iter(None).into_iter().flatten().collect(); assert_eq!(contents.len(), 2); assert_eq!(&*contents[0].0, &*key1); assert_eq!(&*contents[0].1, b"cat"); diff --git a/util/memorydb/src/lib.rs b/util/memorydb/src/lib.rs index 0699fb3995..65f3a02054 100644 --- a/util/memorydb/src/lib.rs +++ b/util/memorydb/src/lib.rs @@ -44,36 +44,35 @@ use std::mem; /// extern crate memorydb; /// use hashdb::*; /// use memorydb::*; -/// fn main() { -/// let mut m = MemoryDB::new(); -/// let d = "Hello world!".as_bytes(); /// -/// let k = m.insert(d); -/// assert!(m.contains(&k)); -/// assert_eq!(m.get(&k).unwrap(), d); +/// let mut m = MemoryDB::new(); +/// let d = "Hello world!".as_bytes(); /// -/// m.insert(d); -/// assert!(m.contains(&k)); +/// let k = m.insert(d); +/// assert!(m.contains(&k)); +/// assert_eq!(m.get(&k).unwrap(), d); /// -/// m.remove(&k); -/// assert!(m.contains(&k)); +/// m.insert(d); +/// assert!(m.contains(&k)); /// -/// m.remove(&k); -/// assert!(!m.contains(&k)); +/// m.remove(&k); +/// assert!(m.contains(&k)); /// -/// m.remove(&k); -/// assert!(!m.contains(&k)); +/// m.remove(&k); +/// assert!(!m.contains(&k)); /// -/// m.insert(d); -/// assert!(!m.contains(&k)); +/// m.remove(&k); +/// assert!(!m.contains(&k)); +/// +/// m.insert(d); +/// assert!(!m.contains(&k)); -/// m.insert(d); -/// assert!(m.contains(&k)); -/// assert_eq!(m.get(&k).unwrap(), d); +/// m.insert(d); +/// assert!(m.contains(&k)); +/// assert_eq!(m.get(&k).unwrap(), d); /// -/// m.remove(&k); -/// assert!(!m.contains(&k)); -/// } +/// m.remove(&k); +/// assert!(!m.contains(&k)); /// ``` #[derive(Default, Clone, PartialEq)] pub struct MemoryDB { @@ -96,14 +95,13 @@ impl MemoryDB { /// extern crate memorydb; /// use hashdb::*; /// use memorydb::*; - /// fn main() { - /// let mut m = MemoryDB::new(); - /// let hello_bytes = "Hello world!".as_bytes(); - /// let hash = m.insert(hello_bytes); - /// assert!(m.contains(&hash)); - /// m.clear(); - /// assert!(!m.contains(&hash)); - /// } + /// + /// let mut m = MemoryDB::new(); + /// let hello_bytes = "Hello world!".as_bytes(); + /// let hash = m.insert(hello_bytes); + /// assert!(m.contains(&hash)); + /// m.clear(); + /// assert!(!m.contains(&hash)); /// ``` pub fn clear(&mut self) { self.data.clear(); diff --git a/util/merkle/src/nibbleslice.rs b/util/merkle/src/nibbleslice.rs index 244714f004..77a9705111 100644 --- a/util/merkle/src/nibbleslice.rs +++ b/util/merkle/src/nibbleslice.rs @@ -197,7 +197,7 @@ mod tests { use super::NibbleSlice; use elastic_array::ElasticArray36; - static D: &'static [u8; 3] = &[0x01u8, 0x23, 0x45]; + static D: &[u8; 3] = &[0x01u8, 0x23, 0x45]; #[test] fn basics() { diff --git a/util/merkle/src/triedb.rs b/util/merkle/src/triedb.rs index 7ef72e31bb..c65ce58c6a 100644 --- a/util/merkle/src/triedb.rs +++ b/util/merkle/src/triedb.rs @@ -38,14 +38,12 @@ use crate::{Query, Trie, TrieError}; /// use memorydb::*; /// use primitives::H256; /// -/// fn main() { -/// let mut memdb = MemoryDB::new(); -/// let mut root = H256::new(); -/// TrieDBMut::new(&mut memdb, &mut root).insert(b"foo", b"bar").unwrap(); -/// let t = TrieDB::try_new(&memdb, &root).unwrap(); -/// assert!(t.contains(b"foo").unwrap()); -/// assert_eq!(t.get(b"foo").unwrap().unwrap(), DBValue::from_slice(b"bar")); -/// } +/// let mut memdb = MemoryDB::new(); +/// let mut root = H256::new(); +/// TrieDBMut::new(&mut memdb, &mut root).insert(b"foo", b"bar").unwrap(); +/// let t = TrieDB::try_new(&memdb, &root).unwrap(); +/// assert!(t.contains(b"foo").unwrap()); +/// assert_eq!(t.get(b"foo").unwrap().unwrap(), DBValue::from_slice(b"bar")); /// ``` pub struct TrieDB<'db> { db: &'db dyn HashDB, diff --git a/util/rlp/src/common.rs b/util/rlp/src/common.rs index c01de810a6..0056aa4f5c 100644 --- a/util/rlp/src/common.rs +++ b/util/rlp/src/common.rs @@ -20,7 +20,7 @@ lazy_static! { pub static ref BLOCKS_RLP_SWAPPER: InvalidRlpSwapper<'static> = InvalidRlpSwapper::new(COMMON_RLPS, INVALID_RLPS); } -static EMPTY_RLPS: &'static [&'static [u8]] = &[ +static EMPTY_RLPS: &[&[u8]] = &[ // RLP of KECCAK_NULL_RLP &[ 160, 86, 232, 31, 23, 27, 204, 85, 166, 255, 131, 69, 230, 146, 192, 248, 110, 91, 72, 224, 27, 153, 108, 173, @@ -33,7 +33,7 @@ static EMPTY_RLPS: &'static [&'static [u8]] = &[ ], ]; -static COMMON_RLPS: &'static [&'static [u8]] = &[ +static COMMON_RLPS: &[&[u8]] = &[ // RLP of KECCAK_NULL_RLP &[ 160, 86, 232, 31, 23, 27, 204, 85, 166, 255, 131, 69, 230, 146, 192, 248, 110, 91, 72, 224, 27, 153, 108, 173, @@ -62,7 +62,7 @@ static COMMON_RLPS: &'static [&'static [u8]] = &[ ], ]; -static INVALID_RLPS: &'static [&'static [u8]] = &[ +static INVALID_RLPS: &[&[u8]] = &[ &[0x81, 0x0], &[0x81, 0x1], &[0x81, 0x2], diff --git a/util/rlp_compress/src/common.rs b/util/rlp_compress/src/common.rs index 1d230e9c88..b3f83b8cfc 100644 --- a/util/rlp_compress/src/common.rs +++ b/util/rlp_compress/src/common.rs @@ -20,7 +20,7 @@ lazy_static! { pub static ref BLOCKS_SWAPPER: Swapper<'static> = Swapper::new(COMMON_RLPS, INVALID_RLPS); } -static EMPTY_RLPS: &'static [&'static [u8]] = &[ +static EMPTY_RLPS: &[&[u8]] = &[ // RLP of KECCAK_NULL_RLP &[ 160, 86, 232, 31, 23, 27, 204, 85, 166, 255, 131, 69, 230, 146, 192, 248, 110, 91, 72, 224, 27, 153, 108, 173, @@ -33,7 +33,7 @@ static EMPTY_RLPS: &'static [&'static [u8]] = &[ ], ]; -static COMMON_RLPS: &'static [&'static [u8]] = &[ +static COMMON_RLPS: &[&[u8]] = &[ // RLP of KECCAK_NULL_RLP &[ 160, 86, 232, 31, 23, 27, 204, 85, 166, 255, 131, 69, 230, 146, 192, 248, 110, 91, 72, 224, 27, 153, 108, 173, @@ -62,7 +62,7 @@ static COMMON_RLPS: &'static [&'static [u8]] = &[ ], ]; -static INVALID_RLPS: &'static [&'static [u8]] = &[ +static INVALID_RLPS: &[&[u8]] = &[ &[0x81, 0x0], &[0x81, 0x1], &[0x81, 0x2], diff --git a/vm/tests/chk_sig.rs b/vm/tests/chk_sig.rs index dae1a07757..227dee3ab8 100644 --- a/vm/tests/chk_sig.rs +++ b/vm/tests/chk_sig.rs @@ -136,7 +136,7 @@ fn sign_all_input_all_output() { quantity: 0, }; let input0 = AssetTransferInput { - prev_out: out0.clone(), + prev_out: out0, timelock: None, lock_script: Vec::new(), unlock_script: Vec::new(), @@ -214,7 +214,7 @@ fn sign_single_input_all_output() { quantity: 0, }; let input0 = AssetTransferInput { - prev_out: out0.clone(), + prev_out: out0, timelock: None, lock_script: Vec::new(), unlock_script: Vec::new(), @@ -252,7 +252,7 @@ fn sign_single_input_all_output() { let transaction = ShardTransaction::TransferAsset { network_id: NetworkId::default(), burns: Vec::new(), - inputs: vec![input0.clone(), input1.clone()], + inputs: vec![input0.clone(), input1], outputs: vec![output0.clone(), output1.clone()], }; @@ -291,7 +291,7 @@ fn sign_all_input_partial_output() { quantity: 0, }; let input0 = AssetTransferInput { - prev_out: out0.clone(), + prev_out: out0, timelock: None, lock_script: Vec::new(), unlock_script: Vec::new(), @@ -330,7 +330,7 @@ fn sign_all_input_partial_output() { network_id: NetworkId::default(), burns: Vec::new(), inputs: vec![input0.clone(), input1.clone()], - outputs: vec![output0.clone(), output1.clone()], + outputs: vec![output0.clone(), output1], }; // Execute sciprt in input0 @@ -368,7 +368,7 @@ fn sign_single_input_partial_output() { quantity: 0, }; let input0 = AssetTransferInput { - prev_out: out0.clone(), + prev_out: out0, timelock: None, lock_script: Vec::new(), unlock_script: Vec::new(), @@ -406,8 +406,8 @@ fn sign_single_input_partial_output() { let transaction = ShardTransaction::TransferAsset { network_id: NetworkId::default(), burns: Vec::new(), - inputs: vec![input0.clone(), input1.clone()], - outputs: vec![output0.clone(), output1.clone()], + inputs: vec![input0.clone(), input1], + outputs: vec![output0.clone(), output1], }; // Execute sciprt in input0 @@ -445,7 +445,7 @@ fn distinguish_sign_single_input_with_sign_all() { quantity: 0, }; let input0 = AssetTransferInput { - prev_out: out0.clone(), + prev_out: out0, timelock: None, lock_script: Vec::new(), unlock_script: Vec::new(), @@ -501,7 +501,7 @@ fn distinguish_sign_single_output_with_sign_all() { quantity: 0, }; let input0 = AssetTransferInput { - prev_out: out0.clone(), + prev_out: out0, timelock: None, lock_script: Vec::new(), unlock_script: Vec::new(),