diff --git a/Cargo.lock b/Cargo.lock index 1f7152c7ace3c9..565193d5254bff 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -337,6 +337,12 @@ version = "3.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6894a79550807490d9f19a138a6da0f8830e70c83e83402dd23f16fd6c479056" +[[package]] +name = "bytecount" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0017894339f586ccb943b01b9555de56770c11cda818e7e3d8bd93f4ed7f46e" + [[package]] name = "byteorder" version = "1.3.4" @@ -4259,6 +4265,7 @@ version = "1.2.0" dependencies = [ "assert_cmd", "bs58 0.3.1", + "bytecount", "clap", "histogram", "serde_json", diff --git a/clap-utils/src/input_parsers.rs b/clap-utils/src/input_parsers.rs index cddf0a65a909e8..05f546c1b34a72 100644 --- a/clap-utils/src/input_parsers.rs +++ b/clap-utils/src/input_parsers.rs @@ -349,16 +349,16 @@ mod tests { let matches = app() .clone() .get_matches_from(vec!["test", "--single", "50"]); - assert_eq!(lamports_of_sol(&matches, "single"), Some(50000000000)); + assert_eq!(lamports_of_sol(&matches, "single"), Some(50_000_000_000)); assert_eq!(lamports_of_sol(&matches, "multiple"), None); let matches = app() .clone() .get_matches_from(vec!["test", "--single", "1.5"]); - assert_eq!(lamports_of_sol(&matches, "single"), Some(1500000000)); + assert_eq!(lamports_of_sol(&matches, "single"), Some(1_500_000_000)); assert_eq!(lamports_of_sol(&matches, "multiple"), None); let matches = app() .clone() .get_matches_from(vec!["test", "--single", "0.03"]); - assert_eq!(lamports_of_sol(&matches, "single"), Some(30000000)); + assert_eq!(lamports_of_sol(&matches, "single"), Some(30_000_000)); } } diff --git a/cli/src/checks.rs b/cli/src/checks.rs index 8b6f5ec6529bd3..5ef4aafa61c92b 100644 --- a/cli/src/checks.rs +++ b/cli/src/checks.rs @@ -97,10 +97,8 @@ mod tests { let mut mocks = HashMap::new(); mocks.insert(RpcRequest::GetBalance, account_balance_response.clone()); let rpc_client = RpcClient::new_mock_with_mocks("".to_string(), mocks); - assert_eq!( - check_account_for_fee(&rpc_client, &pubkey, &fee_calculator, &message0).unwrap(), - () - ); + check_account_for_fee(&rpc_client, &pubkey, &fee_calculator, &message0) + .expect("unexpected result"); let mut mocks = HashMap::new(); mocks.insert(RpcRequest::GetBalance, account_balance_response.clone()); @@ -128,16 +126,13 @@ mod tests { mocks.insert(RpcRequest::GetBalance, account_balance_response); let rpc_client = RpcClient::new_mock_with_mocks("".to_string(), mocks); - assert_eq!( - check_account_for_multiple_fees( - &rpc_client, - &pubkey, - &fee_calculator, - &[&message0, &message0] - ) - .unwrap(), - () - ); + check_account_for_multiple_fees( + &rpc_client, + &pubkey, + &fee_calculator, + &[&message0, &message0], + ) + .expect("unexpected result"); } #[test] @@ -194,19 +189,14 @@ mod tests { #[test] fn test_check_unique_pubkeys() { let pubkey0 = Pubkey::new_rand(); - let pubkey_clone = pubkey0.clone(); + let pubkey_clone = pubkey0; let pubkey1 = Pubkey::new_rand(); - assert_eq!( - check_unique_pubkeys((&pubkey0, "foo".to_string()), (&pubkey1, "bar".to_string())) - .unwrap(), - () - ); - assert_eq!( - check_unique_pubkeys((&pubkey0, "foo".to_string()), (&pubkey1, "foo".to_string())) - .unwrap(), - () - ); + check_unique_pubkeys((&pubkey0, "foo".to_string()), (&pubkey1, "bar".to_string())) + .expect("unexpected result"); + check_unique_pubkeys((&pubkey0, "foo".to_string()), (&pubkey1, "foo".to_string())) + .expect("unexpected result"); + assert!(check_unique_pubkeys( (&pubkey0, "foo".to_string()), (&pubkey_clone, "bar".to_string()) diff --git a/cli/src/cli.rs b/cli/src/cli.rs index 3e67d393abe7ea..c27927a64d7d46 100644 --- a/cli/src/cli.rs +++ b/cli/src/cli.rs @@ -2703,6 +2703,7 @@ mod tests { } #[test] + #[allow(clippy::cognitive_complexity)] fn test_cli_parse_command() { let test_commands = app("test", "desc", "version"); @@ -2800,7 +2801,7 @@ mod tests { ); // Test Confirm Subcommand - let signature = Signature::new(&vec![1; 64]); + let signature = Signature::new(&[1; 64]); let signature_string = format!("{:?}", signature); let test_confirm = test_commands @@ -3235,6 +3236,7 @@ mod tests { } #[test] + #[allow(clippy::cognitive_complexity)] fn test_cli_process_command() { // Success cases let mut config = CliConfig::default(); @@ -3774,7 +3776,7 @@ mod tests { blockhash_query::Source::NonceAccount(nonce_address), blockhash ), - nonce_account: Some(nonce_address.into()), + nonce_account: Some(nonce_address), nonce_authority: 1, fee_payer: 0, }, diff --git a/cli/src/offline/blockhash_query.rs b/cli/src/offline/blockhash_query.rs index 98ffbb71f0571d..b6ee58a57da2eb 100644 --- a/cli/src/offline/blockhash_query.rs +++ b/cli/src/offline/blockhash_query.rs @@ -303,19 +303,19 @@ mod tests { ); mocks.insert( RpcRequest::GetFeeCalculatorForBlockhash, - get_fee_calculator_for_blockhash_response.clone(), + get_fee_calculator_for_blockhash_response, ); let rpc_client = RpcClient::new_mock_with_mocks("".to_string(), mocks); assert_eq!( BlockhashQuery::FeeCalculator(Source::Cluster, test_blockhash) .get_blockhash_and_fee_calculator(&rpc_client) .unwrap(), - (test_blockhash, rpc_fee_calc.clone()), + (test_blockhash, rpc_fee_calc), ); let mut mocks = HashMap::new(); mocks.insert( RpcRequest::GetRecentBlockhash, - get_recent_blockhash_response.clone(), + get_recent_blockhash_response, ); let rpc_client = RpcClient::new_mock_with_mocks("".to_string(), mocks); assert_eq!( @@ -347,7 +347,7 @@ mod tests { let rpc_nonce_account = RpcAccount::encode(nonce_account); let get_account_response = json!(Response { context: RpcResponseContext { slot: 1 }, - value: json!(Some(rpc_nonce_account.clone())), + value: json!(Some(rpc_nonce_account)), }); let mut mocks = HashMap::new(); @@ -366,7 +366,7 @@ mod tests { BlockhashQuery::FeeCalculator(Source::NonceAccount(nonce_pubkey), nonce_blockhash) .get_blockhash_and_fee_calculator(&rpc_client) .unwrap(), - (nonce_blockhash, nonce_fee_calc.clone()), + (nonce_blockhash, nonce_fee_calc), ); let mut mocks = HashMap::new(); mocks.insert(RpcRequest::GetAccountInfo, get_account_response.clone()); @@ -377,7 +377,7 @@ mod tests { .is_err() ); let mut mocks = HashMap::new(); - mocks.insert(RpcRequest::GetAccountInfo, get_account_response.clone()); + mocks.insert(RpcRequest::GetAccountInfo, get_account_response); let rpc_client = RpcClient::new_mock_with_mocks("".to_string(), mocks); assert_eq!( BlockhashQuery::None(nonce_blockhash) diff --git a/cli/src/stake.rs b/cli/src/stake.rs index aacef4873513b1..c61c9ac46aee24 100644 --- a/cli/src/stake.rs +++ b/cli/src/stake.rs @@ -1482,6 +1482,7 @@ mod tests { } #[test] + #[allow(clippy::cognitive_complexity)] fn test_parse_command() { let test_commands = app("test", "desc", "version"); let default_keypair = Keypair::new(); @@ -2861,7 +2862,7 @@ mod tests { blockhash_query::Source::NonceAccount(nonce_account), nonce_hash ), - nonce_account: Some(nonce_account.into()), + nonce_account: Some(nonce_account), nonce_authority: 1, split_stake_account: 2, seed: None, diff --git a/cli/src/validator_info.rs b/cli/src/validator_info.rs index 719294ebdc3d96..e2b0e5115a7dcc 100644 --- a/cli/src/validator_info.rs +++ b/cli/src/validator_info.rs @@ -508,9 +508,7 @@ mod tests { let mut info = Map::new(); info.insert("name".to_string(), Value::String("Alice".to_string())); let info_string = serde_json::to_string(&Value::Object(info.clone())).unwrap(); - let validator_info = ValidatorInfo { - info: info_string.clone(), - }; + let validator_info = ValidatorInfo { info: info_string }; let data = serialize(&(config, validator_info)).unwrap(); assert_eq!( @@ -547,9 +545,7 @@ mod tests { info.insert("details".to_string(), Value::String(max_long_string)); let info_string = serde_json::to_string(&Value::Object(info)).unwrap(); - let validator_info = ValidatorInfo { - info: info_string.clone(), - }; + let validator_info = ValidatorInfo { info: info_string }; assert_eq!( serialized_size(&validator_info).unwrap(), diff --git a/cli/tests/stake.rs b/cli/tests/stake.rs index 9a90980843657e..2dbed0bec85d70 100644 --- a/cli/tests/stake.rs +++ b/cli/tests/stake.rs @@ -354,7 +354,7 @@ fn test_offline_stake_delegation_and_deactivation() { config_validator.command = CliCommand::CreateStakeAccount { stake_account: 1, seed: None, - staker: Some(config_offline.signers[0].pubkey().into()), + staker: Some(config_offline.signers[0].pubkey()), withdrawer: None, lockup: Lockup::default(), amount: SpendAmount::Some(50_000), @@ -1033,7 +1033,7 @@ fn test_stake_split() { check_balance(0, &rpc_client, &split_account.pubkey()); config_offline.signers.push(&split_account); config_offline.command = CliCommand::SplitStake { - stake_account_pubkey: stake_account_pubkey, + stake_account_pubkey, stake_authority: 0, sign_only: true, blockhash_query: BlockhashQuery::None(nonce_hash), @@ -1051,7 +1051,7 @@ fn test_stake_split() { let offline_presigner = sign_only.presigner_of(&offline_pubkey).unwrap(); config.signers = vec![&offline_presigner, &split_account]; config.command = CliCommand::SplitStake { - stake_account_pubkey: stake_account_pubkey, + stake_account_pubkey, stake_authority: 0, sign_only: false, blockhash_query: BlockhashQuery::FeeCalculator( @@ -1165,7 +1165,7 @@ fn test_stake_set_lockup() { // Online set lockup let lockup = LockupArgs { - unix_timestamp: Some(1581534570), + unix_timestamp: Some(1_581_534_570), epoch: Some(200), custodian: None, }; @@ -1199,7 +1199,7 @@ fn test_stake_set_lockup() { let online_custodian_pubkey = online_custodian.pubkey(); let lockup = LockupArgs { - unix_timestamp: Some(1581534571), + unix_timestamp: Some(1_581_534_571), epoch: Some(201), custodian: Some(online_custodian_pubkey), }; @@ -1216,7 +1216,7 @@ fn test_stake_set_lockup() { process_command(&config).unwrap(); let lockup = LockupArgs { - unix_timestamp: Some(1581534572), + unix_timestamp: Some(1_581_534_572), epoch: Some(202), custodian: None, }; @@ -1247,7 +1247,7 @@ fn test_stake_set_lockup() { // Set custodian to offline pubkey let lockup = LockupArgs { - unix_timestamp: Some(1581534573), + unix_timestamp: Some(1_581_534_573), epoch: Some(203), custodian: Some(offline_pubkey), }; @@ -1287,7 +1287,7 @@ fn test_stake_set_lockup() { // Nonced offline set lockup let lockup = LockupArgs { - unix_timestamp: Some(1581534576), + unix_timestamp: Some(1_581_534_576), epoch: Some(222), custodian: None, }; @@ -1524,8 +1524,8 @@ fn test_offline_nonced_create_stake_account_and_withdraw() { config.command = CliCommand::CreateStakeAccount { stake_account: 1, seed: Some(seed.to_string()), - staker: Some(offline_pubkey.into()), - withdrawer: Some(offline_pubkey.into()), + staker: Some(offline_pubkey), + withdrawer: Some(offline_pubkey), lockup: Lockup::default(), amount: SpendAmount::Some(50_000), sign_only: false, diff --git a/client/src/rpc_client.rs b/client/src/rpc_client.rs index 83ba77b7c656c2..3834549a2675c1 100644 --- a/client/src/rpc_client.rs +++ b/client/src/rpc_client.rs @@ -1057,7 +1057,6 @@ mod tests { use jsonrpc_core::{Error, IoHandler, Params}; use jsonrpc_http_server::{AccessControlAllowOrigin, DomainsValidation, ServerBuilder}; use serde_json::Number; - use solana_logger; use solana_sdk::{ instruction::InstructionError, signature::Keypair, system_transaction, transaction::TransactionError, diff --git a/client/src/rpc_request.rs b/client/src/rpc_request.rs index ee1842f1e764c5..5e470c12585b20 100644 --- a/client/src/rpc_request.rs +++ b/client/src/rpc_request.rs @@ -151,7 +151,7 @@ mod tests { assert_eq!(request["method"], "getRecentBlockhash"); let test_request = RpcRequest::GetFeeCalculatorForBlockhash; - let request = test_request.build_request_json(1, json!([addr.clone()])); + let request = test_request.build_request_json(1, json!([addr])); assert_eq!(request["method"], "getFeeCalculatorForBlockhash"); let test_request = RpcRequest::GetFeeRateGovernor; diff --git a/core/src/accounts_hash_verifier.rs b/core/src/accounts_hash_verifier.rs index 4959b172b23017..a9b12079539d0a 100644 --- a/core/src/accounts_hash_verifier.rs +++ b/core/src/accounts_hash_verifier.rs @@ -209,7 +209,7 @@ mod tests { trusted_validators.insert(validator1.pubkey()); assert!(AccountsHashVerifier::should_halt( &cluster_info, - &Some(trusted_validators.clone()), + &Some(trusted_validators), &mut slot_to_hash, )); } diff --git a/core/src/banking_stage.rs b/core/src/banking_stage.rs index 0479539db71427..c2ccdff6cd8f29 100644 --- a/core/src/banking_stage.rs +++ b/core/src/banking_stage.rs @@ -1504,7 +1504,7 @@ mod tests { assert_eq!( BankingStage::filter_transaction_indexes( transactions.clone(), - &vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], + &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], ), (filtered_transactions.clone(), vec![1, 2, 3, 6, 8, 10]) ); @@ -1512,7 +1512,7 @@ mod tests { assert_eq!( BankingStage::filter_transaction_indexes( transactions, - &vec![1, 2, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15], + &[1, 2, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15], ), (filtered_transactions, vec![2, 4, 5, 9, 11, 13]) ); @@ -1537,7 +1537,7 @@ mod tests { ]; assert_eq!( - BankingStage::prepare_filter_for_pending_transactions(&transactions, &vec![2, 4, 5],), + BankingStage::prepare_filter_for_pending_transactions(&transactions, &[2, 4, 5],), vec![ Err(TransactionError::BlockhashNotFound), Err(TransactionError::BlockhashNotFound), @@ -1549,7 +1549,7 @@ mod tests { ); assert_eq!( - BankingStage::prepare_filter_for_pending_transactions(&transactions, &vec![0, 2, 3],), + BankingStage::prepare_filter_for_pending_transactions(&transactions, &[0, 2, 3],), vec![ Ok(()), Err(TransactionError::BlockhashNotFound), @@ -1565,7 +1565,7 @@ mod tests { fn test_bank_filter_valid_transaction_indexes() { assert_eq!( BankingStage::filter_valid_transaction_indexes( - &vec![ + &[ (Err(TransactionError::BlockhashNotFound), None), (Err(TransactionError::BlockhashNotFound), None), (Ok(()), Some(HashAgeKind::Extant)), @@ -1573,14 +1573,14 @@ mod tests { (Ok(()), Some(HashAgeKind::Extant)), (Ok(()), Some(HashAgeKind::Extant)), ], - &vec![2, 4, 5, 9, 11, 13] + &[2, 4, 5, 9, 11, 13] ), - vec![5, 11, 13] + [5, 11, 13] ); assert_eq!( BankingStage::filter_valid_transaction_indexes( - &vec![ + &[ (Ok(()), Some(HashAgeKind::Extant)), (Err(TransactionError::BlockhashNotFound), None), (Err(TransactionError::BlockhashNotFound), None), @@ -1588,9 +1588,9 @@ mod tests { (Ok(()), Some(HashAgeKind::Extant)), (Ok(()), Some(HashAgeKind::Extant)), ], - &vec![1, 6, 7, 9, 31, 43] + &[1, 6, 7, 9, 31, 43] ), - vec![1, 9, 31, 43] + [1, 9, 31, 43] ); } @@ -1613,48 +1613,23 @@ mod tests { ); assert_eq!( - BankingStage::consume_or_forward_packets( - &my_pubkey, - Some(my_pubkey1.clone()), - false, - false, - ), + BankingStage::consume_or_forward_packets(&my_pubkey, Some(my_pubkey1), false, false,), BufferedPacketsDecision::Forward ); assert_eq!( - BankingStage::consume_or_forward_packets( - &my_pubkey, - Some(my_pubkey1.clone()), - false, - true, - ), + BankingStage::consume_or_forward_packets(&my_pubkey, Some(my_pubkey1), false, true,), BufferedPacketsDecision::Hold ); assert_eq!( - BankingStage::consume_or_forward_packets( - &my_pubkey, - Some(my_pubkey1.clone()), - true, - false, - ), + BankingStage::consume_or_forward_packets(&my_pubkey, Some(my_pubkey1), true, false,), BufferedPacketsDecision::Consume ); assert_eq!( - BankingStage::consume_or_forward_packets( - &my_pubkey1, - Some(my_pubkey1.clone()), - false, - false, - ), + BankingStage::consume_or_forward_packets(&my_pubkey1, Some(my_pubkey1), false, false,), BufferedPacketsDecision::Hold ); assert_eq!( - BankingStage::consume_or_forward_packets( - &my_pubkey1, - Some(my_pubkey1.clone()), - true, - false, - ), + BankingStage::consume_or_forward_packets(&my_pubkey1, Some(my_pubkey1), true, false,), BufferedPacketsDecision::Consume ); } @@ -1950,7 +1925,7 @@ mod tests { poh_recorder.lock().unwrap().set_working_bank(working_bank); - let shreds = entries_to_test_shreds(entries.clone(), bank.slot(), 0, true, 0); + let shreds = entries_to_test_shreds(entries, bank.slot(), 0, true, 0); blockstore.insert_shreds(shreds, None, false).unwrap(); blockstore.set_roots(&[bank.slot()]).unwrap(); diff --git a/core/src/broadcast_stage.rs b/core/src/broadcast_stage.rs index 568e95f654b387..2768867a92a68a 100644 --- a/core/src/broadcast_stage.rs +++ b/core/src/broadcast_stage.rs @@ -453,6 +453,7 @@ pub mod test { path::Path, sync::atomic::AtomicBool, sync::mpsc::channel, sync::Arc, thread::sleep, }; + #[allow(clippy::implicit_hasher)] pub fn make_transmit_shreds( slot: Slot, num: u64, @@ -553,7 +554,7 @@ pub mod test { .send(vec![(updated_slot, bank0.clone())].into_iter().collect()) .unwrap(); retransmit_slots_sender - .send(vec![(updated_slot, bank0.clone())].into_iter().collect()) + .send(vec![(updated_slot, bank0)].into_iter().collect()) .unwrap(); BroadcastStage::check_retransmit_signals( &blockstore, diff --git a/core/src/broadcast_stage/broadcast_metrics.rs b/core/src/broadcast_stage/broadcast_metrics.rs index dbe5af44a434dd..f6084c5b9bb9bf 100644 --- a/core/src/broadcast_stage/broadcast_metrics.rs +++ b/core/src/broadcast_stage/broadcast_metrics.rs @@ -189,7 +189,7 @@ mod test { &Some(BroadcastShredBatchInfo { slot: 0, num_expected_batches: Some(2), - slot_start_ts: start.clone(), + slot_start_ts: start, }), ); @@ -233,7 +233,7 @@ mod test { &Some(BroadcastShredBatchInfo { slot: 0, num_expected_batches: None, - slot_start_ts: start.clone(), + slot_start_ts: start, }), ); @@ -249,7 +249,6 @@ mod test { let slot = 0; let (sender, receiver) = channel(); let thread_handles: Vec<_> = (0..num_threads) - .into_iter() .map(|i| { let slot_broadcast_stats = slot_broadcast_stats.clone(); let sender = Some(sender.clone()); @@ -257,7 +256,7 @@ mod test { let mut broadcast_batch_info = BroadcastShredBatchInfo { slot, num_expected_batches: None, - slot_start_ts: start.clone(), + slot_start_ts: start, }; if i == round % num_threads { broadcast_batch_info.num_expected_batches = Some(num_threads); diff --git a/core/src/broadcast_stage/standard_broadcast_run.rs b/core/src/broadcast_stage/standard_broadcast_run.rs index 790700a67dfbd2..c05fa31e0ca7e3 100644 --- a/core/src/broadcast_stage/standard_broadcast_run.rs +++ b/core/src/broadcast_stage/standard_broadcast_run.rs @@ -425,9 +425,7 @@ mod test { let leader_keypair = Arc::new(Keypair::new()); let leader_pubkey = leader_keypair.pubkey(); let leader_info = Node::new_localhost_with_pubkey(&leader_pubkey); - let cluster_info = Arc::new(ClusterInfo::new_with_invalid_keypair( - leader_info.info.clone(), - )); + let cluster_info = Arc::new(ClusterInfo::new_with_invalid_keypair(leader_info.info)); let socket = UdpSocket::bind("0.0.0.0:0").unwrap(); let mut genesis_config = create_genesis_config(10_000).genesis_config; genesis_config.ticks_per_slot = max_ticks_per_n_shreds(num_shreds_per_slot) + 1; @@ -543,7 +541,7 @@ mod test { let receive_results = ReceiveResults { entries: ticks1.clone(), time_elapsed: Duration::new(2, 0), - bank: bank2.clone(), + bank: bank2, last_tick_height: (ticks1.len() - 1) as u64, }; standard_broadcast_run @@ -597,7 +595,7 @@ mod test { let receive_results = ReceiveResults { entries: ticks.clone(), time_elapsed: Duration::new(3, 0), - bank: bank0.clone(), + bank: bank0, last_tick_height: ticks.len() as u64, }; diff --git a/core/src/cluster_info.rs b/core/src/cluster_info.rs index f0d1b91afc65dc..876ce5cd7a8192 100644 --- a/core/src/cluster_info.rs +++ b/core/src/cluster_info.rs @@ -2117,7 +2117,7 @@ mod tests { #[should_panic] fn test_update_contact_info() { let d = ContactInfo::new_localhost(&Pubkey::new_rand(), timestamp()); - let cluster_info = ClusterInfo::new_with_invalid_keypair(d.clone()); + let cluster_info = ClusterInfo::new_with_invalid_keypair(d); let entry_label = CrdsValueLabel::ContactInfo(cluster_info.id()); assert!(cluster_info .gossip @@ -2153,7 +2153,7 @@ mod tests { assert!(x < range.1); } - fn check_sockets(sockets: &Vec, ip: IpAddr, range: (u16, u16)) { + fn check_sockets(sockets: &[UdpSocket], ip: IpAddr, range: (u16, u16)) { assert!(sockets.len() > 1); let port = sockets[0].local_addr().unwrap().port(); for socket in sockets.iter() { @@ -2214,8 +2214,8 @@ mod tests { let peer_keypair = Keypair::new(); let contact_info = ContactInfo::new_localhost(&keypair.pubkey(), 0); let peer = ContactInfo::new_localhost(&peer_keypair.pubkey(), 0); - let cluster_info = ClusterInfo::new(contact_info.clone(), Arc::new(keypair)); - cluster_info.insert_info(peer.clone()); + let cluster_info = ClusterInfo::new(contact_info, Arc::new(keypair)); + cluster_info.insert_info(peer); cluster_info .gossip .write() @@ -2228,7 +2228,7 @@ mod tests { .unwrap() .new_push_messages(timestamp()); // there should be some pushes ready - assert_eq!(push_messages.len() > 0, true); + assert_eq!(push_messages.is_empty(), false); push_messages .values() .for_each(|v| v.par_iter().for_each(|v| assert!(v.verify()))); @@ -2525,7 +2525,7 @@ mod tests { }); i += 1; } - let split = ClusterInfo::split_gossip_messages(vec![value.clone()]); + let split = ClusterInfo::split_gossip_messages(vec![value]); assert_eq!(split.len(), 0); } @@ -2547,13 +2547,13 @@ mod tests { //sanity test to ensure filter size never exceeds MTU size check_pull_request_size(CrdsFilter::new_rand(1000, 10)); check_pull_request_size(CrdsFilter::new_rand(1000, 1000)); - check_pull_request_size(CrdsFilter::new_rand(100000, 1000)); - check_pull_request_size(CrdsFilter::new_rand(100000, MAX_BLOOM_SIZE)); + check_pull_request_size(CrdsFilter::new_rand(100_000, 1000)); + check_pull_request_size(CrdsFilter::new_rand(100_000, MAX_BLOOM_SIZE)); } fn check_pull_request_size(filter: CrdsFilter) { let value = CrdsValue::new_unsigned(CrdsData::ContactInfo(ContactInfo::default())); - let protocol = Protocol::PullRequest(filter, value.clone()); + let protocol = Protocol::PullRequest(filter, value); assert!(serialized_size(&protocol).unwrap() <= PACKET_DATA_SIZE as u64); } @@ -2590,7 +2590,7 @@ mod tests { let mut contact_info = ContactInfo::new_localhost(&id4, timestamp()); contact_info.shred_version = 1; assert_ne!(contact_info.shred_version, d.shred_version); - cluster_info.insert_info(contact_info.clone()); + cluster_info.insert_info(contact_info); stakes.insert(id4, 10); let stakes = Arc::new(stakes); @@ -2659,11 +2659,8 @@ mod tests { node_keypair, ); for i in 0..10 { - let mut peer_lowest = 0; - if i >= 5 { - // make these invalid for the upcoming repair request - peer_lowest = 10; - } + // make these invalid for the upcoming repair request + let peer_lowest = if i >= 5 { 10 } else { 0 }; let other_node_pubkey = Pubkey::new_rand(); let other_node = ContactInfo::new_localhost(&other_node_pubkey, timestamp()); cluster_info.insert_info(other_node.clone()); diff --git a/core/src/cluster_info_vote_listener.rs b/core/src/cluster_info_vote_listener.rs index 93c2dded0c7423..944306dae13e6c 100644 --- a/core/src/cluster_info_vote_listener.rs +++ b/core/src/cluster_info_vote_listener.rs @@ -534,7 +534,7 @@ mod tests { solana_logger::setup(); let node_keypair = Keypair::new(); let vote_keypair = Keypair::new(); - let slots: Vec<_> = (0..31).into_iter().collect(); + let slots: Vec<_> = (0..31).collect(); let vote_tx = vote_transaction::new_vote_transaction( slots, @@ -746,15 +746,14 @@ mod tests { .map(|keypairs| { let node_keypair = &keypairs.node_keypair; let vote_keypair = &keypairs.vote_keypair; - let vote_tx = vote_transaction::new_vote_transaction( + vote_transaction::new_vote_transaction( vec![i as u64 + 1], Hash::default(), Hash::default(), node_keypair, vote_keypair, vote_keypair, - ); - vote_tx + ) }) .collect(); votes_sender.send(validator_votes).unwrap(); @@ -983,7 +982,7 @@ mod tests { assert!(packets.is_empty()); } - fn verify_packets_len(packets: &Vec<(CrdsValueLabel, Packets)>, ref_value: usize) { + fn verify_packets_len(packets: &[(CrdsValueLabel, Packets)], ref_value: usize) { let num_packets: usize = packets.iter().map(|p| p.1.packets.len()).sum(); assert_eq!(num_packets, ref_value); } @@ -992,22 +991,20 @@ mod tests { let node_keypair = Keypair::new(); let vote_keypair = Keypair::new(); let auth_voter_keypair = Keypair::new(); - let vote_tx = vote_transaction::new_vote_transaction( + vote_transaction::new_vote_transaction( vec![0], Hash::default(), Hash::default(), &node_keypair, &vote_keypair, &auth_voter_keypair, - ); - - vote_tx + ) } #[test] fn test_verify_votes_1_pass() { let vote_tx = test_vote_tx(); - let votes = vec![vote_tx.clone()]; + let votes = vec![vote_tx]; let labels = vec![CrdsValueLabel::Vote(0, Pubkey::new_rand())]; let (vote_txs, packets) = ClusterInfoVoteListener::verify_votes(votes, labels); assert_eq!(vote_txs.len(), 1); @@ -1021,10 +1018,7 @@ mod tests { bad_vote.signatures[0] = Signature::default(); let votes = vec![vote_tx.clone(), bad_vote, vote_tx]; let label = CrdsValueLabel::Vote(0, Pubkey::new_rand()); - let labels: Vec<_> = (0..votes.len()) - .into_iter() - .map(|_| label.clone()) - .collect(); + let labels: Vec<_> = (0..votes.len()).map(|_| label.clone()).collect(); let (vote_txs, packets) = ClusterInfoVoteListener::verify_votes(votes, labels); assert_eq!(vote_txs.len(), 2); verify_packets_len(&packets, 2); diff --git a/core/src/cluster_slots.rs b/core/src/cluster_slots.rs index f37e28c31a3797..e7981886017a06 100644 --- a/core/src/cluster_slots.rs +++ b/core/src/cluster_slots.rs @@ -248,8 +248,8 @@ mod tests { let mut map = HashMap::new(); let k1 = Pubkey::new_rand(); let k2 = Pubkey::new_rand(); - map.insert(Arc::new(k1.clone()), std::u64::MAX / 2); - map.insert(Arc::new(k2.clone()), 0); + map.insert(Arc::new(k1), std::u64::MAX / 2); + map.insert(Arc::new(k2), 0); cs.cluster_slots .write() .unwrap() @@ -270,14 +270,14 @@ mod tests { let mut map = HashMap::new(); let k1 = Pubkey::new_rand(); let k2 = Pubkey::new_rand(); - map.insert(Arc::new(k2.clone()), 0); + map.insert(Arc::new(k2), 0); cs.cluster_slots .write() .unwrap() .insert(0, Arc::new(RwLock::new(map))); //make sure default weights are used as well let validator_stakes: HashMap<_, _> = vec![( - *Arc::new(k1.clone()), + *Arc::new(k1), NodeVoteAccounts { total_stake: std::u64::MAX / 2, vote_accounts: vec![Pubkey::default()], diff --git a/core/src/commitment.rs b/core/src/commitment.rs index 7de5d07376f0a5..e548547ffa03e1 100644 --- a/core/src/commitment.rs +++ b/core/src/commitment.rs @@ -415,9 +415,9 @@ mod tests { cache2.increase_confirmation_stake(2, 5); let mut block_commitment = HashMap::new(); - block_commitment.entry(0).or_insert(cache0.clone()); - block_commitment.entry(1).or_insert(cache1.clone()); - block_commitment.entry(2).or_insert(cache2.clone()); + block_commitment.entry(0).or_insert(cache0); + block_commitment.entry(1).or_insert(cache1); + block_commitment.entry(2).or_insert(cache2); let block_commitment_cache = BlockCommitmentCache::new(block_commitment, 0, 50, bank, blockstore, 0); @@ -442,9 +442,9 @@ mod tests { cache2.increase_rooted_stake(20); let mut block_commitment = HashMap::new(); - block_commitment.entry(1).or_insert(cache0.clone()); - block_commitment.entry(2).or_insert(cache1.clone()); - block_commitment.entry(3).or_insert(cache2.clone()); + block_commitment.entry(1).or_insert(cache0); + block_commitment.entry(2).or_insert(cache1); + block_commitment.entry(3).or_insert(cache2); let largest_confirmed_root = 1; let block_commitment_cache = BlockCommitmentCache::new( block_commitment, @@ -484,7 +484,7 @@ mod tests { let lamports = 5; let mut vote_state = VoteState::default(); - let root = ancestors.last().unwrap().clone(); + let root = *ancestors.last().unwrap(); vote_state.root_slot = Some(root); AggregateCommitmentService::aggregate_commitment_for_vote_account( &mut commitment, diff --git a/core/src/consensus.rs b/core/src/consensus.rs index 20018879e67834..9c19aded03d54b 100644 --- a/core/src/consensus.rs +++ b/core/src/consensus.rs @@ -639,42 +639,39 @@ pub mod test { assert!(self.bank_forks.read().unwrap().get(root).is_some()); let mut walk = TreeWalk::from(forks); - loop { - if let Some(visit) = walk.get() { - let slot = visit.node().data; - self.progress - .entry(slot) - .or_insert_with(|| ForkProgress::new(Hash::default(), None, None, 0, 0)); - if self.bank_forks.read().unwrap().get(slot).is_some() { - walk.forward(); - continue; - } - let parent = walk.get_parent().unwrap().data; - let parent_bank = self.bank_forks.read().unwrap().get(parent).unwrap().clone(); - let new_bank = Bank::new_from_parent(&parent_bank, &Pubkey::default(), slot); - for (pubkey, vote) in cluster_votes.iter() { - if vote.contains(&parent) { - let keypairs = self.validator_keypairs.get(pubkey).unwrap(); - let last_blockhash = parent_bank.last_blockhash(); - let vote_tx = vote_transaction::new_vote_transaction( - // Must vote > root to be processed - vec![parent], - parent_bank.hash(), - last_blockhash, - &keypairs.node_keypair, - &keypairs.vote_keypair, - &keypairs.vote_keypair, - ); - info!("voting {} {}", parent_bank.slot(), parent_bank.hash()); - new_bank.process_transaction(&vote_tx).unwrap(); - } - } - new_bank.freeze(); - self.bank_forks.write().unwrap().insert(new_bank); + + while let Some(visit) = walk.get() { + let slot = visit.node().data; + self.progress + .entry(slot) + .or_insert_with(|| ForkProgress::new(Hash::default(), None, None, 0, 0)); + if self.bank_forks.read().unwrap().get(slot).is_some() { walk.forward(); - } else { - break; + continue; + } + let parent = walk.get_parent().unwrap().data; + let parent_bank = self.bank_forks.read().unwrap().get(parent).unwrap().clone(); + let new_bank = Bank::new_from_parent(&parent_bank, &Pubkey::default(), slot); + for (pubkey, vote) in cluster_votes.iter() { + if vote.contains(&parent) { + let keypairs = self.validator_keypairs.get(pubkey).unwrap(); + let last_blockhash = parent_bank.last_blockhash(); + let vote_tx = vote_transaction::new_vote_transaction( + // Must vote > root to be processed + vec![parent], + parent_bank.hash(), + last_blockhash, + &keypairs.node_keypair, + &keypairs.vote_keypair, + &keypairs.vote_keypair, + ); + info!("voting {} {}", parent_bank.slot(), parent_bank.hash()); + new_bank.process_transaction(&vote_tx).unwrap(); + } } + new_bank.freeze(); + self.bank_forks.write().unwrap().insert(new_bank); + walk.forward(); } } @@ -1092,7 +1089,7 @@ pub mod test { // will only both show up in slot 48, at which point // 2/5 > SWITCH_FORK_THRESHOLD of the stake has voted // on another fork, so switching should suceed - let votes_to_simulate = (46..=48).into_iter().collect(); + let votes_to_simulate = (46..=48).collect(); let results = vote_simulator.create_and_vote_new_branch( 45, 48, @@ -1146,11 +1143,11 @@ pub mod test { let mut my_votes: Vec = vec![]; let next_unlocked_slot = 110; // Vote on the first minor fork - my_votes.extend((0..=14).into_iter()); + my_votes.extend(0..=14); // Come back to the main fork - my_votes.extend((43..=44).into_iter()); + my_votes.extend(43..=44); // Vote on the second minor fork - my_votes.extend((45..=50).into_iter()); + my_votes.extend(45..=50); // Vote to come back to main fork my_votes.push(next_unlocked_slot); cluster_votes.insert(node_pubkey, my_votes.clone()); @@ -1219,14 +1216,14 @@ pub mod test { #[test] fn test_collect_vote_lockouts_root() { - let votes: Vec = (0..MAX_LOCKOUT_HISTORY as u64).into_iter().collect(); + let votes: Vec = (0..MAX_LOCKOUT_HISTORY as u64).collect(); //two accounts voting for slots 0..MAX_LOCKOUT_HISTORY with 1 token staked let accounts = gen_stakes(&[(1, &votes), (1, &votes)]); let mut tower = Tower::new_for_tests(0, 0.67); let mut ancestors = HashMap::new(); for i in 0..(MAX_LOCKOUT_HISTORY + 1) { tower.record_vote(i as u64, Hash::default()); - ancestors.insert(i as u64, (0..i as u64).into_iter().collect()); + ancestors.insert(i as u64, (0..i as u64).collect()); } let root = Lockout { confirmation_count: MAX_LOCKOUT_HISTORY as u32, diff --git a/core/src/contact_info.rs b/core/src/contact_info.rs index a93407e4474fd3..dfe66054c7cb8b 100644 --- a/core/src/contact_info.rs +++ b/core/src/contact_info.rs @@ -228,7 +228,6 @@ mod tests { #[test] fn test_is_valid_address() { - assert!(cfg!(test)); let bad_address_port = socketaddr!("127.0.0.1:0"); assert!(!ContactInfo::is_valid_address(&bad_address_port)); let bad_address_unspecified = socketaddr!(0, 1234); diff --git a/core/src/crds.rs b/core/src/crds.rs index 61a0bfb992329d..d17c8c8fc1550c 100644 --- a/core/src/crds.rs +++ b/core/src/crds.rs @@ -246,7 +246,7 @@ mod test { let mut ci = ContactInfo::default(); ci.wallclock += 1; let val3 = CrdsValue::new_unsigned(CrdsData::ContactInfo(ci)); - assert_matches!(crds.insert(val3.clone(), 3), Ok(Some(_))); + assert_matches!(crds.insert(val3, 3), Ok(Some(_))); assert_eq!(crds.table[&val2.label()].local_timestamp, 3); assert_eq!(crds.table[&val2.label()].insert_timestamp, 3); } @@ -315,14 +315,18 @@ mod test { } #[test] + #[allow(clippy::neg_cmp_op_on_partial_ord)] fn test_equal() { let val = CrdsValue::new_unsigned(CrdsData::ContactInfo(ContactInfo::default())); let v1 = VersionedCrdsValue::new(1, val.clone()); let v2 = VersionedCrdsValue::new(1, val); assert_eq!(v1, v2); assert!(!(v1 != v2)); + assert_eq!(v1.partial_cmp(&v2), Some(cmp::Ordering::Equal)); + assert_eq!(v2.partial_cmp(&v1), Some(cmp::Ordering::Equal)); } #[test] + #[allow(clippy::neg_cmp_op_on_partial_ord)] fn test_hash_order() { let v1 = VersionedCrdsValue::new( 1, @@ -345,14 +349,19 @@ mod test { if v1 > v2 { assert!(v1 > v2); assert!(v2 < v1); + assert_eq!(v1.partial_cmp(&v2), Some(cmp::Ordering::Greater)); + assert_eq!(v2.partial_cmp(&v1), Some(cmp::Ordering::Less)); } else if v2 > v1 { assert!(v1 < v2); assert!(v2 > v1); + assert_eq!(v1.partial_cmp(&v2), Some(cmp::Ordering::Less)); + assert_eq!(v2.partial_cmp(&v1), Some(cmp::Ordering::Greater)); } else { panic!("bad PartialOrd implementation?"); } } #[test] + #[allow(clippy::neg_cmp_op_on_partial_ord)] fn test_wallclock_order() { let v1 = VersionedCrdsValue::new( 1, @@ -373,8 +382,11 @@ mod test { assert!(!(v1 < v2)); assert!(v1 != v2); assert!(!(v1 == v2)); + assert_eq!(v1.partial_cmp(&v2), Some(cmp::Ordering::Greater)); + assert_eq!(v2.partial_cmp(&v1), Some(cmp::Ordering::Less)); } #[test] + #[allow(clippy::neg_cmp_op_on_partial_ord)] fn test_label_order() { let v1 = VersionedCrdsValue::new( 1, @@ -396,5 +408,7 @@ mod test { assert!(!(v1 > v2)); assert!(!(v2 < v1)); assert!(!(v2 > v1)); + assert_eq!(v1.partial_cmp(&v2), None); + assert_eq!(v2.partial_cmp(&v1), None); } } diff --git a/core/src/crds_gossip_pull.rs b/core/src/crds_gossip_pull.rs index ad3947df873a09..165a9433d0c42f 100644 --- a/core/src/crds_gossip_pull.rs +++ b/core/src/crds_gossip_pull.rs @@ -431,25 +431,25 @@ mod test { let me = CrdsValue::new_unsigned(CrdsData::ContactInfo(ContactInfo { id: Pubkey::new_rand(), shred_version: 123, - gossip: gossip.clone(), + gossip, ..ContactInfo::default() })); let spy = CrdsValue::new_unsigned(CrdsData::ContactInfo(ContactInfo { id: Pubkey::new_rand(), shred_version: 0, - gossip: gossip.clone(), + gossip, ..ContactInfo::default() })); let node_123 = CrdsValue::new_unsigned(CrdsData::ContactInfo(ContactInfo { id: Pubkey::new_rand(), shred_version: 123, - gossip: gossip.clone(), + gossip, ..ContactInfo::default() })); let node_456 = CrdsValue::new_unsigned(CrdsData::ContactInfo(ContactInfo { id: Pubkey::new_rand(), shred_version: 456, - gossip: gossip.clone(), + gossip, ..ContactInfo::default() })); @@ -560,12 +560,12 @@ mod test { ))); let node_pubkey = entry.label().pubkey(); let node = CrdsGossipPull::default(); - node_crds.insert(entry.clone(), 0).unwrap(); + node_crds.insert(entry, 0).unwrap(); let new = CrdsValue::new_unsigned(CrdsData::ContactInfo(ContactInfo::new_localhost( &Pubkey::new_rand(), 0, ))); - node_crds.insert(new.clone(), 0).unwrap(); + node_crds.insert(new, 0).unwrap(); let req = node.new_pull_request( &node_crds, &node_pubkey, @@ -606,13 +606,13 @@ mod test { ))); let node_pubkey = entry.label().pubkey(); let mut node = CrdsGossipPull::default(); - node_crds.insert(entry.clone(), 0).unwrap(); + node_crds.insert(entry, 0).unwrap(); let new = CrdsValue::new_unsigned(CrdsData::ContactInfo(ContactInfo::new_localhost( &Pubkey::new_rand(), 0, ))); - node_crds.insert(new.clone(), 0).unwrap(); + node_crds.insert(new, 0).unwrap(); let mut dest = CrdsGossipPull::default(); let mut dest_crds = Crds::default(); @@ -698,7 +698,7 @@ mod test { let node_label = entry.label(); let node_pubkey = node_label.pubkey(); let mut node = CrdsGossipPull::default(); - node_crds.insert(entry.clone(), 0).unwrap(); + node_crds.insert(entry, 0).unwrap(); let old = CrdsValue::new_unsigned(CrdsData::ContactInfo(ContactInfo::new_localhost( &Pubkey::new_rand(), 0, @@ -731,6 +731,7 @@ mod test { assert_eq!(node.purged_values.len(), 0); } #[test] + #[allow(clippy::float_cmp)] fn test_crds_filter_mask() { let filter = CrdsFilter::new_rand(1, 128); assert_eq!(filter.mask, !0x0); @@ -738,7 +739,7 @@ mod test { //1000/9 = 111, so 7 bits are needed to mask it assert_eq!(CrdsFilter::mask_bits(1000f64, 9f64), 7u32); let filter = CrdsFilter::new_rand(1000, 10); - assert_eq!(filter.mask & 0x00ffffffff, 0x00ffffffff); + assert_eq!(filter.mask & 0x00_ffff_ffff, 0x00_ffff_ffff); } #[test] fn test_crds_filter_add_no_mask() { @@ -800,7 +801,6 @@ mod test { } fn run_test_mask(mask_bits: u32) { let masks: Vec<_> = (0..2u64.pow(mask_bits)) - .into_iter() .map(|seed| CrdsFilter::compute_mask(seed, mask_bits)) .dedup() .collect(); @@ -854,7 +854,7 @@ mod test { &mut node_crds, &peer_pubkey, &timeouts, - vec![peer_entry.clone()], + vec![peer_entry], node.msg_timeout + 1, ), 0 @@ -883,7 +883,7 @@ mod test { &mut node_crds, &peer_pubkey, &timeouts, - vec![peer_vote.clone()], + vec![peer_vote], node.msg_timeout + 1, ), 1 diff --git a/core/src/crds_gossip_push.rs b/core/src/crds_gossip_push.rs index 6b701f4c7e94da..453c9f32cab288 100644 --- a/core/src/crds_gossip_push.rs +++ b/core/src/crds_gossip_push.rs @@ -393,7 +393,7 @@ mod test { let high_staked_peer = Pubkey::new_rand(); let high_stake = CrdsGossipPush::prune_stake_threshold(100, 100) + 10; stakes.insert(high_staked_peer, high_stake); - let _ = push.process_push_message(&mut crds, &high_staked_peer, value.clone(), 0); + let _ = push.process_push_message(&mut crds, &high_staked_peer, value, 0); let pruned = push.prune_received_cache(&self_id, &origin, hash, &stakes); assert!( @@ -426,7 +426,7 @@ mod test { // push it again assert_eq!( - push.process_push_message(&mut crds, &Pubkey::default(), value.clone(), 0), + push.process_push_message(&mut crds, &Pubkey::default(), value, 0), Err(CrdsGossipError::PushMessageAlreadyReceived) ); } @@ -446,7 +446,7 @@ mod test { // push an old version ci.wallclock = 0; - let value = CrdsValue::new_unsigned(CrdsData::ContactInfo(ci.clone())); + let value = CrdsValue::new_unsigned(CrdsData::ContactInfo(ci)); assert_eq!( push.process_push_message(&mut crds, &Pubkey::default(), value, 0), Err(CrdsGossipError::PushMessageOldVersion) @@ -469,7 +469,7 @@ mod test { // push a version to far in the past ci.wallclock = 0; - let value = CrdsValue::new_unsigned(CrdsData::ContactInfo(ci.clone())); + let value = CrdsValue::new_unsigned(CrdsData::ContactInfo(ci)); assert_eq!( push.process_push_message(&mut crds, &Pubkey::default(), value, timeout + 1), Err(CrdsGossipError::PushMessageTimeout) @@ -491,7 +491,7 @@ mod test { // push an old version ci.wallclock = 1; - let value = CrdsValue::new_unsigned(CrdsData::ContactInfo(ci.clone())); + let value = CrdsValue::new_unsigned(CrdsData::ContactInfo(ci)); assert_eq!( push.process_push_message(&mut crds, &Pubkey::default(), value, 0) .unwrap() @@ -580,25 +580,25 @@ mod test { let me = CrdsValue::new_unsigned(CrdsData::ContactInfo(ContactInfo { id: Pubkey::new_rand(), shred_version: 123, - gossip: gossip.clone(), + gossip, ..ContactInfo::default() })); let spy = CrdsValue::new_unsigned(CrdsData::ContactInfo(ContactInfo { id: Pubkey::new_rand(), shred_version: 0, - gossip: gossip.clone(), + gossip, ..ContactInfo::default() })); let node_123 = CrdsValue::new_unsigned(CrdsData::ContactInfo(ContactInfo { id: Pubkey::new_rand(), shred_version: 123, - gossip: gossip.clone(), + gossip, ..ContactInfo::default() })); let node_456 = CrdsValue::new_unsigned(CrdsData::ContactInfo(ContactInfo { id: Pubkey::new_rand(), shred_version: 456, - gossip: gossip.clone(), + gossip, ..ContactInfo::default() })); @@ -683,7 +683,7 @@ mod test { ))); let mut expected = HashMap::new(); expected.insert(peer_1.pubkey(), vec![new_msg.clone()]); - expected.insert(peer_2.pubkey(), vec![new_msg.clone()]); + expected.insert(peer_2.pubkey(), vec![new_msg]); assert_eq!(push.active_set.len(), 3); assert_eq!(push.new_push_messages(&crds, 0), expected); } @@ -718,15 +718,15 @@ mod test { &Pubkey::new_rand(), 0, ))); - assert_eq!(crds.insert(peer.clone(), 0), Ok(None)); + assert_eq!(crds.insert(peer, 0), Ok(None)); push.refresh_push_active_set(&crds, &HashMap::new(), &Pubkey::default(), 0, 1, 1); let mut ci = ContactInfo::new_localhost(&Pubkey::new_rand(), 0); ci.wallclock = 1; - let new_msg = CrdsValue::new_unsigned(CrdsData::ContactInfo(ci.clone())); + let new_msg = CrdsValue::new_unsigned(CrdsData::ContactInfo(ci)); let expected = HashMap::new(); assert_eq!( - push.process_push_message(&mut crds, &Pubkey::default(), new_msg.clone(), 1), + push.process_push_message(&mut crds, &Pubkey::default(), new_msg, 1), Ok(None) ); push.purge_old_pending_push_messages(&crds, 0); @@ -739,7 +739,7 @@ mod test { let mut push = CrdsGossipPush::default(); let mut ci = ContactInfo::new_localhost(&Pubkey::new_rand(), 0); ci.wallclock = 0; - let value = CrdsValue::new_unsigned(CrdsData::ContactInfo(ci.clone())); + let value = CrdsValue::new_unsigned(CrdsData::ContactInfo(ci)); let label = value.label(); // push a new message assert_eq!( @@ -759,7 +759,7 @@ mod test { // push it again assert_eq!( - push.process_push_message(&mut crds, &Pubkey::default(), value.clone(), 0), + push.process_push_message(&mut crds, &Pubkey::default(), value, 0), Err(CrdsGossipError::PushMessageOldVersion) ); } diff --git a/core/src/crds_value.rs b/core/src/crds_value.rs index 26878d06f72ca3..f6ef6c83c221d1 100644 --- a/core/src/crds_value.rs +++ b/core/src/crds_value.rs @@ -487,21 +487,21 @@ mod test { let mut o = ls.clone(); o.root = 1; - let v = CrdsValue::new_unsigned(CrdsData::LowestSlot(0, o.clone())); + let v = CrdsValue::new_unsigned(CrdsData::LowestSlot(0, o)); assert_eq!(v.sanitize(), Err(SanitizeError::InvalidValue)); let o = ls.clone(); - let v = CrdsValue::new_unsigned(CrdsData::LowestSlot(1, o.clone())); + let v = CrdsValue::new_unsigned(CrdsData::LowestSlot(1, o)); assert_eq!(v.sanitize(), Err(SanitizeError::ValueOutOfBounds)); let mut o = ls.clone(); o.slots.insert(1); - let v = CrdsValue::new_unsigned(CrdsData::LowestSlot(0, o.clone())); + let v = CrdsValue::new_unsigned(CrdsData::LowestSlot(0, o)); assert_eq!(v.sanitize(), Err(SanitizeError::InvalidValue)); - let mut o = ls.clone(); + let mut o = ls; o.stash.push(deprecated::EpochIncompleteSlots::default()); - let v = CrdsValue::new_unsigned(CrdsData::LowestSlot(0, o.clone())); + let v = CrdsValue::new_unsigned(CrdsData::LowestSlot(0, o)); assert_eq!(v.sanitize(), Err(SanitizeError::InvalidValue)); } diff --git a/core/src/epoch_slots.rs b/core/src/epoch_slots.rs index b81e5a397ce9fc..e69622e211f075 100644 --- a/core/src/epoch_slots.rs +++ b/core/src/epoch_slots.rs @@ -400,24 +400,24 @@ mod tests { o.first_slot = MAX_SLOT; assert_eq!(o.sanitize(), Err(SanitizeError::ValueOutOfBounds)); - let mut o = compressed.clone(); + let mut o = compressed; o.num = MAX_SLOTS_PER_ENTRY; assert_eq!(o.sanitize(), Err(SanitizeError::ValueOutOfBounds)); let mut slots = EpochSlots::default(); - let range: Vec = (0..5000).into_iter().collect(); + let range: Vec = (0..5000).collect(); assert_eq!(slots.fill(&range, 1), 5000); assert_eq!(slots.wallclock, 1); assert!(slots.sanitize().is_ok()); - let mut o = slots.clone(); + let mut o = slots; o.wallclock = MAX_WALLCLOCK; assert_eq!(o.sanitize(), Err(SanitizeError::ValueOutOfBounds)); } #[test] fn test_epoch_slots_fill_range() { - let range: Vec = (0..5000).into_iter().collect(); + let range: Vec = (0..5000).collect(); let mut slots = EpochSlots::default(); assert_eq!(slots.fill(&range, 1), 5000); assert_eq!(slots.wallclock, 1); @@ -427,7 +427,7 @@ mod tests { } #[test] fn test_epoch_slots_fill_sparce_range() { - let range: Vec = (0..5000).into_iter().map(|x| x * 3).collect(); + let range: Vec = (0..5000).map(|x| x * 3).collect(); let mut slots = EpochSlots::default(); assert_eq!(slots.fill(&range, 2), 5000); assert_eq!(slots.wallclock, 2); @@ -444,7 +444,7 @@ mod tests { #[test] fn test_epoch_slots_fill_large_sparce_range() { - let range: Vec = (0..5000).into_iter().map(|x| x * 7).collect(); + let range: Vec = (0..5000).map(|x| x * 7).collect(); let mut slots = EpochSlots::default(); assert_eq!(slots.fill(&range, 2), 5000); assert_eq!(slots.to_slots(0), range); diff --git a/core/src/gossip_service.rs b/core/src/gossip_service.rs index 3d424909ee1c67..c80cdb5bc11386 100644 --- a/core/src/gossip_service.rs +++ b/core/src/gossip_service.rs @@ -294,7 +294,7 @@ mod tests { let contact_info = ContactInfo::new_localhost(&keypair.pubkey(), 0); let peer0_info = ContactInfo::new_localhost(&peer0, 0); let peer1_info = ContactInfo::new_localhost(&peer1, 0); - let cluster_info = ClusterInfo::new(contact_info.clone(), Arc::new(keypair)); + let cluster_info = ClusterInfo::new(contact_info, Arc::new(keypair)); cluster_info.insert_info(peer0_info.clone()); cluster_info.insert_info(peer1_info); @@ -343,7 +343,7 @@ mod tests { assert_eq!(met_criteria, true); let (met_criteria, _, _, _) = spy( - spy_ref.clone(), + spy_ref, None, Some(0), None, diff --git a/core/src/non_circulating_supply.rs b/core/src/non_circulating_supply.rs index 280cbf5b80b39c..447d81804a70c3 100644 --- a/core/src/non_circulating_supply.rs +++ b/core/src/non_circulating_supply.rs @@ -180,7 +180,7 @@ mod tests { bank = Arc::new(new_from_parent(&bank)); } assert_eq!(bank.epoch(), 1); - let non_circulating_supply = calculate_non_circulating_supply(bank.clone()); + let non_circulating_supply = calculate_non_circulating_supply(bank); assert_eq!( non_circulating_supply.lamports, num_non_circulating_accounts * new_balance diff --git a/core/src/poh_recorder.rs b/core/src/poh_recorder.rs index 06e3993ed058de..5653ca3b8cc274 100644 --- a/core/src/poh_recorder.rs +++ b/core/src/poh_recorder.rs @@ -759,9 +759,7 @@ mod tests { poh_recorder.tick(); let tx = test_tx(); let h1 = hash(b"hello world!"); - assert!(poh_recorder - .record(bank.slot(), h1, vec![tx.clone()]) - .is_err()); + assert!(poh_recorder.record(bank.slot(), h1, vec![tx]).is_err()); assert!(entry_receiver.try_recv().is_err()); } Blockstore::destroy(&ledger_path).unwrap(); @@ -800,7 +798,7 @@ mod tests { let tx = test_tx(); let h1 = hash(b"hello world!"); assert_matches!( - poh_recorder.record(bank.slot() + 1, h1, vec![tx.clone()]), + poh_recorder.record(bank.slot() + 1, h1, vec![tx]), Err(PohRecorderError::MaxHeightReached) ); } @@ -839,9 +837,7 @@ mod tests { assert_eq!(poh_recorder.tick_height, 1); let tx = test_tx(); let h1 = hash(b"hello world!"); - assert!(poh_recorder - .record(bank.slot(), h1, vec![tx.clone()]) - .is_ok()); + assert!(poh_recorder.record(bank.slot(), h1, vec![tx]).is_ok()); assert_eq!(poh_recorder.tick_cache.len(), 0); //tick in the cache + entry @@ -885,9 +881,7 @@ mod tests { assert_eq!(poh_recorder.tick_height, 2); let tx = test_tx(); let h1 = hash(b"hello world!"); - assert!(poh_recorder - .record(bank.slot(), h1, vec![tx.clone()]) - .is_err()); + assert!(poh_recorder.record(bank.slot(), h1, vec![tx]).is_err()); let (_bank, (entry, _tick_height)) = entry_receiver.recv().unwrap(); assert!(entry.is_tick()); @@ -1122,9 +1116,7 @@ mod tests { let tx = test_tx(); let h1 = hash(b"hello world!"); - assert!(poh_recorder - .record(bank.slot(), h1, vec![tx.clone()]) - .is_err()); + assert!(poh_recorder.record(bank.slot(), h1, vec![tx]).is_err()); assert!(poh_recorder.working_bank.is_none()); // Make sure the starting slot is updated assert_eq!(poh_recorder.start_slot, end_slot); diff --git a/core/src/poh_service.rs b/core/src/poh_service.rs index 76f322cb1a26d1..740a7ca6f42318 100644 --- a/core/src/poh_service.rs +++ b/core/src/poh_service.rs @@ -225,8 +225,8 @@ mod tests { } } exit.store(true, Ordering::Relaxed); - let _ = poh_service.join().unwrap(); - let _ = entry_producer.join().unwrap(); + poh_service.join().unwrap(); + entry_producer.join().unwrap(); } Blockstore::destroy(&ledger_path).unwrap(); } diff --git a/core/src/progress_map.rs b/core/src/progress_map.rs index 3f511d5eb1261f..15a50b62c8725b 100644 --- a/core/src/progress_map.rs +++ b/core/src/progress_map.rs @@ -424,7 +424,7 @@ mod test { fn test_add_node_pubkey_internal() { let num_vote_accounts = 10; let staked_vote_accounts = 5; - let vote_account_pubkeys: Vec<_> = std::iter::repeat_with(|| Pubkey::new_rand()) + let vote_account_pubkeys: Vec<_> = std::iter::repeat_with(Pubkey::new_rand) .take(num_vote_accounts) .collect(); let epoch_vote_accounts: HashMap<_, _> = vote_account_pubkeys @@ -491,7 +491,7 @@ mod test { // Addding another pubkey with different vote accounts should succeed // and increase stake node_pubkey = Pubkey::new_rand(); - let vote_account_pubkeys: Vec<_> = std::iter::repeat_with(|| Pubkey::new_rand()) + let vote_account_pubkeys: Vec<_> = std::iter::repeat_with(Pubkey::new_rand) .take(num_vote_accounts) .collect(); let epoch_vote_accounts: HashMap<_, _> = vote_account_pubkeys diff --git a/core/src/repair_service.rs b/core/src/repair_service.rs index e86725ad5cdc11..52aadd2fa637ba 100644 --- a/core/src/repair_service.rs +++ b/core/src/repair_service.rs @@ -828,7 +828,7 @@ mod test { #[test] pub fn test_update_lowest_slot() { let node_info = Node::new_localhost_with_pubkey(&Pubkey::default()); - let cluster_info = ClusterInfo::new_with_invalid_keypair(node_info.info.clone()); + let cluster_info = ClusterInfo::new_with_invalid_keypair(node_info.info); RepairService::update_lowest_slot(&Pubkey::default(), 5, &cluster_info); let lowest = cluster_info .get_lowest_slot_for_node(&Pubkey::default(), None, |lowest_slot, _| { @@ -889,7 +889,7 @@ mod test { .insert_shreds(shreds[..shreds.len() - 1].to_vec(), None, false) .unwrap(); - duplicate_slot_repair_statuses.insert(dead_slot, duplicate_status.clone()); + duplicate_slot_repair_statuses.insert(dead_slot, duplicate_status); // There is no repair_addr, so should not get filtered because the timeout // `std::u64::MAX` has not expired diff --git a/core/src/replay_stage.rs b/core/src/replay_stage.rs index faff4f58e8e551..58172d78c73c25 100644 --- a/core/src/replay_stage.rs +++ b/core/src/replay_stage.rs @@ -1842,8 +1842,8 @@ pub(crate) mod tests { fn simulate_fork_selection( neutral_fork: &ForkInfo, - forks: &Vec, - validators: &Vec, + forks: &[ForkInfo], + validators: &[ValidatorInfo], ) -> Vec> { fn vote(bank: &Arc, pubkey: &Pubkey, slot: Slot) { let mut vote_account = bank.get_account(&pubkey).unwrap(); @@ -2031,19 +2031,18 @@ pub(crate) mod tests { let (heaviest_bank, _) = ReplayStage::select_forks( &frozen_banks, &towers[i], - &mut fork_progresses[i], + &fork_progresses[i], &bank_fork_ancestors, ); - if heaviest_bank.is_none() { - None - } else { - let bank = heaviest_bank.unwrap(); + if let Some(bank) = heaviest_bank { let stats = &fork_progresses[i].get_fork_stats(bank.slot()).unwrap(); Some(ForkSelectionResponse { slot: bank.slot(), is_locked_out: stats.is_locked_out, }) + } else { + None } }) .collect() @@ -2388,7 +2387,7 @@ pub(crate) mod tests { if let Err(BlockstoreProcessorError::InvalidBlock(block_error)) = res { assert_eq!(block_error, BlockError::InvalidEntryHash); } else { - assert!(false); + panic!(); } } @@ -2413,7 +2412,7 @@ pub(crate) mod tests { if let Err(BlockstoreProcessorError::InvalidBlock(block_error)) = res { assert_eq!(block_error, BlockError::InvalidTickHashCount); } else { - assert!(false); + panic!(); } } @@ -2436,7 +2435,7 @@ pub(crate) mod tests { if let Err(BlockstoreProcessorError::InvalidBlock(block_error)) = res { assert_eq!(block_error, BlockError::InvalidTickCount); } else { - assert!(false); + panic!(); } // Too few ticks per slot @@ -2456,7 +2455,7 @@ pub(crate) mod tests { if let Err(BlockstoreProcessorError::InvalidBlock(block_error)) = res { assert_eq!(block_error, BlockError::InvalidTickCount); } else { - assert!(false); + panic!(); } } @@ -2478,7 +2477,7 @@ pub(crate) mod tests { if let Err(BlockstoreProcessorError::InvalidBlock(block_error)) = res { assert_eq!(block_error, BlockError::InvalidLastTick); } else { - assert!(false); + panic!(); } } @@ -2490,7 +2489,7 @@ pub(crate) mod tests { let slot = bank.slot(); let hashes_per_tick = bank.hashes_per_tick().unwrap_or(0); let mut entries = - entry::create_ticks(bank.ticks_per_slot(), hashes_per_tick, blockhash.clone()); + entry::create_ticks(bank.ticks_per_slot(), hashes_per_tick, blockhash); let last_entry_hash = entries.last().unwrap().hash; let tx = system_transaction::transfer(&genesis_keypair, &keypair.pubkey(), 2, blockhash); @@ -2502,7 +2501,7 @@ pub(crate) mod tests { if let Err(BlockstoreProcessorError::InvalidBlock(block_error)) = res { assert_eq!(block_error, BlockError::TrailingEntry); } else { - assert!(false); + panic!(); } } @@ -2597,7 +2596,7 @@ pub(crate) mod tests { let ledger_path = get_tmp_ledger_path!(); let blockstore = Arc::new(Blockstore::open(&ledger_path).unwrap()); let block_commitment_cache = Arc::new(RwLock::new( - BlockCommitmentCache::default_with_blockstore(blockstore.clone()), + BlockCommitmentCache::default_with_blockstore(blockstore), )); let (lockouts_sender, _) = AggregateCommitmentService::new( &Arc::new(AtomicBool::new(false)), @@ -2659,12 +2658,7 @@ pub(crate) mod tests { bank_forks.write().unwrap().insert(bank2); let arc_bank2 = bank_forks.read().unwrap().get(2).unwrap().clone(); leader_vote(&arc_bank2, &leader_voting_pubkey); - ReplayStage::update_commitment_cache( - arc_bank2.clone(), - 0, - leader_lamports, - &lockouts_sender, - ); + ReplayStage::update_commitment_cache(arc_bank2, 0, leader_lamports, &lockouts_sender); thread::sleep(Duration::from_millis(200)); let mut expected0 = BlockCommitment::default(); @@ -2736,7 +2730,7 @@ pub(crate) mod tests { let (transaction_status_sender, transaction_status_receiver) = unbounded(); let transaction_status_service = TransactionStatusService::new( transaction_status_receiver, - blockstore.clone(), + blockstore, &Arc::new(AtomicBool::new(false)), ); @@ -3423,7 +3417,7 @@ pub(crate) mod tests { let vote_tracker = VoteTracker::new(&bank_forks.root_bank()); for vote_pubkey in &vote_pubkeys { // Insert a vote for the last bank for each voter - vote_tracker.insert_vote(10, Arc::new(vote_pubkey.clone())); + vote_tracker.insert_vote(10, Arc::new(*vote_pubkey)); } // The last bank should reach propagation threshold, and propagate it all @@ -3514,7 +3508,7 @@ pub(crate) mod tests { let vote_tracker = VoteTracker::new(&bank_forks.root_bank()); // Insert a new vote - vote_tracker.insert_vote(10, Arc::new(vote_pubkeys[2].clone())); + vote_tracker.insert_vote(10, Arc::new(vote_pubkeys[2])); // The last bank should reach propagation threshold, and propagate it all // the way back through earlier leader banks diff --git a/core/src/result.rs b/core/src/result.rs index 87c9060ed085b4..5e69d3e180969a 100644 --- a/core/src/result.rs +++ b/core/src/result.rs @@ -136,7 +136,6 @@ impl std::convert::From for Error { mod tests { use crate::result::Error; use crate::result::Result; - use serde_json; use std::io; use std::io::Write; use std::net::SocketAddr; @@ -147,18 +146,15 @@ mod tests { use std::thread; fn addr_parse_error() -> Result { - let r = "12fdfasfsafsadfs".parse()?; - Ok(r) + Ok("12fdfasfsafsadfs".parse()?) } fn join_error() -> Result<()> { panic::set_hook(Box::new(|_info| {})); - let r = thread::spawn(|| panic!("hi")).join()?; - Ok(r) + Ok(thread::spawn(|| panic!("hi")).join()?) } fn json_error() -> Result<()> { - let r = serde_json::from_slice("=342{;;;;:}".as_bytes())?; - Ok(r) + Ok(serde_json::from_slice(b"=342{;;;;:}")?) } fn send_error() -> Result<()> { let (s, r) = channel(); diff --git a/core/src/rpc.rs b/core/src/rpc.rs index 2e9e0c7664ef8d..6d7cd24870e0ab 100644 --- a/core/src/rpc.rs +++ b/core/src/rpc.rs @@ -1568,12 +1568,8 @@ pub mod tests { let mut commitment_slot1 = BlockCommitment::default(); commitment_slot1.increase_confirmation_stake(1, 9); let mut block_commitment: HashMap = HashMap::new(); - block_commitment - .entry(0) - .or_insert(commitment_slot0.clone()); - block_commitment - .entry(1) - .or_insert(commitment_slot1.clone()); + block_commitment.entry(0).or_insert(commitment_slot0); + block_commitment.entry(1).or_insert(commitment_slot1); let block_commitment_cache = Arc::new(RwLock::new(BlockCommitmentCache::new( block_commitment, 0, @@ -1609,7 +1605,7 @@ pub mod tests { blockstore.insert_shreds(shreds, None, false).unwrap(); blockstore.set_roots(&[1]).unwrap(); - let mut roots = blockstore_roots.clone(); + let mut roots = blockstore_roots; if !roots.is_empty() { roots.retain(|&x| x > 0); let mut parent_bank = bank; @@ -1751,7 +1747,8 @@ pub mod tests { .. } = start_rpc_handler_with_tx(&bob_pubkey); - let req = format!(r#"{{"jsonrpc":"2.0","id":1,"method":"getClusterNodes"}}"#); + let req = r#"{"jsonrpc":"2.0","id":1,"method":"getClusterNodes"}"#; + let res = io.handle_request_sync(&req, meta); let result: Response = serde_json::from_str(&res.expect("actual response")) .expect("actual response deserialization"); @@ -1777,7 +1774,7 @@ pub mod tests { .. } = start_rpc_handler_with_tx(&bob_pubkey); - let req = format!(r#"{{"jsonrpc":"2.0","id":1,"method":"getSlotLeader"}}"#); + let req = r#"{"jsonrpc":"2.0","id":1,"method":"getSlotLeader"}"#; let res = io.handle_request_sync(&req, meta); let expected = format!(r#"{{"jsonrpc":"2.0","result":"{}","id":1}}"#, leader_pubkey); let expected: Response = @@ -1792,9 +1789,9 @@ pub mod tests { let bob_pubkey = Pubkey::new_rand(); let RpcHandler { io, meta, .. } = start_rpc_handler_with_tx(&bob_pubkey); - let req = format!(r#"{{"jsonrpc":"2.0","id":1,"method":"getTransactionCount"}}"#); + let req = r#"{"jsonrpc":"2.0","id":1,"method":"getTransactionCount"}"#; let res = io.handle_request_sync(&req, meta); - let expected = format!(r#"{{"jsonrpc":"2.0","result":4,"id":1}}"#); + let expected = r#"{"jsonrpc":"2.0","result":4,"id":1}"#; let expected: Response = serde_json::from_str(&expected).expect("expected response deserialization"); let result: Response = serde_json::from_str(&res.expect("actual response")) @@ -1807,7 +1804,7 @@ pub mod tests { let bob_pubkey = Pubkey::new_rand(); let RpcHandler { io, meta, .. } = start_rpc_handler_with_tx(&bob_pubkey); - let req = format!(r#"{{"jsonrpc":"2.0","id":1,"method":"minimumLedgerSlot"}}"#); + let req = r#"{"jsonrpc":"2.0","id":1,"method":"minimumLedgerSlot"}"#; let res = io.handle_request_sync(&req, meta); let expected = r#"{"jsonrpc":"2.0","result":0,"id":1}"#; let expected: Response = @@ -1822,7 +1819,7 @@ pub mod tests { let bob_pubkey = Pubkey::new_rand(); let RpcHandler { io, meta, .. } = start_rpc_handler_with_tx(&bob_pubkey); - let req = format!(r#"{{"jsonrpc":"2.0","id":1,"method":"getTotalSupply"}}"#); + let req = r#"{"jsonrpc":"2.0","id":1,"method":"getTotalSupply"}"#; let rep = io.handle_request_sync(&req, meta); let res: Response = serde_json::from_str(&rep.expect("actual response")) .expect("actual response deserialization"); @@ -1846,8 +1843,8 @@ pub mod tests { fn test_get_supply() { let bob_pubkey = Pubkey::new_rand(); let RpcHandler { io, meta, .. } = start_rpc_handler_with_tx(&bob_pubkey); - let req = format!(r#"{{"jsonrpc":"2.0","id":1,"method":"getSupply"}}"#); - let res = io.handle_request_sync(&req, meta.clone()); + let req = r#"{"jsonrpc":"2.0","id":1,"method":"getSupply"}"#; + let res = io.handle_request_sync(&req, meta); let json: Value = serde_json::from_str(&res.unwrap()).unwrap(); let supply: RpcSupply = serde_json::from_value(json["result"]["value"].clone()) .expect("actual response deserialization"); @@ -1873,7 +1870,7 @@ pub mod tests { let RpcHandler { io, meta, alice, .. } = start_rpc_handler_with_tx(&bob_pubkey); - let req = format!(r#"{{"jsonrpc":"2.0","id":1,"method":"getLargestAccounts"}}"#); + let req = r#"{"jsonrpc":"2.0","id":1,"method":"getLargestAccounts"}"#; let res = io.handle_request_sync(&req, meta.clone()); let json: Value = serde_json::from_str(&res.unwrap()).unwrap(); let largest_accounts: Vec = @@ -1910,19 +1907,15 @@ pub mod tests { })); // Test Circulating/NonCirculating Filter - let req = format!( - r#"{{"jsonrpc":"2.0","id":1,"method":"getLargestAccounts","params":[{{"filter":"circulating"}}]}}"# - ); + let req = r#"{"jsonrpc":"2.0","id":1,"method":"getLargestAccounts","params":[{"filter":"circulating"}]}"#; let res = io.handle_request_sync(&req, meta.clone()); let json: Value = serde_json::from_str(&res.unwrap()).unwrap(); let largest_accounts: Vec = serde_json::from_value(json["result"]["value"].clone()) .expect("actual response deserialization"); assert_eq!(largest_accounts.len(), 18); - let req = format!( - r#"{{"jsonrpc":"2.0","id":1,"method":"getLargestAccounts","params":[{{"filter":"nonCirculating"}}]}}"# - ); - let res = io.handle_request_sync(&req, meta.clone()); + let req = r#"{"jsonrpc":"2.0","id":1,"method":"getLargestAccounts","params":[{"filter":"nonCirculating"}]}"#; + let res = io.handle_request_sync(&req, meta); let json: Value = serde_json::from_str(&res.unwrap()).unwrap(); let largest_accounts: Vec = serde_json::from_value(json["result"]["value"].clone()) @@ -1967,7 +1960,7 @@ pub mod tests { let bob_pubkey = Pubkey::new_rand(); let RpcHandler { io, meta, bank, .. } = start_rpc_handler_with_tx(&bob_pubkey); - let req = format!(r#"{{"jsonrpc":"2.0","id":1,"method":"getInflation"}}"#); + let req = r#"{"jsonrpc":"2.0","id":1,"method":"getInflation"}"#; let rep = io.handle_request_sync(&req, meta); let res: Response = serde_json::from_str(&rep.expect("actual response")) .expect("actual response deserialization"); @@ -1988,7 +1981,7 @@ pub mod tests { let bob_pubkey = Pubkey::new_rand(); let RpcHandler { io, meta, bank, .. } = start_rpc_handler_with_tx(&bob_pubkey); - let req = format!(r#"{{"jsonrpc":"2.0","id":1,"method":"getEpochSchedule"}}"#); + let req = r#"{"jsonrpc":"2.0","id":1,"method":"getEpochSchedule"}"#; let rep = io.handle_request_sync(&req, meta); let res: Response = serde_json::from_str(&rep.expect("actual response")) .expect("actual response deserialization"); @@ -2284,7 +2277,7 @@ pub mod tests { r#"{{"jsonrpc":"2.0","id":1,"method":"getSignatureStatuses","params":[["{}"]]}}"#, confirmed_block_signatures[1] ); - let res = io.handle_request_sync(&req, meta.clone()); + let res = io.handle_request_sync(&req, meta); let expected_res: transaction::Result<()> = Err(TransactionError::InstructionError( 0, InstructionError::Custom(1), @@ -2306,7 +2299,7 @@ pub mod tests { .. } = start_rpc_handler_with_tx(&bob_pubkey); - let req = format!(r#"{{"jsonrpc":"2.0","id":1,"method":"getRecentBlockhash"}}"#); + let req = r#"{"jsonrpc":"2.0","id":1,"method":"getRecentBlockhash"}"#; let res = io.handle_request_sync(&req, meta); let expected = json!({ "jsonrpc": "2.0", @@ -2359,7 +2352,7 @@ pub mod tests { r#"{{"jsonrpc":"2.0","id":1,"method":"getFeeCalculatorForBlockhash","params":["{:?}"]}}"#, Hash::default() ); - let res = io.handle_request_sync(&req, meta.clone()); + let res = io.handle_request_sync(&req, meta); let expected = json!({ "jsonrpc": "2.0", "result": { @@ -2380,7 +2373,7 @@ pub mod tests { let bob_pubkey = Pubkey::new_rand(); let RpcHandler { io, meta, .. } = start_rpc_handler_with_tx(&bob_pubkey); - let req = format!(r#"{{"jsonrpc":"2.0","id":1,"method":"getFeeRateGovernor"}}"#); + let req = r#"{"jsonrpc":"2.0","id":1,"method":"getFeeRateGovernor"}"#; let res = io.handle_request_sync(&req, meta); let expected = json!({ "jsonrpc": "2.0", @@ -2453,7 +2446,7 @@ pub mod tests { }; let req = r#"{"jsonrpc":"2.0","id":1,"method":"sendTransaction","params":["37u9WtQpcm6ULa3Vmu7ySnANv"]}"#; - let res = io.handle_request_sync(req, meta.clone()); + let res = io.handle_request_sync(req, meta); let expected = r#"{"jsonrpc":"2.0","error":{"code":-32600,"message":"Invalid request"},"id":1}"#; let expected: Response = @@ -2573,7 +2566,7 @@ pub mod tests { let bob_pubkey = Pubkey::new_rand(); let RpcHandler { io, meta, .. } = start_rpc_handler_with_tx(&bob_pubkey); - let req = format!(r#"{{"jsonrpc":"2.0","id":1,"method":"getIdentity"}}"#); + let req = r#"{"jsonrpc":"2.0","id":1,"method":"getIdentity"}"#; let res = io.handle_request_sync(&req, meta); let expected = json!({ "jsonrpc": "2.0", @@ -2594,7 +2587,7 @@ pub mod tests { let bob_pubkey = Pubkey::new_rand(); let RpcHandler { io, meta, .. } = start_rpc_handler_with_tx(&bob_pubkey); - let req = format!(r#"{{"jsonrpc":"2.0","id":1,"method":"getVersion"}}"#); + let req = r#"{"jsonrpc":"2.0","id":1,"method":"getVersion"}"#; let res = io.handle_request_sync(&req, meta); let expected = json!({ "jsonrpc": "2.0", @@ -2623,10 +2616,10 @@ pub mod tests { let mut block_commitment: HashMap = HashMap::new(); block_commitment .entry(0) - .or_insert(commitment_slot0.clone()); + .or_insert_with(|| commitment_slot0.clone()); block_commitment .entry(1) - .or_insert(commitment_slot1.clone()); + .or_insert_with(|| commitment_slot1.clone()); let block_commitment_cache = Arc::new(RwLock::new(BlockCommitmentCache::new( block_commitment, 0, @@ -2678,8 +2671,7 @@ pub mod tests { .. } = start_rpc_handler_with_tx(&bob_pubkey); - let req = - format!(r#"{{"jsonrpc":"2.0","id":1,"method":"getBlockCommitment","params":[0]}}"#); + let req = r#"{"jsonrpc":"2.0","id":1,"method":"getBlockCommitment","params":[0]}"#; let res = io.handle_request_sync(&req, meta.clone()); let result: Response = serde_json::from_str(&res.expect("actual response")) .expect("actual response deserialization"); @@ -2705,8 +2697,7 @@ pub mod tests { ); assert_eq!(total_stake, 10); - let req = - format!(r#"{{"jsonrpc":"2.0","id":1,"method":"getBlockCommitment","params":[2]}}"#); + let req = r#"{"jsonrpc":"2.0","id":1,"method":"getBlockCommitment","params":[2]}"#; let res = io.handle_request_sync(&req, meta); let result: Response = serde_json::from_str(&res.expect("actual response")) .expect("actual response deserialization"); @@ -2735,8 +2726,7 @@ pub mod tests { .. } = start_rpc_handler_with_tx(&bob_pubkey); - let req = - format!(r#"{{"jsonrpc":"2.0","id":1,"method":"getConfirmedBlock","params":[0]}}"#); + let req = r#"{"jsonrpc":"2.0","id":1,"method":"getConfirmedBlock","params":[0]}"#; let res = io.handle_request_sync(&req, meta.clone()); let result: Value = serde_json::from_str(&res.expect("actual response")) .expect("actual response deserialization"); @@ -2776,9 +2766,7 @@ pub mod tests { } } - let req = format!( - r#"{{"jsonrpc":"2.0","id":1,"method":"getConfirmedBlock","params":[0, "binary"]}}"# - ); + let req = r#"{"jsonrpc":"2.0","id":1,"method":"getConfirmedBlock","params":[0,"binary"]}"#; let res = io.handle_request_sync(&req, meta); let result: Value = serde_json::from_str(&res.expect("actual response")) .expect("actual response deserialization"); @@ -2836,40 +2824,35 @@ pub mod tests { .unwrap() .set_get_largest_confirmed_root(8); - let req = - format!(r#"{{"jsonrpc":"2.0","id":1,"method":"getConfirmedBlocks","params":[0]}}"#); + let req = r#"{"jsonrpc":"2.0","id":1,"method":"getConfirmedBlocks","params":[0]}"#; let res = io.handle_request_sync(&req, meta.clone()); let result: Value = serde_json::from_str(&res.expect("actual response")) .expect("actual response deserialization"); let confirmed_blocks: Vec = serde_json::from_value(result["result"].clone()).unwrap(); assert_eq!(confirmed_blocks, roots[1..].to_vec()); - let req = - format!(r#"{{"jsonrpc":"2.0","id":1,"method":"getConfirmedBlocks","params":[2]}}"#); + let req = r#"{"jsonrpc":"2.0","id":1,"method":"getConfirmedBlocks","params":[2]}"#; let res = io.handle_request_sync(&req, meta.clone()); let result: Value = serde_json::from_str(&res.expect("actual response")) .expect("actual response deserialization"); let confirmed_blocks: Vec = serde_json::from_value(result["result"].clone()).unwrap(); assert_eq!(confirmed_blocks, vec![3, 4, 8]); - let req = - format!(r#"{{"jsonrpc":"2.0","id":1,"method":"getConfirmedBlocks","params":[0, 4]}}"#); + let req = r#"{"jsonrpc":"2.0","id":1,"method":"getConfirmedBlocks","params":[0,4]}"#; let res = io.handle_request_sync(&req, meta.clone()); let result: Value = serde_json::from_str(&res.expect("actual response")) .expect("actual response deserialization"); let confirmed_blocks: Vec = serde_json::from_value(result["result"].clone()).unwrap(); assert_eq!(confirmed_blocks, vec![1, 3, 4]); - let req = - format!(r#"{{"jsonrpc":"2.0","id":1,"method":"getConfirmedBlocks","params":[0, 7]}}"#); + let req = r#"{"jsonrpc":"2.0","id":1,"method":"getConfirmedBlocks","params":[0,7]}"#; let res = io.handle_request_sync(&req, meta.clone()); let result: Value = serde_json::from_str(&res.expect("actual response")) .expect("actual response deserialization"); let confirmed_blocks: Vec = serde_json::from_value(result["result"].clone()).unwrap(); assert_eq!(confirmed_blocks, vec![1, 3, 4]); - let req = - format!(r#"{{"jsonrpc":"2.0","id":1,"method":"getConfirmedBlocks","params":[9, 11]}}"#); + let req = r#"{"jsonrpc":"2.0","id":1,"method":"getConfirmedBlocks","params":[9,11]}"#; let res = io.handle_request_sync(&req, meta); let result: Value = serde_json::from_str(&res.expect("actual response")) .expect("actual response deserialization"); @@ -2880,7 +2863,7 @@ pub mod tests { #[test] fn test_get_block_time() { let bob_pubkey = Pubkey::new_rand(); - let base_timestamp = 1576183541; + let base_timestamp = 1_576_183_541; let RpcHandler { io, meta, @@ -2934,7 +2917,7 @@ pub mod tests { slot ); let res = io.handle_request_sync(&req, meta); - let expected = format!(r#"{{"jsonrpc":"2.0","result":null,"id":1}}"#); + let expected = r#"{"jsonrpc":"2.0","result":null,"id":1}"#; let expected: Response = serde_json::from_str(&expected).expect("expected response deserialization"); let result: Response = serde_json::from_str(&res.expect("actual response")) @@ -2982,7 +2965,7 @@ pub mod tests { // Check getVoteAccounts: the bootstrap validator vote account will be delinquent as it has // stake but has never voted, and the vote account with no stake should not be present. { - let req = format!(r#"{{"jsonrpc":"2.0","id":1,"method":"getVoteAccounts"}}"#); + let req = r#"{"jsonrpc":"2.0","id":1,"method":"getVoteAccounts"}"#; let res = io.handle_request_sync(&req, meta.clone()); let result: Value = serde_json::from_str(&res.expect("actual response")) .expect("actual response deserialization"); @@ -3090,7 +3073,7 @@ pub mod tests { json!([CommitmentConfig::recent()]) ); - let res = io.handle_request_sync(&req, meta.clone()); + let res = io.handle_request_sync(&req, meta); let result: Value = serde_json::from_str(&res.expect("actual response")) .expect("actual response deserialization"); diff --git a/core/src/rpc_pubsub.rs b/core/src/rpc_pubsub.rs index 2f3f0503e172c1..235c4404622191 100644 --- a/core/src/rpc_pubsub.rs +++ b/core/src/rpc_pubsub.rs @@ -447,23 +447,19 @@ mod tests { ); let _res = io.handle_request_sync(&req, session.clone()); - let req = - format!(r#"{{"jsonrpc":"2.0","id":1,"method":"signatureUnsubscribe","params":[0]}}"#); + let req = r#"{"jsonrpc":"2.0","id":1,"method":"signatureUnsubscribe","params":[0]}"#; let res = io.handle_request_sync(&req, session.clone()); - let expected = format!(r#"{{"jsonrpc":"2.0","result":true,"id":1}}"#); + let expected = r#"{"jsonrpc":"2.0","result":true,"id":1}"#; let expected: Response = serde_json::from_str(&expected).unwrap(); let result: Response = serde_json::from_str(&res.unwrap()).unwrap(); assert_eq!(expected, result); // Test bad parameter - let req = - format!(r#"{{"jsonrpc":"2.0","id":1,"method":"signatureUnsubscribe","params":[1]}}"#); - let res = io.handle_request_sync(&req, session.clone()); - let expected = format!( - r#"{{"jsonrpc":"2.0","error":{{"code":-32602,"message":"Invalid Request: Subscription id does not exist"}},"id":1}}"# - ); + let req = r#"{"jsonrpc":"2.0","id":1,"method":"signatureUnsubscribe","params":[1]}"#; + let res = io.handle_request_sync(&req, session); + let expected = r#"{"jsonrpc":"2.0","error":{"code":-32602,"message":"Invalid Request: Subscription id does not exist"},"id":1}"#; let expected: Response = serde_json::from_str(&expected).unwrap(); let result: Response = serde_json::from_str(&res.unwrap()).unwrap(); @@ -604,8 +600,7 @@ mod tests { let bank_forks = Arc::new(RwLock::new(BankForks::new(0, Bank::new(&genesis_config)))); let mut io = PubSubHandler::default(); - let rpc = - RpcSolPubSubImpl::default_with_blockstore_bank_forks(blockstore, bank_forks.clone()); + let rpc = RpcSolPubSubImpl::default_with_blockstore_bank_forks(blockstore, bank_forks); io.extend_with(rpc.to_delegate()); @@ -615,23 +610,19 @@ mod tests { ); let _res = io.handle_request_sync(&req, session.clone()); - let req = - format!(r#"{{"jsonrpc":"2.0","id":1,"method":"accountUnsubscribe","params":[0]}}"#); + let req = r#"{"jsonrpc":"2.0","id":1,"method":"accountUnsubscribe","params":[0]}"#; let res = io.handle_request_sync(&req, session.clone()); - let expected = format!(r#"{{"jsonrpc":"2.0","result":true,"id":1}}"#); + let expected = r#"{"jsonrpc":"2.0","result":true,"id":1}"#; let expected: Response = serde_json::from_str(&expected).unwrap(); let result: Response = serde_json::from_str(&res.unwrap()).unwrap(); assert_eq!(expected, result); // Test bad parameter - let req = - format!(r#"{{"jsonrpc":"2.0","id":1,"method":"accountUnsubscribe","params":[1]}}"#); - let res = io.handle_request_sync(&req, session.clone()); - let expected = format!( - r#"{{"jsonrpc":"2.0","error":{{"code":-32602,"message":"Invalid Request: Subscription id does not exist"}},"id":1}}"# - ); + let req = r#"{"jsonrpc":"2.0","id":1,"method":"accountUnsubscribe","params":[1]}"#; + let res = io.handle_request_sync(&req, session); + let expected = r#"{"jsonrpc":"2.0","error":{"code":-32602,"message":"Invalid Request: Subscription id does not exist"},"id":1}"#; let expected: Response = serde_json::from_str(&expected).unwrap(); let result: Response = serde_json::from_str(&res.unwrap()).unwrap(); @@ -746,7 +737,7 @@ mod tests { let mut block_commitment: HashMap = HashMap::new(); block_commitment.insert(0, BlockCommitment::default()); let mut new_block_commitment = - BlockCommitmentCache::new(block_commitment, 1, 10, bank2, blockstore.clone(), 1); + BlockCommitmentCache::new(block_commitment, 1, 10, bank2, blockstore, 1); let mut w_block_commitment_cache = block_commitment_cache.write().unwrap(); std::mem::swap(&mut *w_block_commitment_cache, &mut new_block_commitment); drop(w_block_commitment_cache); diff --git a/core/src/rpc_service.rs b/core/src/rpc_service.rs index 483c2f9fa94bc5..9218e2791e812c 100644 --- a/core/src/rpc_service.rs +++ b/core/src/rpc_service.rs @@ -452,7 +452,7 @@ mod tests { fn test_health_check_with_no_trusted_validators() { let cluster_info = Arc::new(ClusterInfo::new_with_invalid_keypair(ContactInfo::default())); - let rm = RpcRequestMiddleware::new(PathBuf::from("/"), None, cluster_info.clone(), None); + let rm = RpcRequestMiddleware::new(PathBuf::from("/"), None, cluster_info, None); assert_eq!(rm.health_check(), "ok"); } @@ -483,7 +483,7 @@ mod tests { .crds .insert( CrdsValue::new_unsigned(CrdsData::AccountsHashes(SnapshotHash::new( - trusted_validators[0].clone(), + trusted_validators[0], vec![ (1, Hash::default()), (1001, Hash::default()), @@ -503,7 +503,7 @@ mod tests { .crds .insert( CrdsValue::new_unsigned(CrdsData::AccountsHashes(SnapshotHash::new( - trusted_validators[1].clone(), + trusted_validators[1], vec![(1000 + HEALTH_CHECK_SLOT_DISTANCE - 1, Hash::default())], ))), 1, @@ -519,7 +519,7 @@ mod tests { .crds .insert( CrdsValue::new_unsigned(CrdsData::AccountsHashes(SnapshotHash::new( - trusted_validators[2].clone(), + trusted_validators[2], vec![(1000 + HEALTH_CHECK_SLOT_DISTANCE, Hash::default())], ))), 1, diff --git a/core/src/rpc_subscriptions.rs b/core/src/rpc_subscriptions.rs index 393a1d3810665a..49b2fece7ce003 100644 --- a/core/src/rpc_subscriptions.rs +++ b/core/src/rpc_subscriptions.rs @@ -665,7 +665,6 @@ pub(crate) mod tests { use jsonrpc_core::futures::{self, stream::Stream}; use jsonrpc_pubsub::typed::Subscriber; use serial_test_derive::serial; - use solana_budget_program; use solana_ledger::{ blockstore::Blockstore, genesis_utils::{create_genesis_config, GenesisConfigInfo}, @@ -924,8 +923,8 @@ pub(crate) mod tests { let cache1 = BlockCommitment::default(); let mut block_commitment = HashMap::new(); - block_commitment.entry(0).or_insert(cache0.clone()); - block_commitment.entry(1).or_insert(cache1.clone()); + block_commitment.entry(0).or_insert(cache0); + block_commitment.entry(1).or_insert(cache1); let block_commitment_cache = BlockCommitmentCache::new(block_commitment, 0, 10, bank1, blockstore, 0); diff --git a/core/src/serve_repair.rs b/core/src/serve_repair.rs index 9fecab2c058bc3..edf0ac5ae6da9a 100644 --- a/core/src/serve_repair.rs +++ b/core/src/serve_repair.rs @@ -768,7 +768,7 @@ mod tests { .expect("run_orphan packets") .packets .iter() - .map(|b| b.clone()) + .cloned() .collect(); let expected: Vec<_> = (1..=3) .rev() diff --git a/core/src/sigverify_shreds.rs b/core/src/sigverify_shreds.rs index bea9ca3b09c2ef..7787ff903a2577 100644 --- a/core/src/sigverify_shreds.rs +++ b/core/src/sigverify_shreds.rs @@ -82,7 +82,7 @@ pub mod tests { fn test_sigverify_shreds_read_slots() { solana_logger::setup(); let mut shred = Shred::new_from_data( - 0xdeadc0de, + 0xdead_c0de, 0xc0de, 0xdead, Some(&[1, 2, 3, 4]), @@ -101,7 +101,7 @@ pub mod tests { batch[0].packets[0].meta.size = shred.payload.len(); let mut shred = Shred::new_from_data( - 0xc0dedead, + 0xc0de_dead, 0xc0de, 0xdead, Some(&[1, 2, 3, 4]), @@ -116,7 +116,7 @@ pub mod tests { batch[1].packets[0].data[0..shred.payload.len()].copy_from_slice(&shred.payload); batch[1].packets[0].meta.size = shred.payload.len(); - let expected: HashSet = [0xc0dedead, 0xdeadc0de].iter().cloned().collect(); + let expected: HashSet = [0xc0de_dead, 0xdead_c0de].iter().cloned().collect(); assert_eq!(ShredSigVerifier::read_slots(&batch), expected); } diff --git a/core/src/tvu.rs b/core/src/tvu.rs index d1a0908a3fe6de..1447608e6db35c 100644 --- a/core/src/tvu.rs +++ b/core/src/tvu.rs @@ -259,7 +259,7 @@ pub mod tests { //start cluster_info1 let cluster_info1 = ClusterInfo::new_with_invalid_keypair(target1.info.clone()); - cluster_info1.insert_info(leader.info.clone()); + cluster_info1.insert_info(leader.info); let cref1 = Arc::new(cluster_info1); let (blockstore_path, _) = create_new_tmp_ledger!(&genesis_config); diff --git a/core/src/verified_vote_packets.rs b/core/src/verified_vote_packets.rs index 019e29ac3a96fc..2cf566e89884c1 100644 --- a/core/src/verified_vote_packets.rs +++ b/core/src/verified_vote_packets.rs @@ -94,7 +94,7 @@ mod tests { let (new_update_version, updates) = verified_vote_packets.get_latest_votes(1); assert_eq!(new_update_version, 2); assert_eq!(updates.len(), 1); - assert!(updates[0].packets.len() > 0); + assert_eq!(updates[0].packets.is_empty(), false); // If the given timestamp is greater than all timestamps in any update, // returned timestamp should be the same as the given timestamp, and @@ -123,8 +123,7 @@ mod tests { }; let later_packets = Packets::new(vec![data, Packet::default()]); - s.send(vec![(label1.clone(), later_packets.clone())]) - .unwrap(); + s.send(vec![(label1.clone(), later_packets)]).unwrap(); let mut verified_vote_packets = VerifiedVotePackets(HashMap::new()); verified_vote_packets .get_and_process_vote_packets(&r, &mut update_version) diff --git a/core/src/window_service.rs b/core/src/window_service.rs index 84cfffe4217b8e..70a41823f68fdb 100644 --- a/core/src/window_service.rs +++ b/core/src/window_service.rs @@ -594,7 +594,7 @@ mod test { let shreds = local_entries_to_shred(&[Entry::default()], slot + 1, slot - 1, &leader_keypair); assert_eq!( - should_retransmit_and_persist(&shreds[0], Some(bank.clone()), &cache, &me_id, slot, 0), + should_retransmit_and_persist(&shreds[0], Some(bank), &cache, &me_id, slot, 0), false ); diff --git a/core/tests/bank_forks.rs b/core/tests/bank_forks.rs index 7b2fd1e6062a81..e4174965c4f8c6 100644 --- a/core/tests/bank_forks.rs +++ b/core/tests/bank_forks.rs @@ -267,7 +267,7 @@ mod tests { }; bank_forks - .generate_accounts_package(slot, &vec![], &package_sender) + .generate_accounts_package(slot, &[], &package_sender) .unwrap(); if slot == saved_slot as u64 { diff --git a/core/tests/client.rs b/core/tests/client.rs index 71be8443cb7f06..a16c269ddf67e1 100644 --- a/core/tests/client.rs +++ b/core/tests/client.rs @@ -79,7 +79,7 @@ fn test_rpc_client() { assert!(confirmed_tx); assert_eq!(client.get_balance(&bob_pubkey).unwrap(), 20); - assert_eq!(client.get_balance(&alice.pubkey()).unwrap(), 999980); + assert_eq!(client.get_balance(&alice.pubkey()).unwrap(), 999_980); server.close().unwrap(); remove_dir_all(ledger_path).unwrap(); diff --git a/core/tests/cluster_info.rs b/core/tests/cluster_info.rs index 42f138f396bf96..55bb6b132cdc59 100644 --- a/core/tests/cluster_info.rs +++ b/core/tests/cluster_info.rs @@ -65,6 +65,7 @@ fn retransmit( shred } +#[allow(clippy::type_complexity)] fn run_simulation(stakes: &[u64], fanout: usize) { let num_threads = num_threads(); // set timeout to 5 minutes @@ -91,7 +92,7 @@ fn run_simulation(stakes: &[u64], fanout: usize) { let range: Vec<_> = (1..=stakes.len()).collect(); let chunk_size = (stakes.len() + num_threads - 1) / num_threads; range.chunks(chunk_size).for_each(|chunk| { - chunk.into_iter().for_each(|i| { + chunk.iter().for_each(|i| { //distribute neighbors across threads to maximize parallel compute let batch_ix = *i as usize % batches.len(); let node = ContactInfo::new_localhost(&Pubkey::new_rand(), 0); @@ -121,16 +122,15 @@ fn run_simulation(stakes: &[u64], fanout: usize) { &stakes_and_index, seed, ); - let peers = shuffled_stakes_and_indexes + shuffled_stakes_and_indexes .into_iter() .map(|(_, i)| peers[i].clone()) - .collect(); - peers + .collect() }) .collect(); // create some "shreds". - (0..shreds_len).into_iter().for_each(|i| { + (0..shreds_len).for_each(|i| { let broadcast_table = &shuffled_peers[i]; find_insert_shred(&broadcast_table[0].id, i as i32, &mut batches); }); diff --git a/core/tests/crds_gossip.rs b/core/tests/crds_gossip.rs index f73aeb0dcd78ca..c1ee0172d6c4aa 100644 --- a/core/tests/crds_gossip.rs +++ b/core/tests/crds_gossip.rs @@ -93,7 +93,7 @@ fn star_network_create(num: usize) -> Network { .collect(); let mut node = CrdsGossip::default(); let id = entry.label().pubkey(); - node.crds.insert(entry.clone(), 0).unwrap(); + node.crds.insert(entry, 0).unwrap(); node.set_self(&id); network.insert(id, Node::new(Arc::new(Mutex::new(node)))); Network::new(network) @@ -106,7 +106,7 @@ fn rstar_network_create(num: usize) -> Network { ))); let mut origin = CrdsGossip::default(); let id = entry.label().pubkey(); - origin.crds.insert(entry.clone(), 0).unwrap(); + origin.crds.insert(entry, 0).unwrap(); origin.set_self(&id); let mut network: HashMap<_, _> = (1..num) .map(|_| { @@ -144,7 +144,7 @@ fn ring_network_create(num: usize) -> Network { for k in 0..keys.len() { let start_info = { let start = &network[&keys[k]]; - let start_id = start.lock().unwrap().id.clone(); + let start_id = start.lock().unwrap().id; start .lock() .unwrap() @@ -183,7 +183,7 @@ fn connected_staked_network_create(stakes: &[u64]) -> Network { .iter() .map(|k| { let start = &network[k].lock().unwrap(); - let start_id = start.id.clone(); + let start_id = start.id; let start_label = CrdsValueLabel::ContactInfo(start_id); start.crds.lookup(&start_label).unwrap().clone() }) @@ -448,7 +448,7 @@ fn network_run_pull( .unwrap(); bytes += serialized_size(&rsp).unwrap() as usize; msgs += rsp.len(); - network.get(&from).map(|node| { + if let Some(node) = network.get(&from) { node.lock() .unwrap() .mark_pull_request_creation_time(&from, now); @@ -456,7 +456,7 @@ fn network_run_pull( .lock() .unwrap() .process_pull_response(&from, &timeouts, rsp, now); - }); + } (bytes, msgs, overhead) }) .collect(); diff --git a/core/tests/fork-selection.rs b/core/tests/fork-selection.rs index c89b9d4cd526e2..66fb20b7615ea9 100644 --- a/core/tests/fork-selection.rs +++ b/core/tests/fork-selection.rs @@ -175,9 +175,9 @@ impl Tower { } } let trunk = self.votes.get(self.converge_depth).cloned(); - trunk.map(|t| { + if let Some(t) = trunk { self.delayed_votes.retain(|v| v.fork.id > t.fork.id); - }); + } } pub fn pop_best_votes( &mut self, @@ -361,6 +361,7 @@ fn test_is_trunk_of_4() { assert!(!b2.is_trunk_of(&b1, &tree)); } #[test] +#[allow(clippy::cognitive_complexity)] fn test_push_vote() { let tree = HashMap::new(); let bmap = HashMap::new(); @@ -396,7 +397,7 @@ fn test_push_vote() { assert_eq!(tower.votes[0].lockout, 2); let b1 = Fork { id: 1, base: 1 }; - let vote = Vote::new(b1.clone(), 8); + let vote = Vote::new(b1, 8); assert!(!tower.push_vote(vote, &tree, &bmap)); let vote = Vote::new(b0.clone(), 8); @@ -408,7 +409,7 @@ fn test_push_vote() { assert_eq!(tower.votes[2].lockout, 8); assert_eq!(tower.votes[3].lockout, 16); - let vote = Vote::new(b0.clone(), 10); + let vote = Vote::new(b0, 10); assert!(tower.push_vote(vote, &tree, &bmap)); assert_eq!(tower.votes.len(), 2); assert_eq!(tower.votes[0].lockout, 2); @@ -417,7 +418,6 @@ fn test_push_vote() { fn create_towers(sz: usize, height: usize, delay_count: usize) -> Vec { (0..sz) - .into_iter() .map(|_| Tower::new(32, height, delay_count)) .collect() } @@ -438,7 +438,7 @@ fn calc_fork_depth(fork_tree: &HashMap, id: usize) -> usize { /// map of `fork id` to `tower count` /// This map contains the number of nodes that have the fork as an ancestor. /// The fork with the highest count that is the newest is the cluster "trunk". -fn calc_fork_map(towers: &Vec, fork_tree: &HashMap) -> HashMap { +fn calc_fork_map(towers: &[Tower], fork_tree: &HashMap) -> HashMap { let mut lca_map: HashMap = HashMap::new(); for tower in towers { let mut start = tower.last_fork(); @@ -460,7 +460,7 @@ fn calc_newest_trunk(bmap: &HashMap) -> (usize, usize) { data.last().map(|v| (*v.0, *v.1)).unwrap() } /// how common is the latest fork of all the nodes -fn calc_tip_converged(towers: &Vec, bmap: &HashMap) -> usize { +fn calc_tip_converged(towers: &[Tower], bmap: &HashMap) -> usize { let sum: usize = towers .iter() .map(|n| *bmap.get(&n.last_fork().id).unwrap_or(&0)) diff --git a/core/tests/ledger_cleanup.rs b/core/tests/ledger_cleanup.rs index c91880ce4bb27a..7e5ad664bfd047 100644 --- a/core/tests/ledger_cleanup.rs +++ b/core/tests/ledger_cleanup.rs @@ -81,18 +81,15 @@ mod tests { impl CpuStats { fn update(&self) { - match self.sys.cpu_load_aggregate() { - Ok(cpu) => { - std::thread::sleep(Duration::from_millis(400)); - let cpu_new = CpuStatsInner::from(cpu.done().unwrap()); - *self.stats.write().unwrap() = cpu_new; - } - _ => (), + if let Ok(cpu) = self.sys.cpu_load_aggregate() { + std::thread::sleep(Duration::from_millis(400)); + let cpu_new = CpuStatsInner::from(cpu.done().unwrap()); + *self.stats.write().unwrap() = cpu_new; } } fn get_stats(&self) -> CpuStatsInner { - self.stats.read().unwrap().clone() + *self.stats.read().unwrap() } } @@ -118,7 +115,7 @@ mod tests { .unwrap(); Self { - cpu_stats: cpu_stats.clone(), + cpu_stats, t_cleanup, } } diff --git a/dos/src/main.rs b/dos/src/main.rs index 132b9c94cf7087..084a16f9702bbe 100644 --- a/dos/src/main.rs +++ b/dos/src/main.rs @@ -175,7 +175,7 @@ pub mod test { #[test] fn test_dos() { let nodes = [ContactInfo::new_localhost(&Pubkey::new_rand(), timestamp())]; - let entrypoint_addr = nodes[0].gossip.clone(); + let entrypoint_addr = nodes[0].gossip; run_dos( &nodes, 1, diff --git a/faucet/src/faucet.rs b/faucet/src/faucet.rs index dd67ab633ed42d..522fff597c7ed2 100644 --- a/faucet/src/faucet.rs +++ b/faucet/src/faucet.rs @@ -323,7 +323,7 @@ mod tests { fn test_clear_request_count() { let keypair = Keypair::new(); let mut faucet = Faucet::new(keypair, None, None); - faucet.request_current = faucet.request_current + 256; + faucet.request_current += 256; assert_eq!(faucet.request_current, 256); faucet.clear_request_count(); assert_eq!(faucet.request_current, 0); diff --git a/genesis/src/main.rs b/genesis/src/main.rs index 046929ff415570..54f6cb18c01311 100644 --- a/genesis/src/main.rs +++ b/genesis/src/main.rs @@ -555,7 +555,6 @@ mod tests { use std::fs::remove_file; use std::io::Write; use std::path::Path; - use tempfile; #[test] fn test_append_primordial_accounts_to_genesis() { diff --git a/genesis/src/unlocks.rs b/genesis/src/unlocks.rs index ce2b3932972326..c54cf88515298a 100644 --- a/genesis/src/unlocks.rs +++ b/genesis/src/unlocks.rs @@ -143,9 +143,10 @@ mod tests { use super::*; #[test] + #[allow(clippy::float_cmp)] fn test_make_lockups() { // this number just a random val - let total_lamports: u64 = 1725987234408923; + let total_lamports: u64 = 1_725_987_234_408_923; // expected config const EPOCHS_PER_MONTH: Epoch = 2; diff --git a/ledger-tool/Cargo.toml b/ledger-tool/Cargo.toml index 8a08c788261e37..46fd615773e00d 100644 --- a/ledger-tool/Cargo.toml +++ b/ledger-tool/Cargo.toml @@ -10,6 +10,7 @@ homepage = "https://solana.com/" [dependencies] bs58 = "0.3.1" +bytecount = "0.6.0" clap = "2.33.1" histogram = "*" serde_json = "1.0.53" diff --git a/ledger-tool/tests/basic.rs b/ledger-tool/tests/basic.rs index 709b9e586daabd..fa5a6de98ba863 100644 --- a/ledger-tool/tests/basic.rs +++ b/ledger-tool/tests/basic.rs @@ -13,7 +13,7 @@ fn run_ledger_tool(args: &[&str]) -> Output { } fn count_newlines(chars: &[u8]) -> usize { - chars.iter().filter(|&c| *c == '\n' as u8).count() + bytecount::count(chars, b'\n') } #[test] diff --git a/ledger/src/bank_forks.rs b/ledger/src/bank_forks.rs index b3bf1474f5890c..3bd5fbb9002a4f 100644 --- a/ledger/src/bank_forks.rs +++ b/ledger/src/bank_forks.rs @@ -402,7 +402,7 @@ mod tests { assert_eq!(bank_forks.root(), 0); assert_eq!(bank_forks.working_bank().slot(), 1); - let bank_forks = BankForks::new_from_banks(&[child_bank.clone(), bank.clone()], 0); + let bank_forks = BankForks::new_from_banks(&[child_bank, bank], 0); assert_eq!(bank_forks.root(), 0); assert_eq!(bank_forks.working_bank().slot(), 1); } diff --git a/ledger/src/blockstore.rs b/ledger/src/blockstore.rs index 8c1d1ca6d72078..63c38970ceb6c0 100644 --- a/ledger/src/blockstore.rs +++ b/ledger/src/blockstore.rs @@ -4085,6 +4085,7 @@ pub mod tests { } #[test] + #[allow(clippy::cognitive_complexity)] pub fn test_forward_chaining_is_connected() { let blockstore_path = get_tmp_ledger_path!(); { @@ -4284,7 +4285,7 @@ pub mod tests { let blockstore = Blockstore::open(&blockstore_path).unwrap(); // Slot doesn't exist - assert!(blockstore.get_slots_since(&vec![0]).unwrap().is_empty()); + assert!(blockstore.get_slots_since(&[0]).unwrap().is_empty()); let mut meta0 = SlotMeta::new(0, 0); blockstore.meta_cf.put(0, &meta0).unwrap(); @@ -4292,25 +4293,22 @@ pub mod tests { // Slot exists, chains to nothing let expected: HashMap> = HashMap::from_iter(vec![(0, vec![])].into_iter()); - assert_eq!(blockstore.get_slots_since(&vec![0]).unwrap(), expected); + assert_eq!(blockstore.get_slots_since(&[0]).unwrap(), expected); meta0.next_slots = vec![1, 2]; blockstore.meta_cf.put(0, &meta0).unwrap(); // Slot exists, chains to some other slots let expected: HashMap> = HashMap::from_iter(vec![(0, vec![1, 2])].into_iter()); - assert_eq!(blockstore.get_slots_since(&vec![0]).unwrap(), expected); - assert_eq!(blockstore.get_slots_since(&vec![0, 1]).unwrap(), expected); + assert_eq!(blockstore.get_slots_since(&[0]).unwrap(), expected); + assert_eq!(blockstore.get_slots_since(&[0, 1]).unwrap(), expected); let mut meta3 = SlotMeta::new(3, 1); meta3.next_slots = vec![10, 5]; blockstore.meta_cf.put(3, &meta3).unwrap(); let expected: HashMap> = HashMap::from_iter(vec![(0, vec![1, 2]), (3, vec![10, 5])].into_iter()); - assert_eq!( - blockstore.get_slots_since(&vec![0, 1, 3]).unwrap(), - expected - ); + assert_eq!(blockstore.get_slots_since(&[0, 1, 3]).unwrap(), expected); } Blockstore::destroy(&blockstore_path).expect("Expected successful database destruction"); @@ -4899,11 +4897,8 @@ pub mod tests { // Trying to insert value into slot <= than last root should fail { - let mut coding_shred = Shred::new_empty_from_header( - shred.clone(), - DataShredHeader::default(), - coding.clone(), - ); + let mut coding_shred = + Shred::new_empty_from_header(shred, DataShredHeader::default(), coding); let index = index_cf.get(coding_shred.slot()).unwrap().unwrap(); coding_shred.set_slot(*last_root.read().unwrap()); assert!(!Blockstore::should_insert_coding_shred( @@ -5022,7 +5017,7 @@ pub mod tests { .unwrap(); for ((slot, _), _) in data_iter { if slot > 5 { - assert!(false); + panic!(); } } @@ -5051,7 +5046,7 @@ pub mod tests { .slot_meta_iterator(0) .unwrap() .for_each(|(_, _)| { - assert!(false); + panic!(); }); drop(blockstore); @@ -5095,7 +5090,7 @@ pub mod tests { blockstore .slot_meta_iterator(5) .unwrap() - .for_each(|_| assert!(false)); + .for_each(|_| panic!()); drop(blockstore); Blockstore::destroy(&blockstore_path).expect("Expected successful database destruction"); @@ -5479,7 +5474,7 @@ pub mod tests { #[test] fn test_get_block_timestamps() { let vote_keypairs: Vec = (0..6).map(|_| Keypair::new()).collect(); - let base_timestamp = 1576183541; + let base_timestamp = 1_576_183_541; let mut expected_timestamps: Vec<(Pubkey, (Slot, UnixTimestamp))> = Vec::new(); // Populate slot 1 with vote transactions, some of which have timestamps @@ -5506,7 +5501,7 @@ pub mod tests { let mut tick = create_ticks(1, 0, hash(&serialize(&i).unwrap())); vote_entries.append(&mut tick); } - let shreds = entries_to_test_shreds(vote_entries.clone(), 1, 0, true, 0); + let shreds = entries_to_test_shreds(vote_entries, 1, 0, true, 0); let ledger_path = get_tmp_ledger_path!(); let blockstore = Blockstore::open(&ledger_path).unwrap(); blockstore.insert_shreds(shreds, None, false).unwrap(); @@ -5553,7 +5548,7 @@ pub mod tests { #[test] fn test_calculate_stake_weighted_timestamp() { - let recent_timestamp: UnixTimestamp = 1578909061; + let recent_timestamp: UnixTimestamp = 1_578_909_061; let slot = 5; let slot_duration = Duration::from_millis(400); let expected_offset = (slot * slot_duration).as_secs(); @@ -5738,6 +5733,7 @@ pub mod tests { } #[test] + #[allow(clippy::cognitive_complexity)] fn test_transaction_status_index() { let blockstore_path = get_tmp_ledger_path!(); { @@ -5942,6 +5938,7 @@ pub mod tests { } #[test] + #[allow(clippy::cognitive_complexity)] fn test_purge_transaction_status() { let blockstore_path = get_tmp_ledger_path!(); { @@ -6116,8 +6113,8 @@ pub mod tests { let status = TransactionStatusMeta { status: solana_sdk::transaction::Result::<()>::Ok(()), fee: 42u64, - pre_balances: pre_balances_vec.clone(), - post_balances: post_balances_vec.clone(), + pre_balances: pre_balances_vec, + post_balances: post_balances_vec, }; let signature1 = Signature::new(&[1u8; 64]); @@ -6132,46 +6129,46 @@ pub mod tests { // signature4 in 2 non-roots, // extra entries transaction_status_cf - .put((0, signature2.clone(), 1), &status) + .put((0, signature2, 1), &status) .unwrap(); transaction_status_cf - .put((0, signature2.clone(), 2), &status) + .put((0, signature2, 2), &status) .unwrap(); transaction_status_cf - .put((0, signature4.clone(), 0), &status) + .put((0, signature4, 0), &status) .unwrap(); transaction_status_cf - .put((0, signature4.clone(), 1), &status) + .put((0, signature4, 1), &status) .unwrap(); transaction_status_cf - .put((0, signature5.clone(), 0), &status) + .put((0, signature5, 0), &status) .unwrap(); transaction_status_cf - .put((0, signature5.clone(), 1), &status) + .put((0, signature5, 1), &status) .unwrap(); // Initialize index 1, including: // signature4 in non-root and root, // extra entries transaction_status_cf - .put((1, signature4.clone(), 1), &status) + .put((1, signature4, 1), &status) .unwrap(); transaction_status_cf - .put((1, signature4.clone(), 2), &status) + .put((1, signature4, 2), &status) .unwrap(); transaction_status_cf - .put((1, signature5.clone(), 0), &status) + .put((1, signature5, 0), &status) .unwrap(); transaction_status_cf - .put((1, signature5.clone(), 1), &status) + .put((1, signature5, 1), &status) .unwrap(); blockstore.set_roots(&[2]).unwrap(); @@ -6508,8 +6505,8 @@ pub mod tests { transactions.into_iter(), ); assert_eq!(map.len(), 5); - for x in 0..4 { - assert_eq!(map[x].meta.as_ref().unwrap().fee, x as u64); + for (x, m) in map.iter().take(4).enumerate() { + assert_eq!(m.meta.as_ref().unwrap().fee, x as u64); } assert_eq!(map[4].meta, None); } @@ -6771,8 +6768,8 @@ pub mod tests { let entries1 = make_slot_entries_with_transactions(1); let entries2 = make_slot_entries_with_transactions(1); let leader_keypair = Arc::new(Keypair::new()); - let shredder = Shredder::new(slot, 0, 1.0, leader_keypair.clone(), 0, 0) - .expect("Failed in creating shredder"); + let shredder = + Shredder::new(slot, 0, 1.0, leader_keypair, 0, 0).expect("Failed in creating shredder"); let (shreds, _, _) = shredder.entries_to_shreds(&entries1, true, 0); let (duplicate_shreds, _, _) = shredder.entries_to_shreds(&entries2, true, 0); let shred = shreds[0].clone(); diff --git a/ledger/src/blockstore_processor.rs b/ledger/src/blockstore_processor.rs index f8b17746d9f456..da61da04a0733d 100644 --- a/ledger/src/blockstore_processor.rs +++ b/ledger/src/blockstore_processor.rs @@ -1102,7 +1102,7 @@ pub mod tests { ..ProcessOptions::default() }; let (bank_forks, _leader_schedule) = - process_blockstore(&genesis_config, &blockstore, Vec::new(), opts.clone()).unwrap(); + process_blockstore(&genesis_config, &blockstore, Vec::new(), opts).unwrap(); assert_eq!(frozen_bank_slots(&bank_forks), vec![0]); // slot 1 isn't "full", we stop at slot zero @@ -1197,8 +1197,8 @@ pub mod tests { .parents() .iter() .map(|bank| bank.slot()) - .collect::>() - .is_empty()); + .next() + .is_none()); // Ensure bank_forks holds the right banks verify_fork_infos(&bank_forks); @@ -1488,8 +1488,8 @@ pub mod tests { .parents() .iter() .map(|bank| bank.slot()) - .collect::>() - .is_empty()); + .next() + .is_none()); } #[test] @@ -1756,7 +1756,7 @@ pub mod tests { // ensure bank can process a tick assert_eq!(bank.tick_height(), 0); let tick = next_entry(&genesis_config.hash(), 1, vec![]); - assert_eq!(process_entries(&bank, &[tick.clone()], true, None), Ok(())); + assert_eq!(process_entries(&bank, &[tick], true, None), Ok(())); assert_eq!(bank.tick_height(), 1); } @@ -2026,9 +2026,9 @@ pub mod tests { assert!(process_entries( &bank, &[ - entry_1_to_mint.clone(), - entry_2_to_3_and_1_to_mint.clone(), - entry_conflict_itself.clone() + entry_1_to_mint, + entry_2_to_3_and_1_to_mint, + entry_conflict_itself, ], false, None, @@ -2199,21 +2199,18 @@ pub mod tests { // Transfer lamports to each other let entry = next_entry(&bank.last_blockhash(), 1, tx_vector); - assert_eq!(process_entries(&bank, &vec![entry], true, None), Ok(())); + assert_eq!(process_entries(&bank, &[entry], true, None), Ok(())); bank.squash(); // Even number keypair should have balance of 2 * initial_lamports and // odd number keypair should have balance of 0, which proves // that even in case of random order of execution, overall state remains // consistent. - for i in 0..num_accounts { + for (i, keypair) in keypairs.iter().enumerate() { if i % 2 == 0 { - assert_eq!( - bank.get_balance(&keypairs[i].pubkey()), - 2 * initial_lamports - ); + assert_eq!(bank.get_balance(&keypair.pubkey()), 2 * initial_lamports); } else { - assert_eq!(bank.get_balance(&keypairs[i].pubkey()), 0); + assert_eq!(bank.get_balance(&keypair.pubkey()), 0); } } } @@ -2260,12 +2257,7 @@ pub mod tests { system_transaction::transfer(&keypair1, &keypair4.pubkey(), 1, bank.last_blockhash()); let entry_2 = next_entry(&tick.hash, 1, vec![tx]); assert_eq!( - process_entries( - &bank, - &[entry_1.clone(), tick.clone(), entry_2.clone()], - true, - None - ), + process_entries(&bank, &[entry_1, tick, entry_2.clone()], true, None), Ok(()) ); assert_eq!(bank.get_balance(&keypair3.pubkey()), 1); @@ -2539,7 +2531,9 @@ pub mod tests { .expect("process ticks failed"); if i % 16 == 0 { - root.map(|old_root| old_root.squash()); + if let Some(old_root) = root { + old_root.squash(); + } root = Some(bank.clone()); } i += 1; @@ -2584,7 +2578,7 @@ pub mod tests { account_paths: Vec, ) -> EpochSchedule { let bank = Bank::new_with_paths(&genesis_config, account_paths, &[]); - bank.epoch_schedule().clone() + *bank.epoch_schedule() } fn frozen_bank_slots(bank_forks: &BankForks) -> Vec { diff --git a/ledger/src/entry.rs b/ledger/src/entry.rs index 81c09cad5d0967..21bb6cfb30b26b 100644 --- a/ledger/src/entry.rs +++ b/ledger/src/entry.rs @@ -542,7 +542,7 @@ mod tests { let tx1 = system_transaction::transfer(&keypair, &keypair.pubkey(), 1, zero); // Verify entry with 2 transctions - let mut e0 = vec![Entry::new(&zero, 0, vec![tx0.clone(), tx1.clone()])]; + let mut e0 = vec![Entry::new(&zero, 0, vec![tx0, tx1])]; assert!(e0.verify(&zero)); // Clear signature of the first transaction, see that it does not verify @@ -598,7 +598,7 @@ mod tests { let tx0 = create_sample_timestamp(&keypair, zero); let entry0 = next_entry(&zero, 1, vec![tx0.clone()]); assert_eq!(entry0.num_hashes, 1); - assert_eq!(entry0.hash, next_hash(&zero, 1, &vec![tx0])); + assert_eq!(entry0.hash, next_hash(&zero, 1, &[tx0])); } #[test] @@ -707,7 +707,7 @@ mod tests { assert!(tx_and_no_hash_tick.verify_tick_hash_count(&mut tick_hash_count, 0)); assert_eq!(tick_hash_count, 0); - let single_tick = vec![full_tick_entry.clone()]; + let single_tick = vec![full_tick_entry]; assert!(single_tick.verify_tick_hash_count(&mut tick_hash_count, hashes_per_tick)); assert_eq!(tick_hash_count, 0); assert!(!single_tick.verify_tick_hash_count(&mut tick_hash_count, hashes_per_tick - 1)); @@ -718,7 +718,7 @@ mod tests { assert!(ticks_and_txs.verify_tick_hash_count(&mut tick_hash_count, hashes_per_tick)); assert_eq!(tick_hash_count, 0); - let partial_tick = vec![partial_tick_entry.clone()]; + let partial_tick = vec![partial_tick_entry]; assert!(!partial_tick.verify_tick_hash_count(&mut tick_hash_count, hashes_per_tick)); assert_eq!(tick_hash_count, hashes_per_tick - 1); tick_hash_count = 0; diff --git a/ledger/src/hardened_unpack.rs b/ledger/src/hardened_unpack.rs index 7d1a41aa17d207..997e02707f41b8 100644 --- a/ledger/src/hardened_unpack.rs +++ b/ledger/src/hardened_unpack.rs @@ -383,7 +383,7 @@ mod tests { let mut archive = Builder::new(Vec::new()); archive.append(&header, data).unwrap(); let result = finalize_and_unpack_snapshot(archive); - assert_matches!(result, Err(UnpackError::Archive(ref message)) if message.to_string() == *"invalid path found: \"foo/../../../dangerous\""); + assert_matches!(result, Err(UnpackError::Archive(ref message)) if message == "invalid path found: \"foo/../../../dangerous\""); } fn with_archive_unpack_snapshot_invalid_path(path: &str) -> Result<()> { @@ -406,7 +406,7 @@ mod tests { archive.append(&header, data).unwrap(); with_finalize_and_unpack(archive, |unpacking_archive, path| { for entry in unpacking_archive.entries()? { - if entry?.unpack_in(path)? == false { + if !entry?.unpack_in(path)? { return Err(UnpackError::Archive("failed!".to_string())); } else if !path.join(path).exists() { return Err(UnpackError::Archive("not existing!".to_string())); @@ -427,7 +427,7 @@ mod tests { with_archive_unpack_snapshot_invalid_path("/etc/passwd"), Ok(()) ); - assert_matches!(with_archive_unpack_snapshot_invalid_path("../../../dangerous"), Err(UnpackError::Archive(ref message)) if message.to_string() == "failed!"); + assert_matches!(with_archive_unpack_snapshot_invalid_path("../../../dangerous"), Err(UnpackError::Archive(ref message)) if message == "failed!"); } #[test] @@ -442,14 +442,14 @@ mod tests { let mut archive = Builder::new(Vec::new()); archive.append(&header, data).unwrap(); let result = finalize_and_unpack_snapshot(archive); - assert_matches!(result, Err(UnpackError::Archive(ref message)) if message.to_string() == *"extra entry found: \"foo\""); + assert_matches!(result, Err(UnpackError::Archive(ref message)) if message == "extra entry found: \"foo\""); } #[test] fn test_archive_unpack_snapshot_too_large() { let mut header = Header::new_gnu(); header.set_path("version").unwrap(); - header.set_size(1 * 1024 * 1024 * 1024 * 1024 * 1024); + header.set_size(1024 * 1024 * 1024 * 1024 * 1024); header.set_cksum(); let data: &[u8] = &[1, 2, 3, 4]; @@ -457,13 +457,13 @@ mod tests { let mut archive = Builder::new(Vec::new()); archive.append(&header, data).unwrap(); let result = finalize_and_unpack_snapshot(archive); - assert_matches!(result, Err(UnpackError::Archive(ref message)) if message.to_string() == format!("too large archive: 1125899906842624 than limit: {}", MAX_SNAPSHOT_ARCHIVE_UNPACKED_SIZE)); + assert_matches!(result, Err(UnpackError::Archive(ref message)) if message == &format!("too large archive: 1125899906842624 than limit: {}", MAX_SNAPSHOT_ARCHIVE_UNPACKED_SIZE)); } #[test] fn test_archive_unpack_snapshot_bad_unpack() { let result = check_unpack_result(false, "abc".to_string()); - assert_matches!(result, Err(UnpackError::Archive(ref message)) if message.to_string() == *"failed to unpack: \"abc\""); + assert_matches!(result, Err(UnpackError::Archive(ref message)) if message == "failed to unpack: \"abc\""); } #[test] @@ -473,7 +473,7 @@ mod tests { let result = checked_total_size_sum(u64::max_value() - 2, 2, MAX_SNAPSHOT_ARCHIVE_UNPACKED_SIZE); - assert_matches!(result, Err(UnpackError::Archive(ref message)) if message.to_string() == format!("too large archive: 18446744073709551615 than limit: {}", MAX_SNAPSHOT_ARCHIVE_UNPACKED_SIZE)); + assert_matches!(result, Err(UnpackError::Archive(ref message)) if message == &format!("too large archive: 18446744073709551615 than limit: {}", MAX_SNAPSHOT_ARCHIVE_UNPACKED_SIZE)); } #[test] @@ -483,6 +483,6 @@ mod tests { let result = checked_total_count_increment(999_999_999_999, MAX_SNAPSHOT_ARCHIVE_UNPACKED_COUNT); - assert_matches!(result, Err(UnpackError::Archive(ref message)) if message.to_string() == *"too many files in snapshot: 1000000000000"); + assert_matches!(result, Err(UnpackError::Archive(ref message)) if message == "too many files in snapshot: 1000000000000"); } } diff --git a/ledger/src/leader_schedule_cache.rs b/ledger/src/leader_schedule_cache.rs index 6b7f5ba6f35f40..104f890379e1c9 100644 --- a/ledger/src/leader_schedule_cache.rs +++ b/ledger/src/leader_schedule_cache.rs @@ -400,11 +400,11 @@ mod tests { ); assert_eq!( cache.next_leader_slot(&pubkey, 0, &bank, None, std::u64::MAX), - Some((1, 863999)) + Some((1, 863_999)) ); assert_eq!( cache.next_leader_slot(&pubkey, 1, &bank, None, std::u64::MAX), - Some((2, 863999)) + Some((2, 863_999)) ); assert_eq!( cache.next_leader_slot( diff --git a/ledger/src/next_slots_iterator.rs b/ledger/src/next_slots_iterator.rs index 530ce53454caaa..945cdfab337201 100644 --- a/ledger/src/next_slots_iterator.rs +++ b/ledger/src/next_slots_iterator.rs @@ -91,21 +91,18 @@ mod tests { // Trying to get an iterator on any slot on the root fork should succeed let result: HashSet<_> = NextSlotsIterator::new(0, &blockstore) - .into_iter() .map(|(slot, _)| slot) .collect(); let expected = vec![0, 1, 2, 3, 4].into_iter().collect(); assert_eq!(result, expected); let result: HashSet<_> = NextSlotsIterator::new(2, &blockstore) - .into_iter() .map(|(slot, _)| slot) .collect(); let expected = vec![2, 3].into_iter().collect(); assert_eq!(result, expected); let result: HashSet<_> = NextSlotsIterator::new(4, &blockstore) - .into_iter() .map(|(slot, _)| slot) .collect(); let expected = vec![4].into_iter().collect(); diff --git a/ledger/src/rooted_slot_iterator.rs b/ledger/src/rooted_slot_iterator.rs index 3b95eece55b380..202a1b8b67f947 100644 --- a/ledger/src/rooted_slot_iterator.rs +++ b/ledger/src/rooted_slot_iterator.rs @@ -139,7 +139,6 @@ mod tests { // Trying to get an iterator on any slot on the root fork should succeed let result: Vec<_> = RootedSlotIterator::new(3, &blockstore) .unwrap() - .into_iter() .map(|(slot, _)| slot) .collect(); let expected = vec![3]; @@ -147,7 +146,6 @@ mod tests { let result: Vec<_> = RootedSlotIterator::new(0, &blockstore) .unwrap() - .into_iter() .map(|(slot, _)| slot) .collect(); let expected = vec![0, 1, 2, 3]; @@ -207,7 +205,6 @@ mod tests { // should not return a SlotMeta let result: Vec<_> = RootedSlotIterator::new(3, &blockstore) .unwrap() - .into_iter() .map(|(slot, meta)| (slot, meta.is_some())) .collect(); let expected = vec![(3, true), (10, false)]; @@ -221,7 +218,6 @@ mod tests { let result: Vec<_> = RootedSlotIterator::new(0, &blockstore) .unwrap() - .into_iter() .map(|(slot, meta)| (slot, meta.is_some())) .collect(); let expected = vec![ diff --git a/ledger/src/shred.rs b/ledger/src/shred.rs index 0895568623d55f..ddd37544381c28 100644 --- a/ledger/src/shred.rs +++ b/ledger/src/shred.rs @@ -961,7 +961,7 @@ pub mod tests { #[test] fn test_data_shredder() { let keypair = Arc::new(Keypair::new()); - let slot = 0x123456789abcdef0; + let slot = 0x1234_5678_9abc_def0; // Test that parent cannot be > current slot assert_matches!( @@ -1057,7 +1057,7 @@ pub mod tests { let slot = 1; let parent_slot = 0; - let shredder = Shredder::new(slot, parent_slot, 0.0, keypair.clone(), 0, 0) + let shredder = Shredder::new(slot, parent_slot, 0.0, keypair, 0, 0) .expect("Failed in creating shredder"); let entries: Vec<_> = (0..5) @@ -1083,7 +1083,7 @@ pub mod tests { let slot = 1; let parent_slot = 0; - let shredder = Shredder::new(slot, parent_slot, 0.0, keypair.clone(), 5, 0) + let shredder = Shredder::new(slot, parent_slot, 0.0, keypair, 5, 0) .expect("Failed in creating shredder"); let entries: Vec<_> = (0..5) @@ -1113,7 +1113,7 @@ pub mod tests { let slot = 1; let parent_slot = 0; - let shredder = Shredder::new(slot, parent_slot, 0.0, keypair.clone(), u8::max_value(), 0) + let shredder = Shredder::new(slot, parent_slot, 0.0, keypair, u8::max_value(), 0) .expect("Failed in creating shredder"); let entries: Vec<_> = (0..5) @@ -1147,14 +1147,14 @@ pub mod tests { fn test_data_and_code_shredder() { let keypair = Arc::new(Keypair::new()); - let slot = 0x123456789abcdef0; + let slot = 0x1234_5678_9abc_def0; // Test that FEC rate cannot be > 1.0 assert_matches!( Shredder::new(slot, slot - 5, 1.001, keypair.clone(), 0, 0), Err(ShredError::InvalidFecRate(_)) ); - let shredder = Shredder::new(0x123456789abcdef0, slot - 5, 1.0, keypair.clone(), 0, 0) + let shredder = Shredder::new(0x1234_5678_9abc_def0, slot - 5, 1.0, keypair.clone(), 0, 0) .expect("Failed in creating shredder"); // Create enough entries to make > 1 shred @@ -1192,7 +1192,7 @@ pub mod tests { #[test] fn test_recovery_and_reassembly() { let keypair = Arc::new(Keypair::new()); - let slot = 0x123456789abcdef0; + let slot = 0x1234_5678_9abc_def0; let shredder = Shredder::new(slot, slot - 5, 1.0, keypair.clone(), 0, 0) .expect("Failed in creating shredder"); @@ -1554,12 +1554,10 @@ pub mod tests { assert!(data_shreds.len() > MAX_DATA_SHREDS_PER_FEC_BLOCK as usize); - (1..=MAX_DATA_SHREDS_PER_FEC_BLOCK as usize) - .into_iter() - .for_each(|count| { - let coding_shreds = shredder.data_shreds_to_coding_shreds(&data_shreds[..count]); - assert_eq!(coding_shreds.len(), count); - }); + (1..=MAX_DATA_SHREDS_PER_FEC_BLOCK as usize).for_each(|count| { + let coding_shreds = shredder.data_shreds_to_coding_shreds(&data_shreds[..count]); + assert_eq!(coding_shreds.len(), count); + }); let coding_shreds = shredder.data_shreds_to_coding_shreds( &data_shreds[..MAX_DATA_SHREDS_PER_FEC_BLOCK as usize + 1], diff --git a/ledger/src/sigverify_shreds.rs b/ledger/src/sigverify_shreds.rs index 7753054fe74b6a..1cfa08f2166b44 100644 --- a/ledger/src/sigverify_shreds.rs +++ b/ledger/src/sigverify_shreds.rs @@ -452,7 +452,7 @@ pub mod tests { fn test_sigverify_shred_cpu() { solana_logger::setup(); let mut packet = Packet::default(); - let slot = 0xdeadc0de; + let slot = 0xdead_c0de; let mut shred = Shred::new_from_data( slot, 0xc0de, @@ -495,7 +495,7 @@ pub mod tests { fn test_sigverify_shreds_cpu() { solana_logger::setup(); let mut batch = [Packets::default()]; - let slot = 0xdeadc0de; + let slot = 0xdead_c0de; let mut shred = Shred::new_from_data( slot, 0xc0de, @@ -547,7 +547,7 @@ pub mod tests { let recycler_cache = RecyclerCache::default(); let mut batch = [Packets::default()]; - let slot = 0xdeadc0de; + let slot = 0xdead_c0de; let mut shred = Shred::new_from_data( slot, 0xc0de, @@ -610,7 +610,7 @@ pub mod tests { let mut packets = Packets::default(); let num_packets = 32; let num_batches = 100; - let slot = 0xdeadc0de; + let slot = 0xdead_c0de; packets.packets.resize(num_packets, Packet::default()); for (i, p) in packets.packets.iter_mut().enumerate() { let shred = Shred::new_from_data( @@ -654,7 +654,7 @@ pub mod tests { solana_logger::setup(); let mut batch = [Packets::default()]; - let slot = 0xdeadc0de; + let slot = 0xdead_c0de; let keypair = Keypair::new(); let shred = Shred::new_from_data( slot, diff --git a/ledger/tests/shred.rs b/ledger/tests/shred.rs index 4168fda76f141e..61e848f98a7baf 100644 --- a/ledger/tests/shred.rs +++ b/ledger/tests/shred.rs @@ -10,7 +10,7 @@ use std::sync::Arc; #[test] fn test_multi_fec_block_coding() { let keypair = Arc::new(Keypair::new()); - let slot = 0x123456789abcdef0; + let slot = 0x1234_5678_9abc_def0; let shredder = Shredder::new(slot, slot - 5, 1.0, keypair.clone(), 0, 0) .expect("Failed in creating shredder"); diff --git a/local-cluster/tests/local_cluster.rs b/local-cluster/tests/local_cluster.rs index b814d96aa37298..9ef8e3f3bdb46b 100644 --- a/local-cluster/tests/local_cluster.rs +++ b/local-cluster/tests/local_cluster.rs @@ -52,7 +52,7 @@ fn test_ledger_cleanup_service() { cluster_lamports: 10_000, poh_config: PohConfig::new_sleep(Duration::from_millis(50)), node_stakes: vec![100; num_nodes], - validator_configs: vec![validator_config.clone(); num_nodes], + validator_configs: vec![validator_config; num_nodes], ..ClusterConfig::default() }; let mut cluster = LocalCluster::new(&config); @@ -67,7 +67,7 @@ fn test_ledger_cleanup_service() { ); cluster.close_preserve_ledgers(); //check everyone's ledgers and make sure only ~100 slots are stored - for (_, info) in &cluster.validators { + for info in cluster.validators.values() { let mut slots = 0; let blockstore = Blockstore::open(&info.info.ledger_path).unwrap(); blockstore @@ -166,7 +166,7 @@ fn test_validator_exit_2() { let config = ClusterConfig { cluster_lamports: 10_000, node_stakes: vec![100; num_nodes], - validator_configs: vec![validator_config.clone(); num_nodes], + validator_configs: vec![validator_config; num_nodes], ..ClusterConfig::default() }; let local = LocalCluster::new(&config); @@ -185,7 +185,7 @@ fn test_leader_failure_4() { let config = ClusterConfig { cluster_lamports: 10_000, node_stakes: vec![100; 4], - validator_configs: vec![validator_config.clone(); num_nodes], + validator_configs: vec![validator_config; num_nodes], ..ClusterConfig::default() }; let local = LocalCluster::new(&config); @@ -206,6 +206,7 @@ fn test_leader_failure_4() { /// whether or not it should be killed during the partition /// * `leader_schedule` - An option that specifies whether the cluster should /// run with a fixed, predetermined leader schedule +#[allow(clippy::cognitive_complexity)] fn run_cluster_partition( partitions: &[&[(usize, bool)]], leader_schedule: Option<(LeaderSchedule, Vec>)>, @@ -255,7 +256,7 @@ fn run_cluster_partition( let config = ClusterConfig { cluster_lamports, node_stakes, - validator_configs: vec![validator_config.clone(); num_nodes], + validator_configs: vec![validator_config; num_nodes], validator_keys: Some(validator_keys), ..ClusterConfig::default() }; @@ -336,7 +337,7 @@ fn run_cluster_partition( } } - assert!(alive_node_contact_infos.len() > 0); + assert_eq!(alive_node_contact_infos.is_empty(), false); info!("PARTITION_TEST discovering nodes"); let cluster_nodes = discover_cluster( &alive_node_contact_infos[0].gossip, @@ -428,7 +429,7 @@ fn test_two_unbalanced_stakes() { let mut cluster = LocalCluster::new(&ClusterConfig { node_stakes: vec![999_990, 3], cluster_lamports: 1_000_000, - validator_configs: vec![validator_config.clone(); 2], + validator_configs: vec![validator_config; 2], ticks_per_slot: num_ticks_per_slot, slots_per_epoch: num_slots_per_epoch, stakers_slot_offset: num_slots_per_epoch, @@ -706,7 +707,7 @@ fn test_consistency_halt() { let config = ClusterConfig { node_stakes: vec![validator_stake], cluster_lamports: 100_000, - validator_configs: vec![leader_snapshot_test_config.validator_config.clone()], + validator_configs: vec![leader_snapshot_test_config.validator_config], ..ClusterConfig::default() }; @@ -848,7 +849,7 @@ fn test_snapshot_restart_tower() { let config = ClusterConfig { node_stakes: vec![10000, 10], - cluster_lamports: 100000, + cluster_lamports: 100_000, validator_configs: vec![ leader_snapshot_test_config.validator_config.clone(), validator_snapshot_test_config.validator_config.clone(), @@ -924,7 +925,7 @@ fn test_snapshots_blockstore_floor() { let config = ClusterConfig { node_stakes: vec![10000], - cluster_lamports: 100000, + cluster_lamports: 100_000, validator_configs: vec![leader_snapshot_test_config.validator_config.clone()], ..ClusterConfig::default() }; @@ -1023,7 +1024,7 @@ fn test_snapshots_restart_validity() { let config = ClusterConfig { node_stakes: vec![10000], - cluster_lamports: 100000, + cluster_lamports: 100_000, validator_configs: vec![snapshot_test_config.validator_config.clone()], ..ClusterConfig::default() }; @@ -1094,7 +1095,7 @@ fn test_faulty_node(faulty_node_type: BroadcastStageType) { let num_nodes = 2; let validator_config = ValidatorConfig::default(); let mut error_validator_config = ValidatorConfig::default(); - error_validator_config.broadcast_stage_type = faulty_node_type.clone(); + error_validator_config.broadcast_stage_type = faulty_node_type; let mut validator_configs = vec![validator_config; num_nodes - 1]; // Push a faulty_bootstrap = vec![error_validator_config]; validator_configs.insert(0, error_validator_config); @@ -1103,7 +1104,7 @@ fn test_faulty_node(faulty_node_type: BroadcastStageType) { let cluster_config = ClusterConfig { cluster_lamports: 10_000, node_stakes, - validator_configs: validator_configs, + validator_configs, slots_per_epoch: MINIMUM_SLOTS_PER_EPOCH * 2 as u64, stakers_slot_offset: MINIMUM_SLOTS_PER_EPOCH * 2 as u64, ..ClusterConfig::default() @@ -1131,7 +1132,7 @@ fn test_no_voting() { let config = ClusterConfig { cluster_lamports: 10_000, node_stakes: vec![100], - validator_configs: vec![validator_config.clone()], + validator_configs: vec![validator_config], ..ClusterConfig::default() }; let mut cluster = LocalCluster::new(&config); diff --git a/merkle-tree/src/merkle_tree.rs b/merkle-tree/src/merkle_tree.rs index 204bd88f7a3188..7b13b2aa91909c 100644 --- a/merkle-tree/src/merkle_tree.rs +++ b/merkle-tree/src/merkle_tree.rs @@ -183,13 +183,12 @@ impl MerkleTree { #[cfg(test)] mod tests { use super::*; - use hex; - const TEST: &'static [&'static [u8]] = &[ + const TEST: &[&[u8]] = &[ b"my", b"very", b"eager", b"mother", b"just", b"served", b"us", b"nine", b"pizzas", b"make", b"prime", ]; - const BAD: &'static [&'static [u8]] = &[b"bad", b"missing", b"false"]; + const BAD: &[&[u8]] = &[b"bad", b"missing", b"false"]; #[test] fn test_tree_from_empty() { diff --git a/metrics/src/metrics.rs b/metrics/src/metrics.rs index 5de46e01a7fb58..c77f56c7a5abb9 100644 --- a/metrics/src/metrics.rs +++ b/metrics/src/metrics.rs @@ -623,7 +623,7 @@ mod test { fn test_flush_before_drop() { let writer = Arc::new(MockMetricsWriter::new()); { - let agent = MetricsAgent::new(writer.clone(), Duration::from_secs(9999999), 1000); + let agent = MetricsAgent::new(writer.clone(), Duration::from_secs(9_999_999), 1000); agent.submit(DataPoint::new("point 1"), Level::Info); } diff --git a/perf/src/packet.rs b/perf/src/packet.rs index ced9ca39f8e77d..d62e2747820d5b 100644 --- a/perf/src/packet.rs +++ b/perf/src/packet.rs @@ -117,15 +117,17 @@ mod tests { let keypair = Keypair::new(); let hash = Hash::new(&[1; 32]); let tx = system_transaction::transfer(&keypair, &keypair.pubkey(), 1, hash); - let rv = to_packets(&vec![tx.clone(); 1]); + let rv = to_packets(&[tx.clone(); 1]); assert_eq!(rv.len(), 1); assert_eq!(rv[0].packets.len(), 1); + #[allow(clippy::useless_vec)] let rv = to_packets(&vec![tx.clone(); NUM_PACKETS]); assert_eq!(rv.len(), 1); assert_eq!(rv[0].packets.len(), NUM_PACKETS); - let rv = to_packets(&vec![tx.clone(); NUM_PACKETS + 1]); + #[allow(clippy::useless_vec)] + let rv = to_packets(&vec![tx; NUM_PACKETS + 1]); assert_eq!(rv.len(), 2); assert_eq!(rv[0].packets.len(), NUM_PACKETS); assert_eq!(rv[1].packets.len(), 1); diff --git a/perf/src/sigverify.rs b/perf/src/sigverify.rs index 0de8aa215a8dfe..9b797d3bde5829 100644 --- a/perf/src/sigverify.rs +++ b/perf/src/sigverify.rs @@ -403,7 +403,7 @@ pub fn make_packet_from_transaction(tx: Transaction) -> Packet { let mut packet = Packet::default(); packet.meta.size = tx_bytes.len(); packet.data[..packet.meta.size].copy_from_slice(&tx_bytes); - return packet; + packet } #[cfg(test)] @@ -519,7 +519,7 @@ mod tests { #[test] fn test_small_packet() { let tx = test_tx(); - let mut packet = sigverify::make_packet_from_transaction(tx.clone()); + let mut packet = sigverify::make_packet_from_transaction(tx); packet.data[0] = 0xff; packet.data[1] = 0xff; @@ -532,7 +532,7 @@ mod tests { #[test] fn test_large_sig_len() { let tx = test_tx(); - let mut packet = sigverify::make_packet_from_transaction(tx.clone()); + let mut packet = sigverify::make_packet_from_transaction(tx); // Make the signatures len huge packet.data[0] = 0x7f; @@ -544,7 +544,7 @@ mod tests { #[test] fn test_really_large_sig_len() { let tx = test_tx(); - let mut packet = sigverify::make_packet_from_transaction(tx.clone()); + let mut packet = sigverify::make_packet_from_transaction(tx); // Make the signatures len huge packet.data[0] = 0xff; @@ -559,7 +559,7 @@ mod tests { #[test] fn test_invalid_pubkey_len() { let tx = test_tx(); - let mut packet = sigverify::make_packet_from_transaction(tx.clone()); + let mut packet = sigverify::make_packet_from_transaction(tx); let res = sigverify::do_get_packet_offsets(&packet, 0); @@ -584,7 +584,7 @@ mod tests { }; let mut tx = Transaction::new_unsigned(message); tx.signatures = vec![Signature::default()]; - let packet = sigverify::make_packet_from_transaction(tx.clone()); + let packet = sigverify::make_packet_from_transaction(tx); let res = sigverify::do_get_packet_offsets(&packet, 0); assert_eq!(res, Err(PacketError::PayerNotWritable)); @@ -692,7 +692,7 @@ mod tests { #[test] fn test_verify_tampered_sig_len() { - let mut tx = test_tx().clone(); + let mut tx = test_tx(); // pretend malicious leader dropped a signature... tx.signatures.pop(); let packet = sigverify::make_packet_from_transaction(tx); diff --git a/programs/bpf_loader/src/lib.rs b/programs/bpf_loader/src/lib.rs index d1273a8f2b448e..3533368ad1c066 100644 --- a/programs/bpf_loader/src/lib.rs +++ b/programs/bpf_loader/src/lib.rs @@ -319,7 +319,7 @@ mod tests { Err(InstructionError::NotEnoughAccountKeys), process_instruction( &bpf_loader::id(), - &vec![], + &[], &instruction_data, &mut MockInvokeContext::default() ) @@ -385,7 +385,7 @@ mod tests { Err(InstructionError::NotEnoughAccountKeys), process_instruction( &bpf_loader::id(), - &vec![], + &[], &instruction_data, &mut MockInvokeContext::default() ) @@ -453,8 +453,8 @@ mod tests { Err(InstructionError::NotEnoughAccountKeys), process_instruction( &bpf_loader::id(), - &vec![], - &vec![], + &[], + &[], &mut MockInvokeContext::default() ) ); @@ -465,7 +465,7 @@ mod tests { process_instruction( &bpf_loader::id(), &keyed_accounts, - &vec![], + &[], &mut MockInvokeContext::default() ) ); @@ -477,7 +477,7 @@ mod tests { process_instruction( &bpf_loader::id(), &keyed_accounts, - &vec![], + &[], &mut MockInvokeContext::default() ) ); @@ -491,7 +491,7 @@ mod tests { process_instruction( &bpf_loader::id(), &keyed_accounts, - &vec![], + &[], &mut MockInvokeContext::default() ) ); @@ -507,7 +507,7 @@ mod tests { process_instruction( &bpf_loader::id(), &keyed_accounts, - &vec![], + &[], &mut MockInvokeContext::default() ) ); @@ -568,7 +568,7 @@ mod tests { let _result = process_instruction( &bpf_loader::id(), &keyed_accounts, - &vec![], + &[], &mut MockInvokeContext::default(), ); }, diff --git a/programs/bpf_loader/src/syscalls.rs b/programs/bpf_loader/src/syscalls.rs index 467dcc47a781df..3c010fe3e99a70 100644 --- a/programs/bpf_loader/src/syscalls.rs +++ b/programs/bpf_loader/src/syscalls.rs @@ -775,9 +775,10 @@ mod tests { (true, START + LENGTH / 2, LENGTH / 2, addr + LENGTH / 2), ]; for (ok, start, length, value) in cases { - match ok { - true => assert_eq!(translate!(start, length, ®ions).unwrap(), value), - false => assert!(translate!(start, length, ®ions).is_err()), + if ok { + assert_eq!(translate!(start, length, ®ions).unwrap(), value) + } else { + assert!(translate!(start, length, ®ions).is_err()) } } } diff --git a/programs/btc_spv/src/utils.rs b/programs/btc_spv/src/utils.rs index 31545c6dc4bb59..7e6557c3df89f8 100644 --- a/programs/btc_spv/src/utils.rs +++ b/programs/btc_spv/src/utils.rs @@ -106,7 +106,7 @@ mod test { assert_eq!(106, value_a); assert_eq!(550, value_b); - assert_eq!(998000, value_c); + assert_eq!(998_000, value_c); } #[test] diff --git a/programs/config/src/config_processor.rs b/programs/config/src/config_processor.rs index b3f409cffe68d7..f65145193285db 100644 --- a/programs/config/src/config_processor.rs +++ b/programs/config/src/config_processor.rs @@ -119,7 +119,7 @@ mod tests { } impl Default for MyConfig { fn default() -> Self { - Self { item: 123456789 } + Self { item: 123_456_789 } } } impl MyConfig { @@ -172,7 +172,7 @@ mod tests { fn test_process_create_ok() { solana_logger::setup(); let keys = vec![]; - let (_, config_account) = create_config_account(keys.clone()); + let (_, config_account) = create_config_account(keys); assert_eq!( Some(MyConfig::default()), deserialize(get_config_data(&config_account.borrow().data).unwrap()).ok() @@ -187,7 +187,7 @@ mod tests { let config_pubkey = config_keypair.pubkey(); let my_config = MyConfig::new(42); - let instruction = config_instruction::store(&config_pubkey, true, keys.clone(), &my_config); + let instruction = config_instruction::store(&config_pubkey, true, keys, &my_config); let accounts = vec![(&config_pubkey, true, &config_account)]; let keyed_accounts = create_keyed_is_signer_accounts(&accounts); assert_eq!( @@ -208,8 +208,7 @@ mod tests { let config_pubkey = config_keypair.pubkey(); let my_config = MyConfig::new(42); - let mut instruction = - config_instruction::store(&config_pubkey, true, keys.clone(), &my_config); + let mut instruction = config_instruction::store(&config_pubkey, true, keys, &my_config); instruction.data = vec![0; 123]; // <-- Replace data with a vector that's too large let accounts = vec![(&config_pubkey, true, &config_account)]; let keyed_accounts = create_keyed_is_signer_accounts(&accounts); @@ -223,7 +222,7 @@ mod tests { fn test_process_store_fail_account0_not_signer() { solana_logger::setup(); let keys = vec![]; - let (config_keypair, config_account) = create_config_account(keys.clone()); + let (config_keypair, config_account) = create_config_account(keys); let config_pubkey = config_keypair.pubkey(); let my_config = MyConfig::new(42); @@ -283,8 +282,7 @@ mod tests { let config_pubkey = config_keypair.pubkey(); let my_config = MyConfig::new(42); - let instruction = - config_instruction::store(&config_pubkey, false, keys.clone(), &my_config); + let instruction = config_instruction::store(&config_pubkey, false, keys, &my_config); let signer0_account = RefCell::new(Account::default()); let accounts = vec![(&signer0_pubkey, true, &signer0_account)]; let keyed_accounts = create_keyed_is_signer_accounts(&accounts); @@ -306,7 +304,7 @@ mod tests { let config_pubkey = config_keypair.pubkey(); let my_config = MyConfig::new(42); - let instruction = config_instruction::store(&config_pubkey, true, keys.clone(), &my_config); + let instruction = config_instruction::store(&config_pubkey, true, keys, &my_config); // Config-data pubkey doesn't match signer let accounts = vec![ @@ -385,8 +383,7 @@ mod tests { // Attempt update with incomplete signatures let keys = vec![(pubkey, false), (signer0_pubkey, true)]; - let instruction = - config_instruction::store(&config_pubkey, false, keys.clone(), &my_config); + let instruction = config_instruction::store(&config_pubkey, false, keys, &my_config); let accounts = vec![ (&config_pubkey, false, &config_account), (&signer0_pubkey, true, &signer0_account), @@ -404,8 +401,7 @@ mod tests { (signer0_pubkey, true), (signer2_pubkey, true), ]; - let instruction = - config_instruction::store(&config_pubkey, false, keys.clone(), &my_config); + let instruction = config_instruction::store(&config_pubkey, false, keys, &my_config); let accounts = vec![ (&config_pubkey, false, &config_account), (&signer0_pubkey, true, &signer0_account), @@ -429,7 +425,7 @@ mod tests { (signer0_pubkey, true), (signer0_pubkey, true), ]; // Dummy keys for account sizing - let (config_keypair, config_account) = create_config_account(keys.clone()); + let (config_keypair, config_account) = create_config_account(keys); let config_pubkey = config_keypair.pubkey(); let my_config = MyConfig::new(42); @@ -472,7 +468,7 @@ mod tests { // Attempt update with incomplete signatures let keys = vec![(pubkey, false), (config_keypair.pubkey(), true)]; - let instruction = config_instruction::store(&config_pubkey, true, keys.clone(), &my_config); + let instruction = config_instruction::store(&config_pubkey, true, keys, &my_config); let accounts = vec![(&config_pubkey, true, &config_account)]; let keyed_accounts = create_keyed_is_signer_accounts(&accounts); assert_eq!( diff --git a/programs/exchange/src/exchange_processor.rs b/programs/exchange/src/exchange_processor.rs index a60ddcb218d0b6..4c930f57ab82e0 100644 --- a/programs/exchange/src/exchange_processor.rs +++ b/programs/exchange/src/exchange_processor.rs @@ -497,6 +497,7 @@ mod test { use solana_sdk::system_instruction; use std::mem; + #[allow(clippy::too_many_arguments)] fn try_calc( scaler: u64, primary_tokens: u64, @@ -604,7 +605,7 @@ mod test { client .send_message(&[owner, &new], Message::new(&[instruction])) - .expect(&format!("{}:{}", line!(), file!())); + .unwrap_or_else(|_| panic!("{}:{}", line!(), file!())); new.pubkey() } @@ -613,7 +614,7 @@ mod test { let instruction = exchange_instruction::account_request(&owner.pubkey(), &new); client .send_instruction(owner, instruction) - .expect(&format!("{}:{}", line!(), file!())); + .unwrap_or_else(|_| panic!("{}:{}", line!(), file!())); new } @@ -627,7 +628,7 @@ mod test { ); client .send_instruction(owner, instruction) - .expect(&format!("{}:{}", line!(), file!())); + .unwrap_or_else(|_| panic!("{}:{}", line!(), file!())); } fn trade( @@ -655,7 +656,7 @@ mod test { ); client .send_instruction(owner, instruction) - .expect(&format!("{}:{}", line!(), file!())); + .unwrap_or_else(|_| panic!("{}:{}", line!(), file!())); (trade, src) } @@ -708,7 +709,7 @@ mod test { ); client .send_instruction(&owner, instruction) - .expect(&format!("{}:{}", line!(), file!())); + .unwrap_or_else(|_| panic!("{}:{}", line!(), file!())); let new_account_data = client.get_account_data(&new).unwrap().unwrap(); @@ -795,7 +796,7 @@ mod test { exchange_instruction::swap_request(&owner.pubkey(), &to_trade, &from_trade, &profit); client .send_instruction(&owner, instruction) - .expect(&format!("{}:{}", line!(), file!())); + .unwrap_or_else(|_| panic!("{}:{}", line!(), file!())); let to_trade_account_data = client.get_account_data(&to_trade).unwrap().unwrap(); let from_trade_account_data = client.get_account_data(&from_trade).unwrap().unwrap(); @@ -862,7 +863,7 @@ mod test { exchange_instruction::swap_request(&owner.pubkey(), &to_trade, &from_trade, &profit); client .send_instruction(&owner, instruction) - .expect(&format!("{}:{}", line!(), file!())); + .unwrap_or_else(|_| panic!("{}:{}", line!(), file!())); let new = create_token_account(&client, &owner); @@ -870,13 +871,13 @@ mod test { exchange_instruction::transfer_request(&owner.pubkey(), &new, &to_trade, Token::B, 1); client .send_instruction(&owner, instruction) - .expect(&format!("{}:{}", line!(), file!())); + .unwrap_or_else(|_| panic!("{}:{}", line!(), file!())); let instruction = exchange_instruction::transfer_request(&owner.pubkey(), &new, &from_trade, Token::A, 1); client .send_instruction(&owner, instruction) - .expect(&format!("{}:{}", line!(), file!())); + .unwrap_or_else(|_| panic!("{}:{}", line!(), file!())); let new_account_data = client.get_account_data(&new).unwrap().unwrap(); diff --git a/programs/stake/src/config.rs b/programs/stake/src/config.rs index d79b779b790950..e69b1ea8d73abf 100644 --- a/programs/stake/src/config.rs +++ b/programs/stake/src/config.rs @@ -78,10 +78,10 @@ mod tests { #[test] fn test() { - let mut account = RefCell::new(create_account(0, &Config::default())); + let account = RefCell::new(create_account(0, &Config::default())); assert_eq!(Config::from(&account.borrow()), Some(Config::default())); assert_eq!( - from_keyed_account(&KeyedAccount::new(&Pubkey::default(), false, &mut account)), + from_keyed_account(&KeyedAccount::new(&Pubkey::default(), false, &account)), Err(InstructionError::InvalidArgument) ); } diff --git a/programs/stake/src/stake_state.rs b/programs/stake/src/stake_state.rs index e29514c5a37347..31b0f9cc5aacb2 100644 --- a/programs/stake/src/stake_state.rs +++ b/programs/stake/src/stake_state.rs @@ -1044,7 +1044,6 @@ mod tests { ..Delegation::default() }, credits_observed: vote_state_credits, - ..Stake::default() } ); @@ -1092,7 +1091,6 @@ mod tests { ..Delegation::default() }, credits_observed: vote_state_credits, - ..Stake::default() } ); @@ -1150,7 +1148,7 @@ mod tests { }; // save this off so stake.config.warmup_rate changes don't break this test - let increment = (1_000 as f64 * stake.warmup_cooldown_rate) as u64; + let increment = (1_000_f64 * stake.warmup_cooldown_rate) as u64; let mut stake_history = StakeHistory::default(); // assert that this stake follows step function if there's no history @@ -1707,7 +1705,7 @@ mod tests { assert_eq!(lockup.epoch, 1); assert_eq!(lockup.custodian, custodian); } else { - assert!(false); + panic!(); } assert_eq!( @@ -1729,7 +1727,7 @@ mod tests { assert_eq!(lockup.epoch, 3); assert_eq!(lockup.custodian, custodian); } else { - assert!(false); + panic!(); } let new_custodian = Pubkey::new_rand(); @@ -1752,7 +1750,7 @@ mod tests { assert_eq!(lockup.epoch, 3); assert_eq!(lockup.custodian, new_custodian); } else { - assert!(false); + panic!(); } assert_eq!( @@ -2173,7 +2171,7 @@ mod tests { stake.credits_observed = 1; // this one should be able to collect exactly 1 (already observed one) assert_eq!( - Some((0, stake.delegation.stake * 1, 2)), + Some((0, stake.delegation.stake, 2)), stake.calculate_rewards(1.0, &vote_state, None) ); @@ -2183,7 +2181,7 @@ mod tests { stake.credits_observed = 2; // this one should be able to collect the one just added assert_eq!( - Some((0, stake.delegation.stake * 1, 3)), + Some((0, stake.delegation.stake, 3)), stake.calculate_rewards(1.0, &vote_state, None) ); @@ -2202,8 +2200,8 @@ mod tests { Some(( 0, stake.delegation.stake * 2 // epoch 0 - + stake.delegation.stake * 1 // epoch 1 - + stake.delegation.stake * 1, // epoch 2 + + stake.delegation.stake // epoch 1 + + stake.delegation.stake, // epoch 2 4 )), stake.calculate_rewards(1.0, &vote_state, None) @@ -2278,7 +2276,7 @@ mod tests { assert_eq!(authorized.staker, stake_pubkey0); assert_eq!(authorized.withdrawer, stake_pubkey0); } else { - assert!(false); + panic!(); } // A second authorization signed by the stake_keyed_account should fail diff --git a/programs/vest/src/vest_processor.rs b/programs/vest/src/vest_processor.rs index 6dba509785b350..6f79d8582cb352 100644 --- a/programs/vest/src/vest_processor.rs +++ b/programs/vest/src/vest_processor.rs @@ -280,7 +280,7 @@ mod tests { assert_eq!( verify_signed_account(&keyed_account, &date_pubkey).unwrap_err(), - InstructionError::MissingRequiredSignature.into() + InstructionError::MissingRequiredSignature ); } diff --git a/programs/vote/src/vote_state/mod.rs b/programs/vote/src/vote_state/mod.rs index db31403533058f..e9e960d2a72b13 100644 --- a/programs/vote/src/vote_state/mod.rs +++ b/programs/vote/src/vote_state/mod.rs @@ -1353,13 +1353,11 @@ mod tests { let mut vote_state_b = VoteState::new_for_test(&account_b); // process some votes on account a - (0..5) - .into_iter() - .for_each(|i| vote_state_a.process_slot_vote_unchecked(i as u64)); + (0..5).for_each(|i| vote_state_a.process_slot_vote_unchecked(i as u64)); assert_ne!(recent_votes(&vote_state_a), recent_votes(&vote_state_b)); // as long as b has missed less than "NUM_RECENT" votes both accounts should be in sync - let slots = (0u64..MAX_RECENT_VOTES as u64).into_iter().collect(); + let slots = (0u64..MAX_RECENT_VOTES as u64).collect(); let vote = Vote::new(slots, Hash::default()); let slot_hashes: Vec<_> = vote.slots.iter().rev().map(|x| (*x, vote.hash)).collect(); @@ -1389,7 +1387,7 @@ mod tests { let vote = Vote::new(vec![0], Hash::default()); assert_eq!( - vote_state.check_slots_are_valid(&vote, &vec![]), + vote_state.check_slots_are_valid(&vote, &[]), Err(VoteError::VoteTooOld) ); } @@ -1642,7 +1640,7 @@ mod tests { #[test] fn test_vote_process_timestamp() { - let (slot, timestamp) = (15, 1575412285); + let (slot, timestamp) = (15, 1_575_412_285); let mut vote_state = VoteState::default(); vote_state.last_timestamp = BlockTimestamp { slot, timestamp }; @@ -1767,13 +1765,13 @@ mod tests { let new_voter = Pubkey::new_rand(); // Set a new authorized voter vote_state - .set_new_authorized_voter(&new_voter, 0, 0 + epoch_offset, |_| Ok(())) + .set_new_authorized_voter(&new_voter, 0, epoch_offset, |_| Ok(())) .unwrap(); assert_eq!(vote_state.prior_voters.idx, 0); assert_eq!( vote_state.prior_voters.last(), - Some(&(original_voter, 0, 0 + epoch_offset)) + Some(&(original_voter, 0, epoch_offset)) ); // Trying to set authorized voter for same epoch again should fail diff --git a/remote-wallet/src/ledger.rs b/remote-wallet/src/ledger.rs index de8c5ceb66a587..af38463fa6eb26 100644 --- a/remote-wallet/src/ledger.rs +++ b/remote-wallet/src/ledger.rs @@ -575,7 +575,7 @@ mod tests { #[test] fn test_parse_status() { - assert_eq!(LedgerWallet::parse_status(APDU_SUCCESS_CODE).unwrap(), ()); + LedgerWallet::parse_status(APDU_SUCCESS_CODE).expect("unexpected result"); if let RemoteWalletError::LedgerError(err) = LedgerWallet::parse_status(0x6985).unwrap_err() { assert_eq!(err, LedgerError::UserCancel); diff --git a/remote-wallet/src/remote_wallet.rs b/remote-wallet/src/remote_wallet.rs index 5105a79056b09b..5ec212add2c764 100644 --- a/remote-wallet/src/remote_wallet.rs +++ b/remote-wallet/src/remote_wallet.rs @@ -535,7 +535,7 @@ mod tests { manufacturer: "Ledger".to_string(), model: "Nano S".to_string(), serial: "0001".to_string(), - pubkey: pubkey.clone(), + pubkey, error: None, }; let mut test_info = RemoteWalletInfo::default(); diff --git a/runtime/src/accounts.rs b/runtime/src/accounts.rs index 6b95c9822b5923..95e83dc5ad07c2 100644 --- a/runtime/src/accounts.rs +++ b/runtime/src/accounts.rs @@ -819,7 +819,7 @@ mod tests { fn load_accounts_with_fee_and_rent( tx: Transaction, - ka: &Vec<(Pubkey, Account)>, + ka: &[(Pubkey, Account)], fee_calculator: &FeeCalculator, rent_collector: &RentCollector, error_counters: &mut ErrorCounters, @@ -832,7 +832,7 @@ mod tests { } let ancestors = vec![(0, 0)].into_iter().collect(); - let res = accounts.load_accounts( + accounts.load_accounts( &ancestors, &[tx], None, @@ -840,13 +840,12 @@ mod tests { &hash_queue, error_counters, rent_collector, - ); - res + ) } fn load_accounts_with_fee( tx: Transaction, - ka: &Vec<(Pubkey, Account)>, + ka: &[(Pubkey, Account)], fee_calculator: &FeeCalculator, error_counters: &mut ErrorCounters, ) -> Vec<(Result, Option)> { @@ -856,7 +855,7 @@ mod tests { fn load_accounts( tx: Transaction, - ka: &Vec<(Pubkey, Account)>, + ka: &[(Pubkey, Account)], error_counters: &mut ErrorCounters, ) -> Vec<(Result, Option)> { let fee_calculator = FeeCalculator::default(); @@ -1090,7 +1089,7 @@ mod tests { // Fee leaves non-zero, but sub-min_balance balance fails accounts[0].1.lamports = 3 * min_balance / 2; let loaded_accounts = load_accounts_with_fee_and_rent( - tx.clone(), + tx, &accounts, &fee_calculator, &rent_collector, @@ -1473,7 +1472,7 @@ mod tests { accounts.bank_hash_at(1); } - fn check_accounts(accounts: &Accounts, pubkeys: &Vec, num: usize) { + fn check_accounts(accounts: &Accounts, pubkeys: &[Pubkey], num: usize) { for _ in 1..num { let idx = thread_rng().gen_range(0, num - 1); let ancestors = vec![(0, 0)].into_iter().collect(); @@ -1701,7 +1700,7 @@ mod tests { } } }); - let counter_clone = counter.clone(); + let counter_clone = counter; for _ in 0..5 { let txs = vec![readonly_tx.clone()]; let results = accounts_arc.clone().lock_accounts(&txs, None); @@ -1768,7 +1767,7 @@ mod tests { Some(HashAgeKind::Extant), ); - let transaction_accounts1 = vec![account1, account2.clone()]; + let transaction_accounts1 = vec![account1, account2]; let transaction_loaders1 = vec![]; let transaction_rent1 = 0; let loaded1 = ( @@ -1804,12 +1803,10 @@ mod tests { assert_eq!(collected_accounts.len(), 2); assert!(collected_accounts .iter() - .find(|(pubkey, _account)| *pubkey == &keypair0.pubkey()) - .is_some()); + .any(|(pubkey, _account)| *pubkey == &keypair0.pubkey())); assert!(collected_accounts .iter() - .find(|(pubkey, _account)| *pubkey == &keypair1.pubkey()) - .is_some()); + .any(|(pubkey, _account)| *pubkey == &keypair1.pubkey())); // Ensure readonly_lock reflects lock let readonly_locks = accounts.readonly_locks.read().unwrap(); diff --git a/runtime/src/accounts_db.rs b/runtime/src/accounts_db.rs index 61cf9a88fb54ed..697212c6c96c31 100644 --- a/runtime/src/accounts_db.rs +++ b/runtime/src/accounts_db.rs @@ -2390,12 +2390,12 @@ pub mod tests { } } - fn update_accounts(accounts: &AccountsDB, pubkeys: &Vec, slot: Slot, range: usize) { + fn update_accounts(accounts: &AccountsDB, pubkeys: &[Pubkey], slot: Slot, range: usize) { for _ in 1..1000 { let idx = thread_rng().gen_range(0, range); let ancestors = vec![(slot, 0)].into_iter().collect(); if let Some((mut account, _)) = accounts.load_slow(&ancestors, &pubkeys[idx]) { - account.lamports = account.lamports + 1; + account.lamports += 1; accounts.store(slot, &[(&pubkeys[idx], &account)]); if account.lamports == 0 { let ancestors = vec![(slot, 0)].into_iter().collect(); @@ -2441,9 +2441,10 @@ pub mod tests { } } + #[allow(clippy::needless_range_loop)] fn modify_accounts( accounts: &AccountsDB, - pubkeys: &Vec, + pubkeys: &[Pubkey], slot: Slot, num: usize, count: usize, @@ -2979,7 +2980,7 @@ pub mod tests { fn assert_no_stores(accounts: &AccountsDB, slot: Slot) { let stores = accounts.storage.read().unwrap(); info!("{:?}", stores.0.get(&slot)); - assert!(stores.0.get(&slot).is_none() || stores.0.get(&slot).unwrap().len() == 0); + assert!(stores.0.get(&slot).is_none() || stores.0.get(&slot).unwrap().is_empty()); } #[test] @@ -3228,8 +3229,7 @@ pub mod tests { solana_logger::setup(); with_chained_zero_lamport_accounts(|accounts, current_slot| { accounts.clean_accounts(); - let accounts = reconstruct_accounts_db_via_serialization(&accounts, current_slot); - accounts + reconstruct_accounts_db_via_serialization(&accounts, current_slot) }); } @@ -3240,8 +3240,7 @@ pub mod tests { let accounts = reconstruct_accounts_db_via_serialization(&accounts, current_slot); print_accounts("after_reconstruct", &accounts); accounts.clean_accounts(); - let accounts = reconstruct_accounts_db_via_serialization(&accounts, current_slot); - accounts + reconstruct_accounts_db_via_serialization(&accounts, current_slot) }); } @@ -3258,7 +3257,6 @@ pub mod tests { db.add_root(slot); let thread_hdls: Vec<_> = (0..num_threads) - .into_iter() .map(|_| { let db = db.clone(); std::thread::Builder::new() @@ -3271,9 +3269,11 @@ pub mod tests { let account_bal = thread_rng().gen_range(1, 99); account.lamports = account_bal; db.store(slot, &[(&pubkey, &account)]); - let (account, slot) = db.load_slow(&HashMap::new(), &pubkey).expect( - &format!("Could not fetch stored account {}, iter {}", pubkey, i), - ); + + let (account, slot) = + db.load_slow(&HashMap::new(), &pubkey).unwrap_or_else(|| { + panic!("Could not fetch stored account {}, iter {}", pubkey, i) + }); assert_eq!(slot, slot); assert_eq!(account.lamports, account_bal); i += 1; @@ -3397,7 +3397,7 @@ pub mod tests { ); // Executable may not be modified - let mut account_modified = account.clone(); + let mut account_modified = account; account_modified.executable = true; assert_ne!( hash, @@ -3641,7 +3641,7 @@ pub mod tests { db.hash_accounts(some_slot, accounts); // provide bogus account hashes let some_hash = Hash::new(&[0xca; HASH_BYTES]); - db.store_with_hashes(some_slot, accounts, &vec![some_hash]); + db.store_with_hashes(some_slot, accounts, &[some_hash]); db.add_root(some_slot); assert_matches!( db.verify_bank_hash(some_slot, &ancestors), @@ -3655,12 +3655,11 @@ pub mod tests { let db = AccountsDB::new(Vec::new()); let some_slot: Slot = 0; - let ancestors = vec![(some_slot, 0)].into_iter().collect(); + let ancestors: Ancestors = [(some_slot, 0)].iter().copied().collect(); for _ in 0..10_000 { let num_accounts = thread_rng().gen_range(0, 100); let accounts_keys: Vec<_> = (0..num_accounts) - .into_iter() .map(|_| { let key = Keypair::new().pubkey(); let lamports = thread_rng().gen_range(0, 100); @@ -3790,7 +3789,7 @@ pub mod tests { let account = Account::new(old_lamport, no_data, &owner); let account2 = Account::new(old_lamport + 100_001, no_data, &owner); let account3 = Account::new(old_lamport + 100_002, no_data, &owner); - let dummy_account = Account::new(99999999, no_data, &owner); + let dummy_account = Account::new(99_999_999, no_data, &owner); let zero_lamport_account = Account::new(zero_lamport, no_data, &owner); let pubkey = Pubkey::new_rand(); @@ -3846,7 +3845,7 @@ pub mod tests { let old_lamport = 223; let zero_lamport = 0; let no_data = 0; - let dummy_lamport = 999999; + let dummy_lamport = 999_999; let owner = Account::default().owner; let account = Account::new(old_lamport, no_data, &owner); @@ -4124,12 +4123,12 @@ pub mod tests { lamports: 0, }; let mut reclaims = vec![]; - accounts_index.insert(0, &key0, info0.clone(), &mut reclaims); + accounts_index.insert(0, &key0, info0, &mut reclaims); accounts_index.insert(1, &key0, info1.clone(), &mut reclaims); - accounts_index.insert(1, &key1, info1.clone(), &mut reclaims); + accounts_index.insert(1, &key1, info1, &mut reclaims); accounts_index.insert(2, &key1, info2.clone(), &mut reclaims); - accounts_index.insert(2, &key2, info2.clone(), &mut reclaims); - accounts_index.insert(3, &key2, info3.clone(), &mut reclaims); + accounts_index.insert(2, &key2, info2, &mut reclaims); + accounts_index.insert(3, &key2, info3, &mut reclaims); accounts_index.add_root(0); accounts_index.add_root(1); accounts_index.add_root(2); diff --git a/runtime/src/append_vec.rs b/runtime/src/append_vec.rs index 134fcc84418f27..cf722da6780599 100644 --- a/runtime/src/append_vec.rs +++ b/runtime/src/append_vec.rs @@ -545,12 +545,12 @@ pub mod tests { } impl<'a> StoredAccount<'a> { + #[allow(clippy::cast_ref_to_mut)] fn set_data_len_unsafe(&self, new_data_len: u64) { - let data_len: &u64 = &self.meta.data_len; - #[allow(mutable_transmutes)] // UNSAFE: cast away & (= const ref) to &mut to force to mutate append-only (=read-only) AppendVec - let data_len: &mut u64 = unsafe { &mut *(data_len as *const u64 as *mut u64) }; - *data_len = new_data_len; + unsafe { + *(&self.meta.data_len as *const u64 as *mut u64) = new_data_len; + } } fn get_executable_byte(&self) -> u8 { @@ -560,13 +560,12 @@ pub mod tests { executable_byte } + #[allow(clippy::cast_ref_to_mut)] fn set_executable_as_byte(&self, new_executable_byte: u8) { - let executable_ref: &bool = &self.account_meta.executable; - #[allow(mutable_transmutes)] // UNSAFE: Force to interpret mmap-backed &bool as &u8 to write some crafted value; - let executable_byte: &mut u8 = - unsafe { &mut *(executable_ref as *const bool as *mut u8) }; - *executable_byte = new_executable_byte; + unsafe { + *(&self.account_meta.executable as *const bool as *mut u8) = new_executable_byte; + } } } @@ -597,31 +596,41 @@ pub mod tests { #[test] fn test_append_vec_sanitize_len_and_size_too_small() { - let result = AppendVec::sanitize_len_and_size(0, 0); + const LEN: usize = 0; + const SIZE: usize = 0; + let result = AppendVec::sanitize_len_and_size(LEN, SIZE); assert_matches!(result, Err(ref message) if message.to_string() == *"too small file size 0 for AppendVec"); } #[test] fn test_append_vec_sanitize_len_and_size_maximum() { - let result = AppendVec::sanitize_len_and_size(0, 16 * 1024 * 1024 * 1024); + const LEN: usize = 0; + const SIZE: usize = 16 * 1024 * 1024 * 1024; + let result = AppendVec::sanitize_len_and_size(LEN, SIZE); assert_matches!(result, Ok(_)); } #[test] fn test_append_vec_sanitize_len_and_size_too_large() { - let result = AppendVec::sanitize_len_and_size(0, 16 * 1024 * 1024 * 1024 + 1); + const LEN: usize = 0; + const SIZE: usize = 16 * 1024 * 1024 * 1024 + 1; + let result = AppendVec::sanitize_len_and_size(LEN, SIZE); assert_matches!(result, Err(ref message) if message.to_string() == *"too large file size 17179869185 for AppendVec"); } #[test] fn test_append_vec_sanitize_len_and_size_full_and_same_as_current_len() { - let result = AppendVec::sanitize_len_and_size(1 * 1024 * 1024, 1 * 1024 * 1024); + const LEN: usize = 1024 * 1024; + const SIZE: usize = 1024 * 1024; + let result = AppendVec::sanitize_len_and_size(LEN, SIZE); assert_matches!(result, Ok(_)); } #[test] fn test_append_vec_sanitize_len_and_size_larger_current_len() { - let result = AppendVec::sanitize_len_and_size(1 * 1024 * 1024 + 1, 1 * 1024 * 1024); + const LEN: usize = 1024 * 1024 + 1; + const SIZE: usize = 1024 * 1024; + let result = AppendVec::sanitize_len_and_size(LEN, SIZE); assert_matches!(result, Err(ref message) if message.to_string() == *"current_len is larger than file size (1048576)"); } @@ -806,7 +815,8 @@ pub mod tests { // Depending on use, *executable_bool can be truthy or falsy due to direct memory manipulation // assert_eq! thinks *exeutable_bool is equal to false but the if condition thinks it's not, contradictly. assert_eq!(*executable_bool, false); - if *executable_bool == false { + const FALSE: bool = false; // keep clippy happy + if *executable_bool == FALSE { panic!("This didn't occur if this test passed."); } assert_eq!(*account.ref_executable_byte(), crafted_executable); diff --git a/runtime/src/bank.rs b/runtime/src/bank.rs index 5b78afb4b781e3..b6880a9aa50805 100644 --- a/runtime/src/bank.rs +++ b/runtime/src/bank.rs @@ -2679,6 +2679,7 @@ mod tests { } #[test] + #[allow(clippy::float_cmp)] fn test_bank_new() { let dummy_leader_pubkey = Pubkey::new_rand(); let dummy_leader_lamports = BOOTSTRAP_VALIDATOR_LAMPORTS; @@ -2728,13 +2729,13 @@ mod tests { fn test_bank_update_epoch_stakes() { impl Bank { fn epoch_stake_keys(&self) -> Vec { - let mut keys: Vec = self.epoch_stakes.keys().map(|k| *k).collect(); + let mut keys: Vec = self.epoch_stakes.keys().copied().collect(); keys.sort(); keys } fn epoch_stake_key_info(&self) -> (Epoch, Epoch, usize) { - let mut keys: Vec = self.epoch_stakes.keys().map(|k| *k).collect(); + let mut keys: Vec = self.epoch_stakes.keys().copied().collect(); keys.sort(); (*keys.first().unwrap(), *keys.last().unwrap(), keys.len()) } @@ -2790,7 +2791,6 @@ mod tests { fn test_bank_capitalization() { let bank = Arc::new(Bank::new(&GenesisConfig { accounts: (0..42) - .into_iter() .map(|_| (Pubkey::new_rand(), Account::new(42, 0, &Pubkey::default()))) .collect(), ..GenesisConfig::default() @@ -2879,7 +2879,7 @@ mod tests { let t3 = system_transaction::transfer(&keypair5, &keypair6.pubkey(), 1, genesis_config.hash()); - let res = bank.process_transactions(&vec![t1.clone(), t2.clone(), t3.clone()]); + let res = bank.process_transactions(&[t1.clone(), t2.clone(), t3]); assert_eq!(res.len(), 3); assert_eq!(res[0], Ok(())); @@ -2891,7 +2891,7 @@ mod tests { let rwlockguard_bank_hash = bank.hash.read().unwrap(); let bank_hash = rwlockguard_bank_hash.as_ref(); - let res = bank_with_success_txs.process_transactions(&vec![t2.clone(), t1.clone()]); + let res = bank_with_success_txs.process_transactions(&[t2, t1]); assert_eq!(res.len(), 2); assert_eq!(res[0], Ok(())); @@ -3294,7 +3294,7 @@ mod tests { #[test] fn test_rent_exempt_executable_account() { - let (mut genesis_config, mint_keypair) = create_genesis_config(100000); + let (mut genesis_config, mint_keypair) = create_genesis_config(100_000); genesis_config.rent = Rent { lamports_per_byte_year: 1, exemption_threshold: 1000.0, @@ -3419,14 +3419,7 @@ mod tests { genesis_config.hash(), ); - let res = bank.process_transactions(&[ - t6.clone(), - t5.clone(), - t1.clone(), - t2.clone(), - t3.clone(), - t4.clone(), - ]); + let res = bank.process_transactions(&[t6, t5, t1, t2, t3, t4]); assert_eq!(res.len(), 6); assert_eq!(res[0], Ok(())); @@ -3548,6 +3541,7 @@ mod tests { } #[test] + #[allow(clippy::cognitive_complexity)] fn test_rent_eager_across_epoch_without_gap_under_multi_epoch_cycle() { let leader_pubkey = Pubkey::new_rand(); let leader_lamports = 3; @@ -3561,32 +3555,32 @@ mod tests { EpochSchedule::custom(SLOTS_PER_EPOCH, LEADER_SCHEDULE_SLOT_OFFSET, false); let mut bank = Arc::new(Bank::new(&genesis_config)); - assert_eq!(DEFAULT_SLOTS_PER_EPOCH, 432000); + assert_eq!(DEFAULT_SLOTS_PER_EPOCH, 432_000); assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 32); assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (0, 0)); - assert_eq!(bank.rent_collection_partitions(), vec![(0, 0, 432000)]); + assert_eq!(bank.rent_collection_partitions(), vec![(0, 0, 432_000)]); bank = Arc::new(new_from_parent(&bank)); assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 32); assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (0, 1)); - assert_eq!(bank.rent_collection_partitions(), vec![(0, 1, 432000)]); + assert_eq!(bank.rent_collection_partitions(), vec![(0, 1, 432_000)]); for _ in 2..32 { bank = Arc::new(new_from_parent(&bank)); } assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 32); assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (0, 31)); - assert_eq!(bank.rent_collection_partitions(), vec![(30, 31, 432000)]); + assert_eq!(bank.rent_collection_partitions(), vec![(30, 31, 432_000)]); bank = Arc::new(new_from_parent(&bank)); assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 32); assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (1, 0)); - assert_eq!(bank.rent_collection_partitions(), vec![(31, 32, 432000)]); + assert_eq!(bank.rent_collection_partitions(), vec![(31, 32, 432_000)]); bank = Arc::new(new_from_parent(&bank)); assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 32); assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (1, 1)); - assert_eq!(bank.rent_collection_partitions(), vec![(32, 33, 432000)]); + assert_eq!(bank.rent_collection_partitions(), vec![(32, 33, 432_000)]); bank = Arc::new(Bank::new_from_parent(&bank, &Pubkey::default(), 1000)); bank = Arc::new(Bank::new_from_parent(&bank, &Pubkey::default(), 1001)); @@ -3594,27 +3588,27 @@ mod tests { assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (31, 9)); assert_eq!( bank.rent_collection_partitions(), - vec![(1000, 1001, 432000)] + vec![(1000, 1001, 432_000)] ); - bank = Arc::new(Bank::new_from_parent(&bank, &Pubkey::default(), 431998)); - bank = Arc::new(Bank::new_from_parent(&bank, &Pubkey::default(), 431999)); + bank = Arc::new(Bank::new_from_parent(&bank, &Pubkey::default(), 431_998)); + bank = Arc::new(Bank::new_from_parent(&bank, &Pubkey::default(), 431_999)); assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 32); assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (13499, 31)); assert_eq!( bank.rent_collection_partitions(), - vec![(431998, 431999, 432000)] + vec![(431_998, 431_999, 432_000)] ); bank = Arc::new(new_from_parent(&bank)); assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 32); assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (13500, 0)); - assert_eq!(bank.rent_collection_partitions(), vec![(0, 0, 432000)]); + assert_eq!(bank.rent_collection_partitions(), vec![(0, 0, 432_000)]); bank = Arc::new(new_from_parent(&bank)); assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 32); assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (13500, 1)); - assert_eq!(bank.rent_collection_partitions(), vec![(0, 1, 432000)]); + assert_eq!(bank.rent_collection_partitions(), vec![(0, 1, 432_000)]); } #[test] @@ -3631,43 +3625,43 @@ mod tests { EpochSchedule::custom(SLOTS_PER_EPOCH, LEADER_SCHEDULE_SLOT_OFFSET, false); let mut bank = Arc::new(Bank::new(&genesis_config)); - assert_eq!(DEFAULT_SLOTS_PER_EPOCH, 432000); + assert_eq!(DEFAULT_SLOTS_PER_EPOCH, 432_000); assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 32); assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (0, 0)); - assert_eq!(bank.rent_collection_partitions(), vec![(0, 0, 432000)]); + assert_eq!(bank.rent_collection_partitions(), vec![(0, 0, 432_000)]); bank = Arc::new(new_from_parent(&bank)); assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 32); assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (0, 1)); - assert_eq!(bank.rent_collection_partitions(), vec![(0, 1, 432000)]); + assert_eq!(bank.rent_collection_partitions(), vec![(0, 1, 432_000)]); for _ in 2..19 { bank = Arc::new(new_from_parent(&bank)); } assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 32); assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (0, 18)); - assert_eq!(bank.rent_collection_partitions(), vec![(17, 18, 432000)]); + assert_eq!(bank.rent_collection_partitions(), vec![(17, 18, 432_000)]); bank = Arc::new(Bank::new_from_parent(&bank, &Pubkey::default(), 44)); assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 32); assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (1, 12)); assert_eq!( bank.rent_collection_partitions(), - vec![(18, 31, 432000), (31, 44, 432000)] + vec![(18, 31, 432_000), (31, 44, 432_000)] ); bank = Arc::new(new_from_parent(&bank)); assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 32); assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (1, 13)); - assert_eq!(bank.rent_collection_partitions(), vec![(44, 45, 432000)]); + assert_eq!(bank.rent_collection_partitions(), vec![(44, 45, 432_000)]); - bank = Arc::new(Bank::new_from_parent(&bank, &Pubkey::default(), 431993)); - bank = Arc::new(Bank::new_from_parent(&bank, &Pubkey::default(), 432011)); + bank = Arc::new(Bank::new_from_parent(&bank, &Pubkey::default(), 431_993)); + bank = Arc::new(Bank::new_from_parent(&bank, &Pubkey::default(), 432_011)); assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 32); assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (13500, 11)); assert_eq!( bank.rent_collection_partitions(), - vec![(431993, 431999, 432000), (0, 11, 432000)] + vec![(431_993, 431_999, 432_000), (0, 11, 432_000)] ); } @@ -3685,7 +3679,7 @@ mod tests { EpochSchedule::custom(SLOTS_PER_EPOCH, LEADER_SCHEDULE_SLOT_OFFSET, true); let mut bank = Arc::new(Bank::new(&genesis_config)); - assert_eq!(DEFAULT_SLOTS_PER_EPOCH, 432000); + assert_eq!(DEFAULT_SLOTS_PER_EPOCH, 432_000); assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 32); assert_eq!(bank.first_normal_epoch(), 3); assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (0, 0)); @@ -3700,31 +3694,31 @@ mod tests { bank = Arc::new(new_from_parent(&bank)); assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 256); assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (3, 0)); - assert_eq!(bank.rent_collection_partitions(), vec![(0, 0, 431872)]); - assert_eq!(431872 % bank.get_slots_in_epoch(bank.epoch()), 0); + assert_eq!(bank.rent_collection_partitions(), vec![(0, 0, 431_872)]); + assert_eq!(431_872 % bank.get_slots_in_epoch(bank.epoch()), 0); bank = Arc::new(new_from_parent(&bank)); assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 256); assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (3, 1)); - assert_eq!(bank.rent_collection_partitions(), vec![(0, 1, 431872)]); + assert_eq!(bank.rent_collection_partitions(), vec![(0, 1, 431_872)]); bank = Arc::new(Bank::new_from_parent( &bank, &Pubkey::default(), - 431872 + 223 - 1, + 431_872 + 223 - 1, )); bank = Arc::new(new_from_parent(&bank)); assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 256); assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (1689, 255)); assert_eq!( bank.rent_collection_partitions(), - vec![(431870, 431871, 431872)] + vec![(431_870, 431_871, 431_872)] ); bank = Arc::new(new_from_parent(&bank)); assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 256); assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (1690, 0)); - assert_eq!(bank.rent_collection_partitions(), vec![(0, 0, 431872)]); + assert_eq!(bank.rent_collection_partitions(), vec![(0, 0, 431_872)]); } #[test] @@ -3744,48 +3738,52 @@ mod tests { assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 32); assert_eq!(bank.first_normal_epoch(), 3); assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (0, 0)); - assert_eq!(bank.rent_collection_partitions(), vec![(0, 0, 432000)]); + assert_eq!(bank.rent_collection_partitions(), vec![(0, 0, 432_000)]); bank = Arc::new(Bank::new_from_parent(&bank, &Pubkey::default(), 222)); bank = Arc::new(new_from_parent(&bank)); assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 128); assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (2, 127)); - assert_eq!(bank.rent_collection_partitions(), vec![(222, 223, 432000)]); + assert_eq!(bank.rent_collection_partitions(), vec![(222, 223, 432_000)]); bank = Arc::new(new_from_parent(&bank)); assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 256); assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (3, 0)); - assert_eq!(bank.rent_collection_partitions(), vec![(223, 224, 432000)]); + assert_eq!(bank.rent_collection_partitions(), vec![(223, 224, 432_000)]); bank = Arc::new(new_from_parent(&bank)); assert_eq!(bank.get_slots_in_epoch(bank.epoch()), 256); assert_eq!(bank.get_epoch_and_slot_index(bank.slot()), (3, 1)); - assert_eq!(bank.rent_collection_partitions(), vec![(224, 225, 432000)]); + assert_eq!(bank.rent_collection_partitions(), vec![(224, 225, 432_000)]); - bank = Arc::new(Bank::new_from_parent(&bank, &Pubkey::default(), 432000 - 2)); + bank = Arc::new(Bank::new_from_parent( + &bank, + &Pubkey::default(), + 432_000 - 2, + )); bank = Arc::new(new_from_parent(&bank)); assert_eq!( bank.rent_collection_partitions(), - vec![(431998, 431999, 432000)] + vec![(431_998, 431_999, 432_000)] ); bank = Arc::new(new_from_parent(&bank)); - assert_eq!(bank.rent_collection_partitions(), vec![(0, 0, 432000)]); + assert_eq!(bank.rent_collection_partitions(), vec![(0, 0, 432_000)]); bank = Arc::new(new_from_parent(&bank)); - assert_eq!(bank.rent_collection_partitions(), vec![(0, 1, 432000)]); + assert_eq!(bank.rent_collection_partitions(), vec![(0, 1, 432_000)]); bank = Arc::new(Bank::new_from_parent( &bank, &Pubkey::default(), - 864000 - 20, + 864_000 - 20, )); bank = Arc::new(Bank::new_from_parent( &bank, &Pubkey::default(), - 864000 + 39, + 864_000 + 39, )); assert_eq!( bank.rent_collection_partitions(), - vec![(431980, 431999, 432000), (0, 39, 432000)] + vec![(431_980, 431_999, 432_000), (0, 39, 432_000)] ); } @@ -3924,7 +3922,7 @@ mod tests { let mut bank = Arc::new(Bank::new(&genesis_config)); let zero_lamports = 0; let little_lamports = 1234; - let large_lamports = 123456789; + let large_lamports = 123_456_789; let rent_collected = 22; bank.store_account( @@ -4064,7 +4062,6 @@ mod tests { // create a bank that ticks really slowly... let bank = Arc::new(Bank::new(&GenesisConfig { accounts: (0..42) - .into_iter() .map(|_| { ( Pubkey::new_rand(), @@ -4102,9 +4099,9 @@ mod tests { // generate some rewards let mut vote_state = Some(VoteState::from(&vote_account).unwrap()); for i in 0..MAX_LOCKOUT_HISTORY + 42 { - vote_state - .as_mut() - .map(|v| v.process_slot_vote_unchecked(i as u64)); + if let Some(v) = vote_state.as_mut() { + v.process_slot_vote_unchecked(i as u64) + } let versioned = VoteStateVersions::Current(Box::new(vote_state.take().unwrap())); VoteState::to(&versioned, &mut vote_account).unwrap(); bank.store_account(&vote_id, &vote_account); @@ -4253,7 +4250,7 @@ mod tests { let t1 = system_transaction::transfer(&mint_keypair, &key1, 1, genesis_config.hash()); let t2 = system_transaction::transfer(&mint_keypair, &key2, 1, genesis_config.hash()); - let res = bank.process_transactions(&vec![t1.clone(), t2.clone()]); + let res = bank.process_transactions(&[t1.clone(), t2.clone()]); assert_eq!(res.len(), 2); assert_eq!(res[0], Ok(())); @@ -4642,7 +4639,7 @@ mod tests { ]; let initial_balance = bank.get_balance(&leader); - let results = bank.filter_program_errors_and_collect_fee(&vec![tx1, tx2], None, &results); + let results = bank.filter_program_errors_and_collect_fee(&[tx1, tx2], None, &results); bank.freeze(); assert_eq!( bank.get_balance(&leader), @@ -4737,7 +4734,7 @@ mod tests { assert_eq!(results[0], Ok(())); assert_eq!(results[1], Ok(())); - let ix0 = vote_instruction::vote(&vote_pubkey2, &authorized_voter.pubkey(), vote.clone()); + let ix0 = vote_instruction::vote(&vote_pubkey2, &authorized_voter.pubkey(), vote); let tx0 = Transaction::new_signed_with_payer( &[ix0], Some(&payer0.pubkey()), @@ -4873,7 +4870,7 @@ mod tests { Err(TransactionError::SanitizeFailure) ); - let mut tx_invalid_account_index = tx.clone(); + let mut tx_invalid_account_index = tx; tx_invalid_account_index.message.instructions[0].accounts[0] = 42; assert_eq!( bank.process_transaction(&tx_invalid_account_index), @@ -5828,6 +5825,7 @@ mod tests { } #[test] + #[allow(clippy::float_cmp)] fn test_check_point_value() { let (genesis_config, _) = create_genesis_config(500); let bank = Arc::new(Bank::new(&genesis_config)); @@ -5881,7 +5879,7 @@ mod tests { ); assert_eq!( bank1.get_program_accounts(Some(&program_id)), - vec![(pubkey0, account0.clone())] + vec![(pubkey0, account0)] ); assert_eq!( bank1.get_program_accounts_modified_since_parent(&program_id), @@ -6056,7 +6054,7 @@ mod tests { sysvar::recent_blockhashes::RecentBlockhashes::from_account(&bhq_account).unwrap(); // Check length assert_eq!(recent_blockhashes.len(), i); - let most_recent_hash = recent_blockhashes.iter().nth(0).unwrap().blockhash; + let most_recent_hash = recent_blockhashes.iter().next().unwrap().blockhash; // Check order assert_eq!(Some(true), bank.check_hash_age(&most_recent_hash, 0)); goto_end_of_slot(Arc::get_mut(&mut bank).unwrap()); @@ -6188,7 +6186,7 @@ mod tests { &custodian_keypair.pubkey(), custodian_lamports, )]; - let nonce_authority = nonce_authority.unwrap_or(nonce_keypair.pubkey()); + let nonce_authority = nonce_authority.unwrap_or_else(|| nonce_keypair.pubkey()); setup_ixs.extend_from_slice(&system_instruction::create_nonce_account( &custodian_keypair.pubkey(), &nonce_keypair.pubkey(), @@ -6348,7 +6346,7 @@ mod tests { let bank = Arc::new(Bank::new(&genesis_config)); let nonce = Keypair::new(); let nonce_account = Account::new_data( - 42424242, + 42_424_242, &nonce::state::Versions::new_current(nonce::State::Initialized( nonce::state::Data::default(), )), @@ -6376,16 +6374,8 @@ mod tests { #[test] fn test_durable_nonce_transaction() { - let (mut bank, _mint_keypair, custodian_keypair, nonce_keypair) = setup_nonce_with_bank( - 10_000_000, - |gc| { - gc.rent.lamports_per_byte_year; - }, - 5_000_000, - 250_000, - None, - ) - .unwrap(); + let (mut bank, _mint_keypair, custodian_keypair, nonce_keypair) = + setup_nonce_with_bank(10_000_000, |_| {}, 5_000_000, 250_000, None).unwrap(); let alice_keypair = Keypair::new(); let alice_pubkey = alice_keypair.pubkey(); let custodian_pubkey = custodian_keypair.pubkey(); @@ -6552,9 +6542,9 @@ mod tests { let blockhash = bank0.last_blockhash(); - let tx0 = system_transaction::transfer(&keypair0, &pubkey0, 2, blockhash.clone()); - let tx1 = system_transaction::transfer(&Keypair::new(), &pubkey1, 2, blockhash.clone()); - let tx2 = system_transaction::transfer(&keypair1, &pubkey2, 12, blockhash.clone()); + let tx0 = system_transaction::transfer(&keypair0, &pubkey0, 2, blockhash); + let tx1 = system_transaction::transfer(&Keypair::new(), &pubkey1, 2, blockhash); + let tx2 = system_transaction::transfer(&keypair1, &pubkey2, 12, blockhash); let txs = vec![tx0, tx1, tx2]; let lock_result = bank0.prepare_batch(&txs, None); @@ -6608,7 +6598,7 @@ mod tests { let from_pubkey = Pubkey::new_rand(); let to_pubkey = Pubkey::new_rand(); - let dup_pubkey = from_pubkey.clone(); + let dup_pubkey = from_pubkey; let from_account = Account::new(100, 1, &mock_program_id); let to_account = Account::new(0, 1, &mock_program_id); bank.store_account(&from_pubkey, &from_account); @@ -6651,7 +6641,7 @@ mod tests { let from_pubkey = Pubkey::new_rand(); let to_pubkey = Pubkey::new_rand(); - let dup_pubkey = from_pubkey.clone(); + let dup_pubkey = from_pubkey; let from_account = Account::new(100, 1, &mock_program_id); let to_account = Account::new(0, 1, &mock_program_id); bank.store_account(&from_pubkey, &from_account); @@ -6873,7 +6863,6 @@ mod tests { let max_programs = 5; let program_keys: Vec<_> = (0..max_programs) - .into_iter() .enumerate() .map(|i| { let key = Pubkey::new_rand(); @@ -6884,7 +6873,6 @@ mod tests { .collect(); let max_keys = 100; let keys: Vec<_> = (0..max_keys) - .into_iter() .enumerate() .map(|_| { let key = Pubkey::new_rand(); @@ -6916,7 +6904,6 @@ mod tests { let mut account_keys: Vec<_> = if thread_rng().gen_ratio(1, 5) { (0..num_keys) - .into_iter() .map(|_| { let idx = thread_rng().gen_range(0, keys.len()); keys[idx].0 @@ -6926,7 +6913,6 @@ mod tests { use std::collections::HashSet; let mut inserted = HashSet::new(); (0..num_keys) - .into_iter() .map(|_| { let mut idx; loop { @@ -6943,11 +6929,9 @@ mod tests { let instructions: Vec<_> = if num_keys > 0 { (0..num_instructions) - .into_iter() .map(|_| { let num_accounts_to_pass = thread_rng().gen_range(0, num_keys); let account_indexes = (0..num_accounts_to_pass) - .into_iter() .map(|_| thread_rng().gen_range(0, num_keys)) .collect(); let program_index: u8 = thread_rng().gen_range(0, num_keys) as u8; diff --git a/runtime/src/message_processor.rs b/runtime/src/message_processor.rs index 30668ec6e82fc1..95aa5b8c0d9104 100644 --- a/runtime/src/message_processor.rs +++ b/runtime/src/message_processor.rs @@ -595,8 +595,8 @@ mod tests { // Check call depth increases and has a limit let mut depth_reached = 1; - for i in 1..MAX_DEPTH { - if Err(InstructionError::CallDepth) == invoke_context.push(&program_ids[i]) { + for program_id in program_ids.iter().skip(1) { + if Err(InstructionError::CallDepth) == invoke_context.push(program_id) { break; } depth_reached += 1; @@ -721,7 +721,7 @@ mod tests { } pub fn new_cross_program(owner: &Pubkey, program_id: &Pubkey, key: &Pubkey) -> Self { let mut change = Change::new(owner, program_id); - change.pre.key = key.clone(); + change.pre.key = *key; change } pub fn read_only(mut self) -> Self { @@ -931,7 +931,7 @@ mod tests { Change::new(&owner, &owner) .executable(false, true) .lamports(0, min_lamports - 1) - .data(data.clone(), data.clone()) + .data(data.clone(), data) .verify(), Err(InstructionError::ExecutableAccountNotRentExempt), "owner should not be able to change an account's data once its marked executable" @@ -968,7 +968,7 @@ mod tests { assert_eq!( Change::new_cross_program(&owner, &system_program_id, &key) - .signer(false, true, &[key.clone()]) + .signer(false, true, &[key]) .verify_cross_program(), Ok(()), "account signed by a signer" @@ -1314,7 +1314,7 @@ mod tests { let from_pubkey = Pubkey::new_rand(); let to_pubkey = Pubkey::new_rand(); - let dup_pubkey = from_pubkey.clone(); + let dup_pubkey = from_pubkey; let account_metas = vec![ AccountMeta::new(from_pubkey, true), AccountMeta::new(to_pubkey, false), diff --git a/runtime/src/nonce_utils.rs b/runtime/src/nonce_utils.rs index 73dc9e6a2a6616..cdd9eb353cbb56 100644 --- a/runtime/src/nonce_utils.rs +++ b/runtime/src/nonce_utils.rs @@ -212,7 +212,7 @@ mod tests { // New is in Uninitialzed state assert_eq!(state, State::Uninitialized); let recent_blockhashes = create_test_recent_blockhashes(0); - let authorized = nonce_account.unsigned_key().clone(); + let authorized = nonce_account.unsigned_key(); nonce_account .initialize_nonce_account(&authorized, &recent_blockhashes, &Rent::free()) .unwrap(); @@ -242,7 +242,7 @@ mod tests { // New is in Uninitialzed state assert_eq!(state, State::Uninitialized); let recent_blockhashes = create_test_recent_blockhashes(0); - let authorized = nonce_account.unsigned_key().clone(); + let authorized = nonce_account.unsigned_key(); nonce_account .initialize_nonce_account(&authorized, &recent_blockhashes, &Rent::free()) .unwrap(); @@ -378,7 +378,7 @@ mod tests { &post_account_pubkey, &Err(transaction::TransactionError::InstructionError( 0, - InstructionError::InvalidArgument.into(), + InstructionError::InvalidArgument, )), Some((&pre_account_pubkey, &pre_account)), &last_blockhash, diff --git a/runtime/src/stakes.rs b/runtime/src/stakes.rs index ba180330ed2aea..3a6c5cf2a49ee3 100644 --- a/runtime/src/stakes.rs +++ b/runtime/src/stakes.rs @@ -323,9 +323,9 @@ pub mod tests { let mut vote_state = Some(VoteState::from(&vote_account).unwrap()); for i in 0..MAX_LOCKOUT_HISTORY + 42 { - vote_state - .as_mut() - .map(|v| v.process_slot_vote_unchecked(i as u64)); + if let Some(v) = vote_state.as_mut() { + v.process_slot_vote_unchecked(i as u64) + } let versioned = VoteStateVersions::Current(Box::new(vote_state.take().unwrap())); VoteState::to(&versioned, &mut vote_account).unwrap(); match versioned { diff --git a/runtime/src/status_cache.rs b/runtime/src/status_cache.rs index 732f076dda95b7..d27674785a409b 100644 --- a/runtime/src/status_cache.rs +++ b/runtime/src/status_cache.rs @@ -456,6 +456,7 @@ mod tests { } #[test] + #[allow(clippy::assertions_on_constants)] fn test_age_sanity() { assert!(MAX_CACHE_ENTRIES <= MAX_RECENT_BLOCKHASHES); } diff --git a/runtime/src/system_instruction_processor.rs b/runtime/src/system_instruction_processor.rs index a161aa39ab6e3d..7a1149c2db3aa9 100644 --- a/runtime/src/system_instruction_processor.rs +++ b/runtime/src/system_instruction_processor.rs @@ -497,7 +497,7 @@ mod tests { let from_lamports = from_account.borrow().lamports; let to_lamports = to_account.lamports; let to_owner = to_account.owner; - let to_data = to_account.data.clone(); + let to_data = to_account.data; assert_eq!(from_lamports, 100); assert_eq!(to_lamports, 0); assert_eq!(to_owner, new_program_owner); diff --git a/runtime/tests/stake.rs b/runtime/tests/stake.rs index c6c63355d3a4cb..c4329addead262 100644 --- a/runtime/tests/stake.rs +++ b/runtime/tests/stake.rs @@ -211,7 +211,7 @@ fn test_stake_account_lifetime() { if let StakeState::Stake(_meta, stake) = stake_state { assert_eq!(stake.delegation.stake, 1_000_000); } else { - assert!(false, "wrong account type found") + panic!("wrong account type found") } // Test that we cannot withdraw anything until deactivation @@ -235,7 +235,7 @@ fn test_stake_account_lifetime() { if let StakeState::Stake(_meta, stake) = stake_state { assert_eq!(stake.delegation.stake, 1_000_000); } else { - assert!(false, "wrong account type found") + panic!("wrong account type found") } loop { @@ -453,6 +453,6 @@ fn test_create_stake_account_from_seed() { if let StakeState::Stake(_meta, stake) = stake_state { assert_eq!(stake.delegation.stake, 1_000_000); } else { - assert!(false, "wrong account type found") + panic!("wrong account type found") } } diff --git a/sdk/src/epoch_schedule.rs b/sdk/src/epoch_schedule.rs index fb622ead1f9210..c266a49403e8cf 100644 --- a/sdk/src/epoch_schedule.rs +++ b/sdk/src/epoch_schedule.rs @@ -183,10 +183,8 @@ mod tests { // until they reach slots_per_epoch let slots_in_epoch = epoch_schedule.get_slots_in_epoch(epoch); - if slots_in_epoch != last_slots_in_epoch { - if slots_in_epoch != slots_per_epoch { - assert_eq!(slots_in_epoch, last_slots_in_epoch * 2); - } + if slots_in_epoch != last_slots_in_epoch && slots_in_epoch != slots_per_epoch { + assert_eq!(slots_in_epoch, last_slots_in_epoch * 2); } last_slots_in_epoch = slots_in_epoch; } diff --git a/sdk/src/hard_forks.rs b/sdk/src/hard_forks.rs index bd91ec190ec4c6..0627ebc206ebb0 100644 --- a/sdk/src/hard_forks.rs +++ b/sdk/src/hard_forks.rs @@ -67,10 +67,7 @@ mod tests { hf.register(10); hf.register(20); - assert_eq!( - hf.iter().map(|i| *i).collect::>(), - vec![(10, 1), (20, 2), (30, 1)] - ); + assert_eq!(hf.hard_forks, vec![(10, 1), (20, 2), (30, 1)]); } #[test] diff --git a/sdk/src/inflation.rs b/sdk/src/inflation.rs index fff5e1c736ade9..5c6e44a82c5a2e 100644 --- a/sdk/src/inflation.rs +++ b/sdk/src/inflation.rs @@ -89,6 +89,7 @@ mod tests { use super::*; #[test] + #[allow(clippy::float_cmp)] fn test_inflation_basic() { let inflation = Inflation::default(); diff --git a/sdk/src/nonce/account.rs b/sdk/src/nonce/account.rs index 7caea2db250df7..aaac8a743454c4 100644 --- a/sdk/src/nonce/account.rs +++ b/sdk/src/nonce/account.rs @@ -218,7 +218,7 @@ mod test { // New is in Uninitialzed state assert_eq!(state, State::Uninitialized); let recent_blockhashes = create_test_recent_blockhashes(95); - let authorized = keyed_account.unsigned_key().clone(); + let authorized = keyed_account.unsigned_key(); keyed_account .initialize_nonce_account(&authorized, &recent_blockhashes, &rent) .unwrap(); @@ -228,7 +228,7 @@ mod test { let data = nonce::state::Data { blockhash: recent_blockhashes[0].blockhash, fee_calculator: recent_blockhashes[0].fee_calculator.clone(), - ..data.clone() + ..data }; // First nonce instruction drives state from Uninitialized to Initialized assert_eq!(state, State::Initialized(data.clone())); @@ -242,7 +242,7 @@ mod test { let data = nonce::state::Data { blockhash: recent_blockhashes[0].blockhash, fee_calculator: recent_blockhashes[0].fee_calculator.clone(), - ..data.clone() + ..data }; // Second nonce instruction consumes and replaces stored nonce assert_eq!(state, State::Initialized(data.clone())); @@ -256,10 +256,10 @@ mod test { let data = nonce::state::Data { blockhash: recent_blockhashes[0].blockhash, fee_calculator: recent_blockhashes[0].fee_calculator.clone(), - ..data.clone() + ..data }; // Third nonce instruction for fun and profit - assert_eq!(state, State::Initialized(data.clone())); + assert_eq!(state, State::Initialized(data)); with_test_keyed_account(42, false, |to_keyed| { let recent_blockhashes = create_test_recent_blockhashes(0); let withdraw_lamports = keyed_account.account.borrow().lamports; @@ -295,11 +295,11 @@ mod test { let min_lamports = rent.minimum_balance(State::size()); with_test_keyed_account(min_lamports + 42, true, |nonce_account| { let recent_blockhashes = create_test_recent_blockhashes(31); - let authority = nonce_account.unsigned_key().clone(); + let authority = *nonce_account.unsigned_key(); nonce_account .initialize_nonce_account(&authority, &recent_blockhashes, &rent) .unwrap(); - let pubkey = nonce_account.account.borrow().owner.clone(); + let pubkey = nonce_account.account.borrow().owner; let nonce_account = KeyedAccount::new(&pubkey, false, nonce_account.account); let state = AccountUtilsState::::state(&nonce_account) .unwrap() @@ -328,7 +328,7 @@ mod test { let mut signers = HashSet::new(); signers.insert(keyed_account.signer_key().unwrap().clone()); let recent_blockhashes = create_test_recent_blockhashes(0); - let authorized = keyed_account.unsigned_key().clone(); + let authorized = *keyed_account.unsigned_key(); keyed_account .initialize_nonce_account(&authorized, &recent_blockhashes, &rent) .unwrap(); @@ -349,7 +349,7 @@ mod test { let mut signers = HashSet::new(); signers.insert(keyed_account.signer_key().unwrap().clone()); let recent_blockhashes = create_test_recent_blockhashes(63); - let authorized = keyed_account.unsigned_key().clone(); + let authorized = *keyed_account.unsigned_key(); keyed_account .initialize_nonce_account(&authorized, &recent_blockhashes, &rent) .unwrap(); @@ -386,7 +386,7 @@ mod test { let mut signers = HashSet::new(); signers.insert(nonce_account.signer_key().unwrap().clone()); let recent_blockhashes = create_test_recent_blockhashes(63); - let authorized = nonce_authority.unsigned_key().clone(); + let authorized = *nonce_authority.unsigned_key(); nonce_account .initialize_nonce_account(&authorized, &recent_blockhashes, &rent) .unwrap(); @@ -411,7 +411,7 @@ mod test { let mut signers = HashSet::new(); signers.insert(nonce_account.signer_key().unwrap().clone()); let recent_blockhashes = create_test_recent_blockhashes(63); - let authorized = nonce_authority.unsigned_key().clone(); + let authorized = *nonce_authority.unsigned_key(); nonce_account .initialize_nonce_account(&authorized, &recent_blockhashes, &rent) .unwrap(); @@ -586,7 +586,7 @@ mod test { let mut signers = HashSet::new(); signers.insert(nonce_keyed.signer_key().unwrap().clone()); let recent_blockhashes = create_test_recent_blockhashes(31); - let authority = nonce_keyed.unsigned_key().clone(); + let authority = *nonce_keyed.unsigned_key(); nonce_keyed .initialize_nonce_account(&authority, &recent_blockhashes, &rent) .unwrap(); @@ -653,7 +653,7 @@ mod test { let min_lamports = rent.minimum_balance(State::size()); with_test_keyed_account(min_lamports + 42, true, |nonce_keyed| { let recent_blockhashes = create_test_recent_blockhashes(0); - let authorized = nonce_keyed.unsigned_key().clone(); + let authorized = *nonce_keyed.unsigned_key(); nonce_keyed .initialize_nonce_account(&authorized, &recent_blockhashes, &rent) .unwrap(); @@ -682,7 +682,7 @@ mod test { let min_lamports = rent.minimum_balance(State::size()); with_test_keyed_account(min_lamports + 42, true, |nonce_keyed| { let recent_blockhashes = create_test_recent_blockhashes(95); - let authorized = nonce_keyed.unsigned_key().clone(); + let authorized = *nonce_keyed.unsigned_key(); nonce_keyed .initialize_nonce_account(&authorized, &recent_blockhashes, &rent) .unwrap(); @@ -712,7 +712,7 @@ mod test { let min_lamports = rent.minimum_balance(State::size()); with_test_keyed_account(min_lamports + 42, true, |nonce_keyed| { let recent_blockhashes = create_test_recent_blockhashes(95); - let authorized = nonce_keyed.unsigned_key().clone(); + let authorized = *nonce_keyed.unsigned_key(); nonce_keyed .initialize_nonce_account(&authorized, &recent_blockhashes, &rent) .unwrap(); @@ -748,7 +748,7 @@ mod test { let mut signers = HashSet::new(); signers.insert(keyed_account.signer_key().unwrap().clone()); let recent_blockhashes = create_test_recent_blockhashes(0); - let authority = keyed_account.unsigned_key().clone(); + let authority = *keyed_account.unsigned_key(); let result = keyed_account.initialize_nonce_account(&authority, &recent_blockhashes, &rent); let data = nonce::state::Data { @@ -775,7 +775,7 @@ mod test { let mut signers = HashSet::new(); signers.insert(keyed_account.signer_key().unwrap().clone()); let recent_blockhashes = RecentBlockhashes::from_iter(vec![].into_iter()); - let authorized = keyed_account.unsigned_key().clone(); + let authorized = *keyed_account.unsigned_key(); let result = keyed_account.initialize_nonce_account(&authorized, &recent_blockhashes, &rent); assert_eq!(result, Err(NonceError::NoRecentBlockhashes.into())); @@ -791,7 +791,7 @@ mod test { let min_lamports = rent.minimum_balance(State::size()); with_test_keyed_account(min_lamports + 42, true, |keyed_account| { let recent_blockhashes = create_test_recent_blockhashes(31); - let authorized = keyed_account.unsigned_key().clone(); + let authorized = *keyed_account.unsigned_key(); keyed_account .initialize_nonce_account(&authorized, &recent_blockhashes, &rent) .unwrap(); @@ -811,7 +811,7 @@ mod test { let min_lamports = rent.minimum_balance(State::size()); with_test_keyed_account(min_lamports - 42, true, |keyed_account| { let recent_blockhashes = create_test_recent_blockhashes(63); - let authorized = keyed_account.unsigned_key().clone(); + let authorized = *keyed_account.unsigned_key(); let result = keyed_account.initialize_nonce_account(&authorized, &recent_blockhashes, &rent); assert_eq!(result, Err(InstructionError::InsufficientFunds)); @@ -829,7 +829,7 @@ mod test { let mut signers = HashSet::new(); signers.insert(nonce_account.signer_key().unwrap().clone()); let recent_blockhashes = create_test_recent_blockhashes(31); - let authorized = nonce_account.unsigned_key().clone(); + let authorized = *nonce_account.unsigned_key(); nonce_account .initialize_nonce_account(&authorized, &recent_blockhashes, &rent) .unwrap(); diff --git a/sdk/src/signature.rs b/sdk/src/signature.rs index c5f25ac2790bf5..7ccd72117876a7 100644 --- a/sdk/src/signature.rs +++ b/sdk/src/signature.rs @@ -396,7 +396,7 @@ mod tests { let out_dir = env::var("FARF_DIR").unwrap_or_else(|_| "farf".to_string()); let keypair = Keypair::new(); - format!("{}/tmp/{}-{}", out_dir, name, keypair.pubkey()).to_string() + format!("{}/tmp/{}-{}", out_dir, name, keypair.pubkey()) } #[test] diff --git a/sdk/src/signers.rs b/sdk/src/signers.rs index 91323c286364f6..667d61acee6b70 100644 --- a/sdk/src/signers.rs +++ b/sdk/src/signers.rs @@ -141,6 +141,7 @@ mod tests { } #[test] + #[allow(clippy::blacklisted_name)] fn test_dyn_keypairs_by_ref_compile() { let foo = Foo {}; let bar = Bar {}; diff --git a/sdk/src/sysvar/recent_blockhashes.rs b/sdk/src/sysvar/recent_blockhashes.rs index 3d44c577da2493..f055eefb9adb47 100644 --- a/sdk/src/sysvar/recent_blockhashes.rs +++ b/sdk/src/sysvar/recent_blockhashes.rs @@ -167,6 +167,7 @@ mod tests { use rand::thread_rng; #[test] + #[allow(clippy::assertions_on_constants)] fn test_sysvar_can_hold_all_active_blockhashes() { // Ensure we can still hold all of the active entries in `BlockhashQueue` assert!(MAX_PROCESSING_AGE <= MAX_ENTRIES); diff --git a/sdk/src/timing.rs b/sdk/src/timing.rs index 9b0bb0e6bd2ae9..de717facb60f96 100644 --- a/sdk/src/timing.rs +++ b/sdk/src/timing.rs @@ -52,6 +52,7 @@ mod test { use super::*; #[test] + #[allow(clippy::float_cmp)] fn test_years_as_slots() { let tick_duration = Duration::from_micros(1000 * 1000 / 160); diff --git a/sdk/src/transaction.rs b/sdk/src/transaction.rs index ff3f6168c6aab1..de50d07231c703 100644 --- a/sdk/src/transaction.rs +++ b/sdk/src/transaction.rs @@ -526,7 +526,7 @@ mod tests { tx.message.account_keys.resize(4, Pubkey::default()); assert_eq!(tx.sanitize(), Err(SanitizeError::IndexOutOfBounds)); - tx = o.clone(); + tx = o; tx.message.header.num_readonly_signed_accounts = 2; tx.message.header.num_required_signatures = 1; assert_eq!(tx.sanitize(), Err(SanitizeError::IndexOutOfBounds)); diff --git a/stake-accounts/src/stake_accounts.rs b/stake-accounts/src/stake_accounts.rs index bafafd81fab743..5e70b2bb3e6d84 100644 --- a/stake-accounts/src/stake_accounts.rs +++ b/stake-accounts/src/stake_accounts.rs @@ -315,7 +315,6 @@ mod tests { num_accounts: usize, ) -> Vec<(Pubkey, u64)> { (0..num_accounts) - .into_iter() .map(|i| { let address = derive_stake_account_address(&base_pubkey, i); (address, client.get_balance(&address).unwrap()) @@ -329,7 +328,6 @@ mod tests { num_accounts: usize, ) -> Vec<(Pubkey, Lockup)> { (0..num_accounts) - .into_iter() .map(|i| { let address = derive_stake_account_address(&base_pubkey, i); let account = client.get_account(&address).unwrap().unwrap(); diff --git a/streamer/src/packet.rs b/streamer/src/packet.rs index 21ddb0838310f2..1fda96834cba44 100644 --- a/streamer/src/packet.rs +++ b/streamer/src/packet.rs @@ -76,7 +76,7 @@ mod tests { let packets = vec![Packet::default()]; let mut msgs = Packets::new(packets); msgs.set_addr(&send_addr); - assert_eq!(SocketAddr::from(msgs.packets[0].meta.addr()), send_addr); + assert_eq!(msgs.packets[0].meta.addr(), send_addr); } #[test] diff --git a/streamer/src/recvmmsg.rs b/streamer/src/recvmmsg.rs index 520003413e6799..b30e6e376acadc 100644 --- a/streamer/src/recvmmsg.rs +++ b/streamer/src/recvmmsg.rs @@ -107,9 +107,9 @@ mod tests { let mut packets = vec![Packet::default(); TEST_NUM_MSGS]; let recv = recv_mmsg(&reader, &mut packets[..]).unwrap().1; assert_eq!(sent, recv); - for i in 0..recv { - assert_eq!(packets[i].meta.size, PACKET_DATA_SIZE); - assert_eq!(packets[i].meta.addr(), saddr); + for packet in packets.iter().take(recv) { + assert_eq!(packet.meta.size, PACKET_DATA_SIZE); + assert_eq!(packet.meta.addr(), saddr); } } @@ -128,16 +128,16 @@ mod tests { let mut packets = vec![Packet::default(); TEST_NUM_MSGS]; let recv = recv_mmsg(&reader, &mut packets[..]).unwrap().1; assert_eq!(TEST_NUM_MSGS, recv); - for i in 0..recv { - assert_eq!(packets[i].meta.size, PACKET_DATA_SIZE); - assert_eq!(packets[i].meta.addr(), saddr); + for packet in packets.iter().take(recv) { + assert_eq!(packet.meta.size, PACKET_DATA_SIZE); + assert_eq!(packet.meta.addr(), saddr); } let recv = recv_mmsg(&reader, &mut packets[..]).unwrap().1; assert_eq!(sent - TEST_NUM_MSGS, recv); - for i in 0..recv { - assert_eq!(packets[i].meta.size, PACKET_DATA_SIZE); - assert_eq!(packets[i].meta.addr(), saddr); + for packet in packets.iter().take(recv) { + assert_eq!(packet.meta.size, PACKET_DATA_SIZE); + assert_eq!(packet.meta.addr(), saddr); } } @@ -159,9 +159,9 @@ mod tests { let mut packets = vec![Packet::default(); TEST_NUM_MSGS]; let recv = recv_mmsg(&reader, &mut packets[..]).unwrap().1; assert_eq!(TEST_NUM_MSGS, recv); - for i in 0..recv { - assert_eq!(packets[i].meta.size, PACKET_DATA_SIZE); - assert_eq!(packets[i].meta.addr(), saddr); + for packet in packets.iter().take(recv) { + assert_eq!(packet.meta.size, PACKET_DATA_SIZE); + assert_eq!(packet.meta.addr(), saddr); } reader.set_nonblocking(true).unwrap(); @@ -196,21 +196,20 @@ mod tests { let recv = recv_mmsg(&reader, &mut packets[..]).unwrap().1; assert_eq!(TEST_NUM_MSGS, recv); - for i in 0..sent1 { - assert_eq!(packets[i].meta.size, PACKET_DATA_SIZE); - assert_eq!(packets[i].meta.addr(), saddr1); + for packet in packets.iter().take(sent1) { + assert_eq!(packet.meta.size, PACKET_DATA_SIZE); + assert_eq!(packet.meta.addr(), saddr1); } - - for i in sent1..recv { - assert_eq!(packets[i].meta.size, PACKET_DATA_SIZE); - assert_eq!(packets[i].meta.addr(), saddr2); + for packet in packets.iter().skip(sent1).take(recv - sent1) { + assert_eq!(packet.meta.size, PACKET_DATA_SIZE); + assert_eq!(packet.meta.addr(), saddr2); } let recv = recv_mmsg(&reader, &mut packets[..]).unwrap().1; assert_eq!(sent1 + sent2 - TEST_NUM_MSGS, recv); - for i in 0..recv { - assert_eq!(packets[i].meta.size, PACKET_DATA_SIZE); - assert_eq!(packets[i].meta.addr(), saddr2); + for packet in packets.iter().take(recv) { + assert_eq!(packet.meta.size, PACKET_DATA_SIZE); + assert_eq!(packet.meta.addr(), saddr2); } } } diff --git a/version/src/lib.rs b/version/src/lib.rs index 142266675b14d3..ad769a0167ef51 100644 --- a/version/src/lib.rs +++ b/version/src/lib.rs @@ -63,7 +63,7 @@ mod test { #[test] fn test_compute_commit() { assert_eq!(compute_commit(None), None); - assert_eq!(compute_commit(Some("1234567890")), Some(0x12345678)); + assert_eq!(compute_commit(Some("1234567890")), Some(0x1234_5678)); assert_eq!(compute_commit(Some("HEAD")), None); assert_eq!(compute_commit(Some("garbagein")), None); } diff --git a/vote-signer/src/rpc.rs b/vote-signer/src/rpc.rs index 0450b2cc00ae6b..66e6b7ff9b24a7 100644 --- a/vote-signer/src/rpc.rs +++ b/vote-signer/src/rpc.rs @@ -210,10 +210,10 @@ mod tests { ); let _pk: Pubkey = serde_json::from_value(succ.result).unwrap(); } else { - assert!(false); + panic!(); } } else { - assert!(false); + panic!(); } } @@ -242,10 +242,10 @@ mod tests { assert_eq!(succ.jsonrpc.unwrap(), Version::V2); assert_eq!(succ.id, Id::Num(1)); } else { - assert!(false); + panic!(); } } else { - assert!(false); + panic!(); } } @@ -273,10 +273,10 @@ mod tests { assert_eq!(succ.jsonrpc.unwrap(), Version::V2); assert_eq!(succ.id, Id::Num(1)); } else { - assert!(false); + panic!(); } } else { - assert!(false); + panic!(); } } @@ -305,10 +305,10 @@ mod tests { assert_eq!(succ.jsonrpc.unwrap(), Version::V2); assert_eq!(succ.id, Id::Num(1)); } else { - assert!(false); + panic!(); } } else { - assert!(false); + panic!(); } } @@ -330,7 +330,7 @@ mod tests { let res = io.handle_request_sync(&req.to_string(), meta.clone()); let result: Response = serde_json::from_str(&res.expect("actual response")) .expect("actual response deserialization"); - let mut vote_pubkey = Pubkey::new_rand(); + let vote_pubkey; if let Response::Single(out) = result { if let Output::Success(succ) = out { assert_eq!(succ.jsonrpc.unwrap(), Version::V2); @@ -341,10 +341,10 @@ mod tests { ); vote_pubkey = serde_json::from_value(succ.result).unwrap(); } else { - assert!(false); + panic!(); } } else { - assert!(false); + panic!(); } let req = json!({ @@ -369,10 +369,10 @@ mod tests { let sig: Signature = serde_json::from_value(succ.result).unwrap(); assert_eq!(verify_signature(&sig, &vote_pubkey, msg.as_bytes()), Ok(())); } else { - assert!(false); + panic!(); } } else { - assert!(false); + panic!(); } } @@ -400,10 +400,10 @@ mod tests { assert_eq!(succ.jsonrpc.unwrap(), Version::V2); assert_eq!(succ.id, Id::Num(1)); } else { - assert!(false); + panic!(); } } else { - assert!(false); + panic!(); } } @@ -448,10 +448,10 @@ mod tests { assert_eq!(succ.jsonrpc.unwrap(), Version::V2); assert_eq!(succ.id, Id::Num(1)); } else { - assert!(false); + panic!(); } } else { - assert!(false); + panic!(); } } @@ -489,10 +489,10 @@ mod tests { assert_eq!(succ.jsonrpc.unwrap(), Version::V2); assert_eq!(succ.id, Id::Num(1)); } else { - assert!(false); + panic!(); } } else { - assert!(false); + panic!(); } } }