diff --git a/account-decoder/src/parse_account_data.rs b/account-decoder/src/parse_account_data.rs index 641b4f6db2..2f013d76b3 100644 --- a/account-decoder/src/parse_account_data.rs +++ b/account-decoder/src/parse_account_data.rs @@ -81,7 +81,7 @@ pub fn parse_account_data( ) -> Result { let program_name = PARSABLE_PROGRAM_IDS .get(program_id) - .ok_or_else(|| ParseAccountError::ProgramNotParsable)?; + .ok_or(ParseAccountError::ProgramNotParsable)?; let additional_data = additional_data.unwrap_or_default(); let parsed_json = match program_name { ParsableAccount::Config => serde_json::to_value(parse_config(data, pubkey)?)?, diff --git a/account-decoder/src/parse_sysvar.rs b/account-decoder/src/parse_sysvar.rs index 66c4ff3b3b..af4a39536e 100644 --- a/account-decoder/src/parse_sysvar.rs +++ b/account-decoder/src/parse_sysvar.rs @@ -217,7 +217,6 @@ mod test { account::create_account, fee_calculator::FeeCalculator, hash::Hash, sysvar::recent_blockhashes::IterItem, }; - use std::iter::FromIterator; #[test] fn test_parse_sysvars() { @@ -250,8 +249,9 @@ mod test { let fee_calculator = FeeCalculator { lamports_per_signature: 10, }; - let recent_blockhashes = - RecentBlockhashes::from_iter(vec![IterItem(0, &hash, &fee_calculator)].into_iter()); + let recent_blockhashes: RecentBlockhashes = vec![IterItem(0, &hash, &fee_calculator)] + .into_iter() + .collect(); let recent_blockhashes_sysvar = create_account(&recent_blockhashes, 1); assert_eq!( parse_sysvar( diff --git a/account-decoder/src/parse_vote.rs b/account-decoder/src/parse_vote.rs index 2ff9d4dd13..a14ad70558 100644 --- a/account-decoder/src/parse_vote.rs +++ b/account-decoder/src/parse_vote.rs @@ -130,9 +130,11 @@ mod test { let mut vote_account_data: Vec = vec![0; VoteState::size_of()]; let versioned = VoteStateVersions::Current(Box::new(vote_state)); VoteState::serialize(&versioned, &mut vote_account_data).unwrap(); - let mut expected_vote_state = UiVoteState::default(); - expected_vote_state.node_pubkey = Pubkey::default().to_string(); - expected_vote_state.authorized_withdrawer = Pubkey::default().to_string(); + let expected_vote_state = UiVoteState { + node_pubkey: Pubkey::default().to_string(), + authorized_withdrawer: Pubkey::default().to_string(), + ..UiVoteState::default() + }; assert_eq!( parse_vote(&vote_account_data).unwrap(), VoteAccountType::Vote(expected_vote_state) diff --git a/bench-exchange/src/cli.rs b/bench-exchange/src/cli.rs index 3f115d65f4..21e8f39dbd 100644 --- a/bench-exchange/src/cli.rs +++ b/bench-exchange/src/cli.rs @@ -163,7 +163,8 @@ pub fn build_args<'a, 'b>(version: &'b str) -> App<'a, 'b> { ) } -pub fn extract_args<'a>(matches: &ArgMatches<'a>) -> Config { +#[allow(clippy::field_reassign_with_default)] +pub fn extract_args(matches: &ArgMatches) -> Config { let mut args = Config::default(); args.entrypoint_addr = solana_net_utils::parse_host_port( diff --git a/bench-exchange/tests/bench_exchange.rs b/bench-exchange/tests/bench_exchange.rs index eead441832..7ddcc057d0 100644 --- a/bench-exchange/tests/bench_exchange.rs +++ b/bench-exchange/tests/bench_exchange.rs @@ -22,15 +22,17 @@ fn test_exchange_local_cluster() { const NUM_NODES: usize = 1; - let mut config = Config::default(); - config.identity = Keypair::new(); - config.duration = Duration::from_secs(1); - config.fund_amount = 100_000; - config.threads = 1; - config.transfer_delay = 20; // 15 - config.batch_size = 100; // 1000; - config.chunk_size = 10; // 200; - config.account_groups = 1; // 10; + let config = Config { + identity: Keypair::new(), + duration: Duration::from_secs(1), + fund_amount: 100_000, + threads: 1, + transfer_delay: 20, // 15 + batch_size: 100, // 1000 + chunk_size: 10, // 200 + account_groups: 1, // 10 + ..Config::default() + }; let Config { fund_amount, batch_size, @@ -89,15 +91,18 @@ fn test_exchange_bank_client() { bank.add_builtin("exchange_program", id(), process_instruction); let clients = vec![BankClient::new(bank)]; - let mut config = Config::default(); - config.identity = identity; - config.duration = Duration::from_secs(1); - config.fund_amount = 100_000; - config.threads = 1; - config.transfer_delay = 20; // 0; - config.batch_size = 100; // 1500; - config.chunk_size = 10; // 1500; - config.account_groups = 1; // 50; - - do_bench_exchange(clients, config); + do_bench_exchange( + clients, + Config { + identity, + duration: Duration::from_secs(1), + fund_amount: 100_000, + threads: 1, + transfer_delay: 20, // 0; + batch_size: 100, // 1500; + chunk_size: 10, // 1500; + account_groups: 1, // 50; + ..Config::default() + }, + ); } diff --git a/bench-tps/src/bench.rs b/bench-tps/src/bench.rs index dea4d95076..2a6de392d4 100644 --- a/bench-tps/src/bench.rs +++ b/bench-tps/src/bench.rs @@ -938,10 +938,12 @@ mod tests { let bank = Bank::new(&genesis_config); let client = Arc::new(BankClient::new(bank)); - let mut config = Config::default(); - config.id = id; - config.tx_count = 10; - config.duration = Duration::from_secs(5); + let config = Config { + id, + tx_count: 10, + duration: Duration::from_secs(5), + ..Config::default() + }; let keypair_count = config.tx_count * config.keypair_multiplier; let keypairs = diff --git a/bench-tps/src/cli.rs b/bench-tps/src/cli.rs index d2985bf96c..875490d1e0 100644 --- a/bench-tps/src/cli.rs +++ b/bench-tps/src/cli.rs @@ -196,7 +196,7 @@ pub fn build_args<'a, 'b>(version: &'b str) -> App<'a, 'b> { /// * `matches` - command line arguments parsed by clap /// # Panics /// Panics if there is trouble parsing any of the arguments -pub fn extract_args<'a>(matches: &ArgMatches<'a>) -> Config { +pub fn extract_args(matches: &ArgMatches) -> Config { let mut args = Config::default(); if let Some(addr) = matches.value_of("entrypoint") { diff --git a/bench-tps/tests/bench_tps.rs b/bench-tps/tests/bench_tps.rs index 2152ab4efe..c3b3b046a1 100644 --- a/bench-tps/tests/bench_tps.rs +++ b/bench-tps/tests/bench_tps.rs @@ -60,9 +60,9 @@ fn test_bench_tps_local_cluster(config: Config) { #[test] #[serial] fn test_bench_tps_local_cluster_solana() { - let mut config = Config::default(); - config.tx_count = 100; - config.duration = Duration::from_secs(10); - - test_bench_tps_local_cluster(config); + test_bench_tps_local_cluster(Config { + tx_count: 100, + duration: Duration::from_secs(10), + ..Config::default() + }); } diff --git a/ci/test-checks.sh b/ci/test-checks.sh index 27765400c2..72edb1ae46 100755 --- a/ci/test-checks.sh +++ b/ci/test-checks.sh @@ -56,9 +56,7 @@ _ "$cargo" stable fmt --all -- --check # -Z... is needed because of clippy bug: https://github.com/rust-lang/rust-clippy/issues/4612 # run nightly clippy for `sdk/` as there's a moderate amount of nightly-only code there -_ "$cargo" nightly clippy \ - -Zunstable-options --workspace --all-targets \ - -- --deny=warnings --allow=clippy::stable_sort_primitive +_ "$cargo" nightly clippy -Zunstable-options --workspace --all-targets -- --deny=warnings cargo_audit_ignores=( # failure is officially deprecated/unmaintained @@ -97,9 +95,7 @@ _ scripts/cargo-for-all-lock-files.sh +"$rust_stable" audit "${cargo_audit_ignor cd "$project" _ "$cargo" stable fmt -- --check _ "$cargo" nightly test - _ "$cargo" nightly clippy -- --deny=warnings \ - --allow=clippy::missing_safety_doc \ - --allow=clippy::stable_sort_primitive + _ "$cargo" nightly clippy -- --deny=warnings --allow=clippy::missing_safety_doc ) done } diff --git a/cli-output/src/display.rs b/cli-output/src/display.rs index 2f12c76311..10c74914f2 100644 --- a/cli-output/src/display.rs +++ b/cli-output/src/display.rs @@ -27,7 +27,7 @@ pub fn build_balance_message(lamports: u64, use_lamports_unit: bool, show_unit: // Pretty print a "name value" pub fn println_name_value(name: &str, value: &str) { - let styled_value = if value == "" { + let styled_value = if value.is_empty() { style("(not set)").italic() } else { style(value) @@ -36,7 +36,7 @@ pub fn println_name_value(name: &str, value: &str) { } pub fn writeln_name_value(f: &mut fmt::Formatter, name: &str, value: &str) -> fmt::Result { - let styled_value = if value == "" { + let styled_value = if value.is_empty() { style("(not set)").italic() } else { style(value) diff --git a/cli/src/cli.rs b/cli/src/cli.rs index a908f917ac..fc7518a38e 100644 --- a/cli/src/cli.rs +++ b/cli/src/cli.rs @@ -444,7 +444,7 @@ impl CliConfig<'_> { ) -> (SettingType, String) { settings .into_iter() - .find(|(_, value)| value != "") + .find(|(_, value)| !value.is_empty()) .expect("no nonempty setting") } @@ -502,13 +502,14 @@ impl CliConfig<'_> { } pub fn recent_for_tests() -> Self { - let mut config = Self::default(); - config.commitment = CommitmentConfig::recent(); - config.send_transaction_config = RpcSendTransactionConfig { - skip_preflight: true, - ..RpcSendTransactionConfig::default() - }; - config + Self { + commitment: CommitmentConfig::recent(), + send_transaction_config: RpcSendTransactionConfig { + skip_preflight: true, + ..RpcSendTransactionConfig::default() + }, + ..Self::default() + } } } @@ -995,6 +996,7 @@ fn process_confirm( } } +#[allow(clippy::unnecessary_wraps)] fn process_decode_transaction(transaction: &Transaction) -> ProcessResult { println_transaction(transaction, &None, ""); Ok("".to_string()) @@ -2763,9 +2765,11 @@ mod tests { #[allow(clippy::cognitive_complexity)] fn test_cli_process_command() { // Success cases - let mut config = CliConfig::default(); - config.rpc_client = Some(RpcClient::new_mock("succeeds".to_string())); - config.json_rpc_url = "http://127.0.0.1:8899".to_string(); + let mut config = CliConfig { + rpc_client: Some(RpcClient::new_mock("succeeds".to_string())), + json_rpc_url: "http://127.0.0.1:8899".to_string(), + ..CliConfig::default() + }; let keypair = Keypair::new(); let pubkey = keypair.pubkey().to_string(); diff --git a/cli/tests/stake.rs b/cli/tests/stake.rs index 39b1624cf6..e5187c3c85 100644 --- a/cli/tests/stake.rs +++ b/cli/tests/stake.rs @@ -1097,8 +1097,10 @@ fn test_stake_set_lockup() { let stake_keypair = keypair_from_seed(&[0u8; 32]).unwrap(); let stake_account_pubkey = stake_keypair.pubkey(); - let mut lockup = Lockup::default(); - lockup.custodian = config.signers[0].pubkey(); + let lockup = Lockup { + custodian: config.signers[0].pubkey(), + ..Lockup::default() + }; config.signers.push(&stake_keypair); config.command = CliCommand::CreateStakeAccount { diff --git a/core/src/banking_stage.rs b/core/src/banking_stage.rs index 4e0f91edee..3aa6f5f0c6 100644 --- a/core/src/banking_stage.rs +++ b/core/src/banking_stage.rs @@ -1171,8 +1171,10 @@ mod tests { Blockstore::open(&ledger_path) .expect("Expected to be able to open database ledger"), ); - let mut poh_config = PohConfig::default(); - poh_config.target_tick_count = Some(bank.max_tick_height() + num_extra_ticks); + let poh_config = PohConfig { + target_tick_count: Some(bank.max_tick_height() + num_extra_ticks), + ..PohConfig::default() + }; let (exit, poh_recorder, poh_service, entry_receiver) = create_test_recorder(&bank, &blockstore, Some(poh_config)); let cluster_info = ClusterInfo::new_with_invalid_keypair(Node::new_localhost().info); @@ -1236,9 +1238,12 @@ mod tests { Blockstore::open(&ledger_path) .expect("Expected to be able to open database ledger"), ); - let mut poh_config = PohConfig::default(); - // limit tick count to avoid clearing working_bank at PohRecord then PohRecorderError(MaxHeightReached) at BankingStage - poh_config.target_tick_count = Some(bank.max_tick_height() - 1); + let poh_config = PohConfig { + // limit tick count to avoid clearing working_bank at PohRecord then + // PohRecorderError(MaxHeightReached) at BankingStage + target_tick_count: Some(bank.max_tick_height() - 1), + ..PohConfig::default() + }; let (exit, poh_recorder, poh_service, entry_receiver) = create_test_recorder(&bank, &blockstore, Some(poh_config)); let cluster_info = ClusterInfo::new_with_invalid_keypair(Node::new_localhost().info); @@ -1381,9 +1386,12 @@ mod tests { Blockstore::open(&ledger_path) .expect("Expected to be able to open database ledger"), ); - let mut poh_config = PohConfig::default(); - // limit tick count to avoid clearing working_bank at PohRecord then PohRecorderError(MaxHeightReached) at BankingStage - poh_config.target_tick_count = Some(bank.max_tick_height() - 1); + let poh_config = PohConfig { + // limit tick count to avoid clearing working_bank at + // PohRecord then PohRecorderError(MaxHeightReached) at BankingStage + target_tick_count: Some(bank.max_tick_height() - 1), + ..PohConfig::default() + }; let (exit, poh_recorder, poh_service, entry_receiver) = create_test_recorder(&bank, &blockstore, Some(poh_config)); let cluster_info = @@ -1973,7 +1981,7 @@ mod tests { assert_eq!(processed_transactions_count, 0,); - retryable_txs.sort(); + retryable_txs.sort_unstable(); let expected: Vec = (0..transactions.len()).collect(); assert_eq!(retryable_txs, expected); } diff --git a/core/src/broadcast_stage.rs b/core/src/broadcast_stage.rs index b62feb27ff..d76cb8c125 100644 --- a/core/src/broadcast_stage.rs +++ b/core/src/broadcast_stage.rs @@ -1,4 +1,5 @@ //! A stage to broadcast data from a leader node to validators +#![allow(clippy::rc_buffer)] use self::{ broadcast_fake_shreds_run::BroadcastFakeShredsRun, broadcast_metrics::*, fail_entry_verification_broadcast_run::FailEntryVerificationBroadcastRun, @@ -518,8 +519,10 @@ pub mod test { #[test] fn test_num_live_peers() { - let mut ci = ContactInfo::default(); - ci.wallclock = std::u64::MAX; + let mut ci = ContactInfo { + wallclock: std::u64::MAX, + ..ContactInfo::default() + }; assert_eq!(num_live_peers(&[ci.clone()]), 1); ci.wallclock = timestamp() - 1; assert_eq!(num_live_peers(&[ci.clone()]), 2); diff --git a/core/src/broadcast_stage/broadcast_metrics.rs b/core/src/broadcast_stage/broadcast_metrics.rs index 64f6ef49e2..b29ace0791 100644 --- a/core/src/broadcast_stage/broadcast_metrics.rs +++ b/core/src/broadcast_stage/broadcast_metrics.rs @@ -270,10 +270,9 @@ mod test { } assert!(slot_broadcast_stats.lock().unwrap().0.get(&slot).is_none()); - let (returned_count, returned_slot, returned_instant) = receiver.recv().unwrap(); + let (returned_count, returned_slot, _returned_instant) = receiver.recv().unwrap(); assert_eq!(returned_count, num_threads); assert_eq!(returned_slot, slot); - assert_eq!(returned_instant, returned_instant); } } } diff --git a/core/src/broadcast_stage/standard_broadcast_run.rs b/core/src/broadcast_stage/standard_broadcast_run.rs index 40756bbcd7..e78626db64 100644 --- a/core/src/broadcast_stage/standard_broadcast_run.rs +++ b/core/src/broadcast_stage/standard_broadcast_run.rs @@ -1,3 +1,5 @@ +#![allow(clippy::rc_buffer)] + use super::{ broadcast_utils::{self, ReceiveResults}, *, @@ -284,7 +286,7 @@ impl StandardBroadcastRun { blockstore: &Arc, shreds: Arc>, broadcast_shred_batch_info: Option, - ) -> Result<()> { + ) { // Insert shreds into blockstore let insert_shreds_start = Instant::now(); // The first shred is inserted synchronously @@ -302,7 +304,6 @@ impl StandardBroadcastRun { num_shreds: shreds.len(), }; self.update_insertion_metrics(&new_insert_shreds_stats, &broadcast_shred_batch_info); - Ok(()) } fn update_insertion_metrics( @@ -438,7 +439,8 @@ impl BroadcastRun for StandardBroadcastRun { blockstore: &Arc, ) -> Result<()> { let (shreds, slot_start_ts) = receiver.lock().unwrap().recv()?; - self.insert(blockstore, shreds, slot_start_ts) + self.insert(blockstore, shreds, slot_start_ts); + Ok(()) } } diff --git a/core/src/cluster_info.rs b/core/src/cluster_info.rs index 5b7046d709..b9beda7fce 100644 --- a/core/src/cluster_info.rs +++ b/core/src/cluster_info.rs @@ -884,7 +884,7 @@ impl ClusterInfo { )) }) .collect(); - current_slots.sort(); + current_slots.sort_unstable(); let min_slot: Slot = current_slots .iter() .map(|((_, s), _)| *s) @@ -4139,8 +4139,10 @@ mod tests { #[test] fn test_protocol_sanitize() { - let mut pd = PruneData::default(); - pd.wallclock = MAX_WALLCLOCK; + let pd = PruneData { + wallclock: MAX_WALLCLOCK, + ..PruneData::default() + }; let msg = Protocol::PruneMessage(Pubkey::default(), pd); assert_eq!(msg.sanitize(), Err(SanitizeError::ValueOutOfBounds)); } diff --git a/core/src/cluster_slots_service.rs b/core/src/cluster_slots_service.rs index 0cd0d02636..6e7a73b312 100644 --- a/core/src/cluster_slots_service.rs +++ b/core/src/cluster_slots_service.rs @@ -125,6 +125,7 @@ impl ClusterSlotsService { while let Ok(mut more) = completed_slots_receiver.try_recv() { slots.append(&mut more); } + #[allow(clippy::stable_sort_primitive)] slots.sort(); if !slots.is_empty() { cluster_info.push_epoch_slots(&slots); @@ -163,7 +164,7 @@ impl ClusterSlotsService { while let Ok(mut more) = completed_slots_receiver.try_recv() { slots.append(&mut more); } - slots.sort(); + slots.sort_unstable(); slots.dedup(); if !slots.is_empty() { cluster_info.push_epoch_slots(&slots); diff --git a/core/src/consensus.rs b/core/src/consensus.rs index 8838e1dcee..bfd9485ec6 100644 --- a/core/src/consensus.rs +++ b/core/src/consensus.rs @@ -1574,9 +1574,11 @@ pub mod test { fn gen_stakes(stake_votes: &[(u64, &[u64])]) -> Vec<(Pubkey, (u64, ArcVoteAccount))> { let mut stakes = vec![]; for (lamports, votes) in stake_votes { - let mut account = Account::default(); - account.data = vec![0; VoteState::size_of()]; - account.lamports = *lamports; + let mut account = Account { + data: vec![0; VoteState::size_of()], + lamports: *lamports, + ..Account::default() + }; let mut vote_state = VoteState::default(); for slot in *votes { vote_state.process_slot_vote_unchecked(*slot); @@ -2059,7 +2061,7 @@ pub mod test { #[test] fn test_check_vote_threshold_without_votes() { let tower = Tower::new_for_tests(1, 0.67); - let stakes = vec![(0, 1 as Stake)].into_iter().collect(); + let stakes = vec![(0, 1)].into_iter().collect(); assert!(tower.check_vote_stake_threshold(0, &stakes, 2)); } @@ -2069,7 +2071,7 @@ pub mod test { let mut tower = Tower::new_for_tests(4, 0.67); let mut stakes = HashMap::new(); for i in 0..(MAX_LOCKOUT_HISTORY as u64 + 1) { - stakes.insert(i, 1 as Stake); + stakes.insert(i, 1); tower.record_vote(i, Hash::default()); } assert!(!tower.check_vote_stake_threshold(MAX_LOCKOUT_HISTORY as u64 + 1, &stakes, 2,)); @@ -2078,7 +2080,7 @@ pub mod test { #[test] fn test_is_slot_confirmed_not_enough_stake_failure() { let tower = Tower::new_for_tests(1, 0.67); - let stakes = vec![(0, 1 as Stake)].into_iter().collect(); + let stakes = vec![(0, 1)].into_iter().collect(); assert!(!tower.is_slot_confirmed(0, &stakes, 2)); } @@ -2092,7 +2094,7 @@ pub mod test { #[test] fn test_is_slot_confirmed_pass() { let tower = Tower::new_for_tests(1, 0.67); - let stakes = vec![(0, 2 as Stake)].into_iter().collect(); + let stakes = vec![(0, 2)].into_iter().collect(); assert!(tower.is_slot_confirmed(0, &stakes, 2)); } @@ -2205,14 +2207,14 @@ pub mod test { #[test] fn test_check_vote_threshold_below_threshold() { let mut tower = Tower::new_for_tests(1, 0.67); - let stakes = vec![(0, 1 as Stake)].into_iter().collect(); + let stakes = vec![(0, 1)].into_iter().collect(); tower.record_vote(0, Hash::default()); assert!(!tower.check_vote_stake_threshold(1, &stakes, 2)); } #[test] fn test_check_vote_threshold_above_threshold() { let mut tower = Tower::new_for_tests(1, 0.67); - let stakes = vec![(0, 2 as Stake)].into_iter().collect(); + let stakes = vec![(0, 2)].into_iter().collect(); tower.record_vote(0, Hash::default()); assert!(tower.check_vote_stake_threshold(1, &stakes, 2)); } @@ -2220,7 +2222,7 @@ pub mod test { #[test] fn test_check_vote_threshold_above_threshold_after_pop() { let mut tower = Tower::new_for_tests(1, 0.67); - let stakes = vec![(0, 2 as Stake)].into_iter().collect(); + let stakes = vec![(0, 2)].into_iter().collect(); tower.record_vote(0, Hash::default()); tower.record_vote(1, Hash::default()); tower.record_vote(2, Hash::default()); @@ -2239,7 +2241,7 @@ pub mod test { fn test_check_vote_threshold_lockouts_not_updated() { solana_logger::setup(); let mut tower = Tower::new_for_tests(1, 0.67); - let stakes = vec![(0, 1 as Stake), (1, 2 as Stake)].into_iter().collect(); + let stakes = vec![(0, 1), (1, 2)].into_iter().collect(); tower.record_vote(0, Hash::default()); tower.record_vote(1, Hash::default()); tower.record_vote(2, Hash::default()); @@ -2249,8 +2251,10 @@ pub mod test { #[test] fn test_stake_is_updated_for_entire_branch() { let mut voted_stakes = HashMap::new(); - let mut account = Account::default(); - account.lamports = 1; + let account = Account { + lamports: 1, + ..Account::default() + }; let set: HashSet = vec![0u64, 1u64].into_iter().collect(); let ancestors: HashMap> = [(2u64, set)].iter().cloned().collect(); Tower::update_ancestor_voted_stakes(&mut voted_stakes, 2, account.lamports, &ancestors); diff --git a/core/src/crds_gossip.rs b/core/src/crds_gossip.rs index a04068d1e4..2ef1650bdb 100644 --- a/core/src/crds_gossip.rs +++ b/core/src/crds_gossip.rs @@ -304,8 +304,10 @@ mod test { #[test] fn test_prune_errors() { - let mut crds_gossip = CrdsGossip::default(); - crds_gossip.id = Pubkey::new(&[0; 32]); + let mut crds_gossip = CrdsGossip { + id: Pubkey::new(&[0; 32]), + ..CrdsGossip::default() + }; let id = crds_gossip.id; let ci = ContactInfo::new_localhost(&Pubkey::new(&[1; 32]), 0); let prune_pubkey = Pubkey::new(&[2; 32]); diff --git a/core/src/crds_gossip_pull.rs b/core/src/crds_gossip_pull.rs index fb92c5386c..1d2a30a312 100644 --- a/core/src/crds_gossip_pull.rs +++ b/core/src/crds_gossip_pull.rs @@ -337,10 +337,7 @@ impl CrdsGossipPull { for r in responses { let owner = r.label().pubkey(); // Check if the crds value is older than the msg_timeout - if now - > r.wallclock() - .checked_add(self.msg_timeout) - .unwrap_or_else(|| 0) + if now > r.wallclock().checked_add(self.msg_timeout).unwrap_or(0) || now + self.msg_timeout < r.wallclock() { match &r.label() { @@ -350,7 +347,7 @@ impl CrdsGossipPull { let timeout = *timeouts .get(&owner) .unwrap_or_else(|| timeouts.get(&Pubkey::default()).unwrap()); - if now > r.wallclock().checked_add(timeout).unwrap_or_else(|| 0) + if now > r.wallclock().checked_add(timeout).unwrap_or(0) || now + timeout < r.wallclock() { stats.timeout_count += 1; diff --git a/core/src/crds_gossip_push.rs b/core/src/crds_gossip_push.rs index d7552eef56..64a09875b3 100644 --- a/core/src/crds_gossip_push.rs +++ b/core/src/crds_gossip_push.rs @@ -175,12 +175,7 @@ impl CrdsGossipPush { now: u64, ) -> Result, CrdsGossipError> { self.num_total += 1; - if now - > value - .wallclock() - .checked_add(self.msg_timeout) - .unwrap_or_else(|| 0) - { + if now > value.wallclock().checked_add(self.msg_timeout).unwrap_or(0) { return Err(CrdsGossipError::PushMessageTimeout); } if now + self.msg_timeout < value.wallclock() { @@ -208,7 +203,7 @@ impl CrdsGossipPush { /// push pull responses pub fn push_pull_responses(&mut self, values: Vec<(CrdsValueLabel, Hash, u64)>, now: u64) { for (label, value_hash, wc) in values { - if now > wc.checked_add(self.msg_timeout).unwrap_or_else(|| 0) { + if now > wc.checked_add(self.msg_timeout).unwrap_or(0) { continue; } self.push_messages.insert(label, value_hash); diff --git a/core/src/epoch_slots.rs b/core/src/epoch_slots.rs index fdcf49f1dc..0ad4857b6f 100644 --- a/core/src/epoch_slots.rs +++ b/core/src/epoch_slots.rs @@ -116,7 +116,7 @@ impl Uncompressed { pub fn to_slots(&self, min_slot: Slot) -> Vec { let mut rv = vec![]; let start = if min_slot < self.first_slot { - 0 as usize + 0 } else { (min_slot - self.first_slot) as usize }; diff --git a/core/src/poh_recorder.rs b/core/src/poh_recorder.rs index c3fd519c7a..b9d556be4e 100644 --- a/core/src/poh_recorder.rs +++ b/core/src/poh_recorder.rs @@ -1228,8 +1228,10 @@ mod tests { init_ticks + bank.ticks_per_slot() ); - let mut parent_meta = SlotMeta::default(); - parent_meta.received = 1; + let parent_meta = SlotMeta { + received: 1, + ..SlotMeta::default() + }; poh_recorder .blockstore .put_meta_bytes(0, &serialize(&parent_meta).unwrap()) diff --git a/core/src/repair_service.rs b/core/src/repair_service.rs index 3dd83a1d24..8fe8ca5135 100644 --- a/core/src/repair_service.rs +++ b/core/src/repair_service.rs @@ -736,7 +736,7 @@ mod test { let num_slots = 2; // Create some shreds - let (mut shreds, _) = make_many_slot_entries(0, num_slots as u64, 150 as u64); + let (mut shreds, _) = make_many_slot_entries(0, num_slots as u64, 150); let num_shreds = shreds.len() as u64; let num_shreds_per_slot = num_shreds / num_slots; @@ -852,9 +852,10 @@ mod test { // sides of the range) for start in 0..slots.len() { for end in start..slots.len() { - let mut repair_slot_range = RepairSlotRange::default(); - repair_slot_range.start = slots[start]; - repair_slot_range.end = slots[end]; + let repair_slot_range = RepairSlotRange { + start: slots[start], + end: slots[end], + }; let expected: Vec = (repair_slot_range.start ..=repair_slot_range.end) .map(|slot_index| { @@ -907,9 +908,7 @@ mod test { RepairType::HighestShred(end, 0), ]; - let mut repair_slot_range = RepairSlotRange::default(); - repair_slot_range.start = 2; - repair_slot_range.end = end; + let repair_slot_range = RepairSlotRange { start: 2, end }; assert_eq!( RepairService::generate_repairs_in_range( diff --git a/core/src/replay_stage.rs b/core/src/replay_stage.rs index 22b34ef04e..94cef77b5f 100644 --- a/core/src/replay_stage.rs +++ b/core/src/replay_stage.rs @@ -455,7 +455,7 @@ impl ReplayStage { &mut heaviest_subtree_fork_choice, &cache_block_time_sender, &bank_notification_sender, - )?; + ); }; voting_time.stop(); @@ -1047,7 +1047,7 @@ impl ReplayStage { heaviest_subtree_fork_choice: &mut HeaviestSubtreeForkChoice, cache_block_time_sender: &Option, bank_notification_sender: &Option, - ) -> Result<()> { + ) { if bank.is_empty() { inc_new_counter_info!("replay_stage-voted_empty_bank", 1); } @@ -1130,7 +1130,6 @@ impl ReplayStage { tower_index, switch_fork_decision, ); - Ok(()) } fn push_vote( diff --git a/core/src/retransmit_stage.rs b/core/src/retransmit_stage.rs index 38f7238117..d73069361b 100644 --- a/core/src/retransmit_stage.rs +++ b/core/src/retransmit_stage.rs @@ -1,4 +1,5 @@ //! The `retransmit_stage` retransmits shreds between validators +#![allow(clippy::rc_buffer)] use crate::shred_fetch_stage::ShredFetchStage; use crate::shred_fetch_stage::ShredFetchStats; diff --git a/core/src/rpc.rs b/core/src/rpc.rs index e53d09577f..a33abe7167 100644 --- a/core/src/rpc.rs +++ b/core/src/rpc.rs @@ -4511,8 +4511,10 @@ pub 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())); - let mut config = JsonRpcConfig::default(); - config.enable_validator_exit = true; + let config = JsonRpcConfig { + enable_validator_exit: true, + ..JsonRpcConfig::default() + }; let bank_forks = new_bank_forks().0; let cluster_info = Arc::new(ClusterInfo::default()); let tpu_address = cluster_info.my_contact_info().tpu; @@ -4601,8 +4603,10 @@ pub mod tests { CommitmentSlots::new_from_slot(bank_forks.read().unwrap().highest_slot()), ))); - let mut config = JsonRpcConfig::default(); - config.enable_validator_exit = true; + let config = JsonRpcConfig { + enable_validator_exit: true, + ..JsonRpcConfig::default() + }; let cluster_info = Arc::new(ClusterInfo::default()); let tpu_address = cluster_info.my_contact_info().tpu; let (request_processor, receiver) = JsonRpcRequestProcessor::new( diff --git a/core/src/rpc_pubsub.rs b/core/src/rpc_pubsub.rs index 574a1bb832..35b1ff3a5b 100644 --- a/core/src/rpc_pubsub.rs +++ b/core/src/rpc_pubsub.rs @@ -534,8 +534,10 @@ mod tests { .get(current_slot) .unwrap() .process_transaction(tx)?; - let mut commitment_slots = CommitmentSlots::default(); - commitment_slots.slot = current_slot; + let commitment_slots = CommitmentSlots { + slot: current_slot, + ..CommitmentSlots::default() + }; subscriptions.notify_subscribers(commitment_slots); Ok(()) } @@ -1018,8 +1020,10 @@ mod tests { .unwrap() .process_transaction(&tx) .unwrap(); - let mut commitment_slots = CommitmentSlots::default(); - commitment_slots.slot = 1; + let commitment_slots = CommitmentSlots { + slot: 1, + ..CommitmentSlots::default() + }; rpc.subscriptions.notify_subscribers(commitment_slots); let commitment_slots = CommitmentSlots { diff --git a/core/src/rpc_subscriptions.rs b/core/src/rpc_subscriptions.rs index 9329cf8e13..d3085f00e5 100644 --- a/core/src/rpc_subscriptions.rs +++ b/core/src/rpc_subscriptions.rs @@ -973,7 +973,7 @@ impl RpcSubscriptions { } pub fn notify_roots(&self, mut rooted_slots: Vec) { - rooted_slots.sort(); + rooted_slots.sort_unstable(); rooted_slots.into_iter().for_each(|root| { self.enqueue_notification(NotificationEntry::Root(root)); }); @@ -1359,8 +1359,8 @@ pub(crate) mod tests { let (create_sub, _id_receiver, create_recv) = Subscriber::new_test("accountNotification"); let (close_sub, _id_receiver, close_recv) = Subscriber::new_test("accountNotification"); - let create_sub_id = SubscriptionId::Number(0 as u64); - let close_sub_id = SubscriptionId::Number(1 as u64); + let create_sub_id = SubscriptionId::Number(0); + let close_sub_id = SubscriptionId::Number(1); let exit = Arc::new(AtomicBool::new(false)); let subscriptions = RpcSubscriptions::new( @@ -1404,8 +1404,10 @@ pub(crate) mod tests { .unwrap() .process_transaction(&tx) .unwrap(); - let mut commitment_slots = CommitmentSlots::default(); - commitment_slots.slot = 1; + let commitment_slots = CommitmentSlots { + slot: 1, + ..CommitmentSlots::default() + }; subscriptions.notify_subscribers(commitment_slots); let (response, _) = robust_poll_or_panic(create_recv); let expected = json!({ @@ -1513,7 +1515,7 @@ pub(crate) mod tests { let (subscriber, _id_receiver, transport_receiver) = Subscriber::new_test("programNotification"); - let sub_id = SubscriptionId::Number(0 as u64); + let sub_id = SubscriptionId::Number(0); let exit = Arc::new(AtomicBool::new(false)); let optimistically_confirmed_bank = OptimisticallyConfirmedBank::locked_from_bank_forks_root(&bank_forks); @@ -1659,7 +1661,7 @@ pub(crate) mod tests { commitment: Some(CommitmentConfig::recent()), enable_received_notification: Some(false), }), - SubscriptionId::Number(1 as u64), + SubscriptionId::Number(1), past_bank_sub1, ); subscriptions.add_signature_subscription( @@ -1668,7 +1670,7 @@ pub(crate) mod tests { commitment: Some(CommitmentConfig::root()), enable_received_notification: Some(false), }), - SubscriptionId::Number(2 as u64), + SubscriptionId::Number(2), past_bank_sub2, ); subscriptions.add_signature_subscription( @@ -1677,7 +1679,7 @@ pub(crate) mod tests { commitment: Some(CommitmentConfig::recent()), enable_received_notification: Some(false), }), - SubscriptionId::Number(3 as u64), + SubscriptionId::Number(3), processed_sub, ); subscriptions.add_signature_subscription( @@ -1686,7 +1688,7 @@ pub(crate) mod tests { commitment: Some(CommitmentConfig::recent()), enable_received_notification: Some(false), }), - SubscriptionId::Number(4 as u64), + SubscriptionId::Number(4), Subscriber::new_test("signatureNotification").0, ); // Add a subscription that gets `received` notifications @@ -1696,7 +1698,7 @@ pub(crate) mod tests { commitment: Some(CommitmentConfig::recent()), enable_received_notification: Some(true), }), - SubscriptionId::Number(5 as u64), + SubscriptionId::Number(5), processed_sub3, ); @@ -1789,7 +1791,7 @@ pub(crate) mod tests { fn test_check_slot_subscribe() { let (subscriber, _id_receiver, transport_receiver) = Subscriber::new_test("slotNotification"); - let sub_id = SubscriptionId::Number(0 as u64); + let sub_id = SubscriptionId::Number(0); let exit = Arc::new(AtomicBool::new(false)); let GenesisConfigInfo { genesis_config, .. } = create_genesis_config(10_000); let bank = Bank::new(&genesis_config); @@ -1840,7 +1842,7 @@ pub(crate) mod tests { fn test_check_root_subscribe() { let (subscriber, _id_receiver, mut transport_receiver) = Subscriber::new_test("rootNotification"); - let sub_id = SubscriptionId::Number(0 as u64); + let sub_id = SubscriptionId::Number(0); let exit = Arc::new(AtomicBool::new(false)); let GenesisConfigInfo { genesis_config, .. } = create_genesis_config(10_000); let bank = Bank::new(&genesis_config); @@ -1976,7 +1978,7 @@ pub(crate) mod tests { ))), optimistically_confirmed_bank.clone(), )); - let sub_id0 = SubscriptionId::Number(0 as u64); + let sub_id0 = SubscriptionId::Number(0); subscriptions.add_account_subscription( alice.pubkey(), Some(RpcAccountInfoConfig { @@ -2057,7 +2059,7 @@ pub(crate) mod tests { assert_eq!(serde_json::to_string(&expected).unwrap(), response); subscriptions.remove_account_subscription(&sub_id0); - let sub_id1 = SubscriptionId::Number(1 as u64); + let sub_id1 = SubscriptionId::Number(1); subscriptions.add_account_subscription( alice.pubkey(), Some(RpcAccountInfoConfig { diff --git a/core/src/serve_repair.rs b/core/src/serve_repair.rs index 6772981cd4..756077a8b5 100644 --- a/core/src/serve_repair.rs +++ b/core/src/serve_repair.rs @@ -708,11 +708,15 @@ mod tests { nonce, ); assert!(rv.is_none()); - let mut common_header = ShredCommonHeader::default(); - common_header.slot = slot; - common_header.index = 1; - let mut data_header = DataShredHeader::default(); - data_header.parent_offset = 1; + let common_header = ShredCommonHeader { + slot, + index: 1, + ..ShredCommonHeader::default() + }; + let data_header = DataShredHeader { + parent_offset: 1, + ..DataShredHeader::default() + }; let shred_info = Shred::new_empty_from_header( common_header, data_header, diff --git a/core/src/verified_vote_packets.rs b/core/src/verified_vote_packets.rs index 280ddcaa8a..4a975a3106 100644 --- a/core/src/verified_vote_packets.rs +++ b/core/src/verified_vote_packets.rs @@ -63,8 +63,8 @@ mod tests { #[test] fn test_get_latest_votes() { let pubkey = solana_sdk::pubkey::new_rand(); - let label1 = CrdsValueLabel::Vote(0 as u8, pubkey); - let label2 = CrdsValueLabel::Vote(1 as u8, pubkey); + let label1 = CrdsValueLabel::Vote(0, pubkey); + let label2 = CrdsValueLabel::Vote(1, pubkey); let mut verified_vote_packets = VerifiedVotePackets(HashMap::new()); let data = Packet { @@ -107,8 +107,8 @@ mod tests { fn test_get_and_process_vote_packets() { let (s, r) = unbounded(); let pubkey = solana_sdk::pubkey::new_rand(); - let label1 = CrdsValueLabel::Vote(0 as u8, pubkey); - let label2 = CrdsValueLabel::Vote(1 as u8, pubkey); + let label1 = CrdsValueLabel::Vote(0, pubkey); + let label2 = CrdsValueLabel::Vote(1, pubkey); let mut update_version = 0; s.send(vec![(label1.clone(), Packets::default())]).unwrap(); s.send(vec![(label2.clone(), Packets::default())]).unwrap(); diff --git a/core/tests/crds_gossip.rs b/core/tests/crds_gossip.rs index 6a3167a0e5..e6c7eadc70 100644 --- a/core/tests/crds_gossip.rs +++ b/core/tests/crds_gossip.rs @@ -624,8 +624,10 @@ fn test_star_network_large_push() { } #[test] fn test_prune_errors() { - let mut crds_gossip = CrdsGossip::default(); - crds_gossip.id = Pubkey::new(&[0; 32]); + let mut crds_gossip = CrdsGossip { + id: Pubkey::new(&[0; 32]), + ..CrdsGossip::default() + }; let id = crds_gossip.id; let ci = ContactInfo::new_localhost(&Pubkey::new(&[1; 32]), 0); let prune_pubkey = Pubkey::new(&[2; 32]); diff --git a/core/tests/fork-selection.rs b/core/tests/fork-selection.rs index 01acb7dd97..8cf3d8b20d 100644 --- a/core/tests/fork-selection.rs +++ b/core/tests/fork-selection.rs @@ -190,7 +190,7 @@ impl Tower { .map(|(i, v)| (*scores.get(&v).unwrap_or(&0), v.time, i)) .collect(); // highest score, latest vote first - best.sort(); + best.sort_unstable(); if self.parasite { best.reverse(); } diff --git a/core/tests/rpc.rs b/core/tests/rpc.rs index cfb58953e2..836da654c5 100644 --- a/core/tests/rpc.rs +++ b/core/tests/rpc.rs @@ -284,8 +284,7 @@ fn test_rpc_subscriptions() { } } Err(_err) => { - assert!( - false, + panic!( "recv_timeout, {}/{} signatures remaining", signature_set.len(), transactions.len() @@ -304,8 +303,7 @@ fn test_rpc_subscriptions() { account_notifications -= 1; } Err(_err) => { - assert!( - false, + panic!( "recv_timeout, {}/{} accounts remaining", account_notifications, transactions.len() diff --git a/faucet/src/bin/faucet.rs b/faucet/src/bin/faucet.rs index 7b982e58c4..dac98a2bdb 100644 --- a/faucet/src/bin/faucet.rs +++ b/faucet/src/bin/faucet.rs @@ -6,13 +6,12 @@ use solana_faucet::{ }; use solana_sdk::signature::read_keypair_file; use std::{ - error, net::{Ipv4Addr, SocketAddr}, sync::{Arc, Mutex}, thread, }; -fn main() -> Result<(), Box> { +fn main() { let default_keypair = solana_cli_config::Config::default().keypair_path; solana_logger::setup_with_default("solana=info"); @@ -78,5 +77,4 @@ fn main() -> Result<(), Box> { }); run_faucet(faucet, faucet_addr, None); - Ok(()) } diff --git a/frozen-abi/src/abi_digester.rs b/frozen-abi/src/abi_digester.rs index 3caa77d593..7365d195b8 100644 --- a/frozen-abi/src/abi_digester.rs +++ b/frozen-abi/src/abi_digester.rs @@ -137,6 +137,7 @@ impl AbiDigester { self.update(&[&label]); } + #[allow(clippy::unnecessary_wraps)] fn digest_primitive(mut self) -> Result { self.update_with_type::("primitive"); Ok(self) @@ -164,6 +165,7 @@ impl AbiDigester { self.create_child().digest_data(v).map(|_| ()) } + #[allow(clippy::unnecessary_wraps)] fn check_for_enum( &mut self, label: &'static str, diff --git a/genesis/src/main.rs b/genesis/src/main.rs index 5387142b14..ee129c5384 100644 --- a/genesis/src/main.rs +++ b/genesis/src/main.rs @@ -443,11 +443,13 @@ fn main() -> Result<(), Box> { ); fee_rate_governor.burn_percent = value_t_or_exit!(matches, "fee_burn_percentage", u8); - let mut poh_config = PohConfig::default(); - poh_config.target_tick_duration = if matches.is_present("target_tick_duration") { - Duration::from_micros(value_t_or_exit!(matches, "target_tick_duration", u64)) - } else { - Duration::from_micros(default_target_tick_duration) + let mut poh_config = PohConfig { + target_tick_duration: if matches.is_present("target_tick_duration") { + Duration::from_micros(value_t_or_exit!(matches, "target_tick_duration", u64)) + } else { + Duration::from_micros(default_target_tick_duration) + }, + ..PohConfig::default() }; let cluster_type = cluster_type_of(&matches, "cluster_type").unwrap(); @@ -663,7 +665,7 @@ mod tests { solana_sdk::pubkey::new_rand().to_string(), Base64Account { owner: solana_sdk::pubkey::new_rand().to_string(), - balance: 2 as u64, + balance: 2, executable: false, data: String::from("aGVsbG8="), }, @@ -672,7 +674,7 @@ mod tests { solana_sdk::pubkey::new_rand().to_string(), Base64Account { owner: solana_sdk::pubkey::new_rand().to_string(), - balance: 1 as u64, + balance: 1, executable: true, data: String::from("aGVsbG8gd29ybGQ="), }, @@ -681,7 +683,7 @@ mod tests { solana_sdk::pubkey::new_rand().to_string(), Base64Account { owner: solana_sdk::pubkey::new_rand().to_string(), - balance: 3 as u64, + balance: 3, executable: true, data: String::from("bWUgaGVsbG8gdG8gd29ybGQ="), }, @@ -736,7 +738,7 @@ mod tests { solana_sdk::pubkey::new_rand().to_string(), Base64Account { owner: solana_sdk::pubkey::new_rand().to_string(), - balance: 6 as u64, + balance: 6, executable: true, data: String::from("eW91IGFyZQ=="), }, @@ -745,7 +747,7 @@ mod tests { solana_sdk::pubkey::new_rand().to_string(), Base64Account { owner: solana_sdk::pubkey::new_rand().to_string(), - balance: 5 as u64, + balance: 5, executable: false, data: String::from("bWV0YSBzdHJpbmc="), }, @@ -754,7 +756,7 @@ mod tests { solana_sdk::pubkey::new_rand().to_string(), Base64Account { owner: solana_sdk::pubkey::new_rand().to_string(), - balance: 10 as u64, + balance: 10, executable: false, data: String::from("YmFzZTY0IHN0cmluZw=="), }, @@ -819,7 +821,7 @@ mod tests { serde_json::to_string(&account_keypairs[0].to_bytes().to_vec()).unwrap(), Base64Account { owner: solana_sdk::pubkey::new_rand().to_string(), - balance: 20 as u64, + balance: 20, executable: true, data: String::from("Y2F0IGRvZw=="), }, @@ -828,7 +830,7 @@ mod tests { serde_json::to_string(&account_keypairs[1].to_bytes().to_vec()).unwrap(), Base64Account { owner: solana_sdk::pubkey::new_rand().to_string(), - balance: 15 as u64, + balance: 15, executable: false, data: String::from("bW9ua2V5IGVsZXBoYW50"), }, @@ -837,7 +839,7 @@ mod tests { serde_json::to_string(&account_keypairs[2].to_bytes().to_vec()).unwrap(), Base64Account { owner: solana_sdk::pubkey::new_rand().to_string(), - balance: 30 as u64, + balance: 30, executable: true, data: String::from("Y29tYSBtb2Nh"), }, diff --git a/install/src/command.rs b/install/src/command.rs index 9f9fe61dcc..70a32cb1ba 100644 --- a/install/src/command.rs +++ b/install/src/command.rs @@ -360,7 +360,7 @@ fn get_windows_path_var() -> Result, String> { } #[cfg(windows)] -fn add_to_path(new_path: &str) -> Result { +fn add_to_path(new_path: &str) -> bool { use std::ptr; use winapi::shared::minwindef::*; use winapi::um::winuser::{ @@ -372,7 +372,7 @@ fn add_to_path(new_path: &str) -> Result { let old_path = if let Some(s) = get_windows_path_var()? { s } else { - return Ok(false); + return false; }; if !old_path.contains(&new_path) { @@ -416,11 +416,11 @@ fn add_to_path(new_path: &str) -> Result { new_path, style("Future applications will automatically have the correct environment, but you may need to restart your current shell.").bold() ); - Ok(true) + true } #[cfg(unix)] -fn add_to_path(new_path: &str) -> Result { +fn add_to_path(new_path: &str) -> bool { let shell_export_string = format!(r#"export PATH="{}:$PATH""#, new_path); let mut modified_rcfiles = false; @@ -502,7 +502,7 @@ fn add_to_path(new_path: &str) -> Result { ); } - Ok(modified_rcfiles) + modified_rcfiles } pub fn init( @@ -533,7 +533,7 @@ pub fn init( update(config_file)?; let path_modified = if !no_modify_path { - add_to_path(&config.active_release_bin_dir().to_str().unwrap())? + add_to_path(&config.active_release_bin_dir().to_str().unwrap()) } else { false }; diff --git a/keygen/src/keygen.rs b/keygen/src/keygen.rs index 49edc8562c..0d40834ae9 100644 --- a/keygen/src/keygen.rs +++ b/keygen/src/keygen.rs @@ -55,7 +55,7 @@ fn get_keypair_from_matches( let mut path = dirs_next::home_dir().expect("home directory"); let path = if matches.is_present("keypair") { matches.value_of("keypair").unwrap() - } else if config.keypair_path != "" { + } else if !config.keypair_path.is_empty() { &config.keypair_path } else { path.extend(&[".config", "solana", "id.json"]); diff --git a/ledger-tool/src/main.rs b/ledger-tool/src/main.rs index 6b77ee525b..eb89d897d7 100644 --- a/ledger-tool/src/main.rs +++ b/ledger-tool/src/main.rs @@ -70,30 +70,23 @@ enum LedgerOutputMethod { Json, } -fn output_slot_rewards( - blockstore: &Blockstore, - slot: Slot, - method: &LedgerOutputMethod, -) -> Result<(), String> { +fn output_slot_rewards(blockstore: &Blockstore, slot: Slot, method: &LedgerOutputMethod) { // Note: rewards are not output in JSON yet if *method == LedgerOutputMethod::Print { - if let Ok(rewards) = blockstore.read_rewards(slot) { - if let Some(rewards) = rewards { - if !rewards.is_empty() { - println!(" Rewards:"); - for reward in rewards { - println!( - " Account {}: {}{} SOL", - reward.pubkey, - if reward.lamports < 0 { '-' } else { ' ' }, - lamports_to_sol(reward.lamports.abs().try_into().unwrap()) - ); - } + if let Ok(Some(rewards)) = blockstore.read_rewards(slot) { + if !rewards.is_empty() { + println!(" Rewards:"); + for reward in rewards { + println!( + " Account {}: {}{} SOL", + reward.pubkey, + if reward.lamports < 0 { '-' } else { ' ' }, + lamports_to_sol(reward.lamports.abs().try_into().unwrap()) + ); } } } } - Ok(()) } fn output_entry( @@ -181,7 +174,7 @@ fn output_slot( output_entry(blockstore, method, slot, entry_index, entry); } - output_slot_rewards(blockstore, slot, method)?; + output_slot_rewards(blockstore, slot, method); } else if verbose_level >= 1 { let mut transactions = 0; let mut hashes = 0; @@ -526,7 +519,7 @@ fn analyze_column< db: &Database, name: &str, key_size: usize, -) -> Result<(), String> { +) { let mut key_tot: u64 = 0; let mut val_hist = histogram::Histogram::new(); let mut val_tot: u64 = 0; @@ -587,38 +580,34 @@ fn analyze_column< }; println!("{}", serde_json::to_string_pretty(&json_result).unwrap()); - - Ok(()) } -fn analyze_storage(database: &Database) -> Result<(), String> { +fn analyze_storage(database: &Database) { use blockstore_db::columns::*; - analyze_column::(database, "SlotMeta", SlotMeta::key_size())?; - analyze_column::(database, "Orphans", Orphans::key_size())?; - analyze_column::(database, "DeadSlots", DeadSlots::key_size())?; - analyze_column::(database, "ErasureMeta", ErasureMeta::key_size())?; - analyze_column::(database, "Root", Root::key_size())?; - analyze_column::(database, "Index", Index::key_size())?; - analyze_column::(database, "ShredData", ShredData::key_size())?; - analyze_column::(database, "ShredCode", ShredCode::key_size())?; + analyze_column::(database, "SlotMeta", SlotMeta::key_size()); + analyze_column::(database, "Orphans", Orphans::key_size()); + analyze_column::(database, "DeadSlots", DeadSlots::key_size()); + analyze_column::(database, "ErasureMeta", ErasureMeta::key_size()); + analyze_column::(database, "Root", Root::key_size()); + analyze_column::(database, "Index", Index::key_size()); + analyze_column::(database, "ShredData", ShredData::key_size()); + analyze_column::(database, "ShredCode", ShredCode::key_size()); analyze_column::( database, "TransactionStatus", TransactionStatus::key_size(), - )?; + ); analyze_column::( database, "TransactionStatusIndex", TransactionStatusIndex::key_size(), - )?; + ); analyze_column::( database, "AddressSignatures", AddressSignatures::key_size(), - )?; - analyze_column::(database, "Rewards", Rewards::key_size())?; - - Ok(()) + ); + analyze_column::(database, "Rewards", Rewards::key_size()); } fn open_blockstore( @@ -2757,7 +2746,7 @@ fn main() { println!("Ledger is empty"); } else { let first = slots.first().unwrap(); - let last = slots.last().unwrap_or_else(|| first); + let last = slots.last().unwrap_or(first); if first != last { println!("Ledger has data for slots {:?} to {:?}", first, last); if all { @@ -2775,18 +2764,11 @@ fn main() { } } ("analyze-storage", _) => { - match analyze_storage(&open_database( + analyze_storage(&open_database( &ledger_path, AccessType::TryPrimaryThenSecondary, - )) { - Ok(()) => { - println!("Ok."); - } - Err(err) => { - eprintln!("Unable to read the Ledger: {:?}", err); - exit(1); - } - } + )); + println!("Ok."); } ("", _) => { eprintln!("{}", matches.usage()); diff --git a/ledger/src/bigtable_upload.rs b/ledger/src/bigtable_upload.rs index dd43975531..2ebc29f59f 100644 --- a/ledger/src/bigtable_upload.rs +++ b/ledger/src/bigtable_upload.rs @@ -107,7 +107,7 @@ pub async fn upload_confirmed_blocks( .difference(&bigtable_slots) .cloned() .collect::>(); - blocks_to_upload.sort(); + blocks_to_upload.sort_unstable(); blocks_to_upload }; diff --git a/ledger/src/blockstore.rs b/ledger/src/blockstore.rs index c3b56f527b..f544d10426 100644 --- a/ledger/src/blockstore.rs +++ b/ledger/src/blockstore.rs @@ -441,10 +441,8 @@ impl Blockstore { } pub fn is_full(&self, slot: Slot) -> bool { - if let Ok(meta) = self.meta_cf.get(slot) { - if let Some(meta) = meta { - return meta.is_full(); - } + if let Ok(Some(meta)) = self.meta_cf.get(slot) { + return meta.is_full(); } false } @@ -467,10 +465,10 @@ impl Blockstore { .unwrap_or(0) } - pub fn slot_meta_iterator<'a>( - &'a self, + pub fn slot_meta_iterator( + &self, slot: Slot, - ) -> Result + 'a> { + ) -> Result + '_> { let meta_iter = self .db .iter::(IteratorMode::From(slot, IteratorDirection::Forward))?; @@ -484,21 +482,18 @@ impl Blockstore { } #[allow(dead_code)] - pub fn live_slots_iterator<'a>( - &'a self, - root: Slot, - ) -> impl Iterator + 'a { + pub fn live_slots_iterator(&self, root: Slot) -> impl Iterator + '_ { let root_forks = NextSlotsIterator::new(root, self); let orphans_iter = self.orphans_iterator(root + 1).unwrap(); root_forks.chain(orphans_iter.flat_map(move |orphan| NextSlotsIterator::new(orphan, self))) } - pub fn slot_data_iterator<'a>( - &'a self, + pub fn slot_data_iterator( + &self, slot: Slot, index: u64, - ) -> Result)> + 'a> { + ) -> Result)> + '_> { let slot_iterator = self.db.iter::(IteratorMode::From( (slot, index), IteratorDirection::Forward, @@ -506,11 +501,11 @@ impl Blockstore { Ok(slot_iterator.take_while(move |((shred_slot, _), _)| *shred_slot == slot)) } - pub fn slot_coding_iterator<'a>( - &'a self, + pub fn slot_coding_iterator( + &self, slot: Slot, index: u64, - ) -> Result)> + 'a> { + ) -> Result)> + '_> { let slot_iterator = self.db.iter::(IteratorMode::From( (slot, index), IteratorDirection::Forward, @@ -518,10 +513,7 @@ impl Blockstore { Ok(slot_iterator.take_while(move |((shred_slot, _), _)| *shred_slot == slot)) } - pub fn rooted_slot_iterator<'a>( - &'a self, - slot: Slot, - ) -> Result + 'a> { + pub fn rooted_slot_iterator(&self, slot: Slot) -> Result + '_> { let slot_iterator = self .db .iter::(IteratorMode::From(slot, IteratorDirection::Forward))?; @@ -929,7 +921,7 @@ impl Blockstore { &self.completed_slots_senders, should_signal, newly_completed_slots, - )?; + ); total_start.stop(); @@ -1690,7 +1682,7 @@ impl Blockstore { .map(|(iter_slot, _)| iter_slot) .take(timestamp_sample_range) .collect(); - timestamp_slots.sort(); + timestamp_slots.sort_unstable(); get_slots.stop(); datapoint_info!( "blockstore-get-timestamp-slots", @@ -2746,17 +2738,14 @@ impl Blockstore { .is_some() } - pub fn orphans_iterator<'a>(&'a self, slot: Slot) -> Result + 'a> { + pub fn orphans_iterator(&self, slot: Slot) -> Result + '_> { let orphans_iter = self .db .iter::(IteratorMode::From(slot, IteratorDirection::Forward))?; Ok(orphans_iter.map(|(slot, _)| slot)) } - pub fn dead_slots_iterator<'a>( - &'a self, - slot: Slot, - ) -> Result + 'a> { + pub fn dead_slots_iterator(&self, slot: Slot) -> Result + '_> { let dead_slots_iterator = self .db .iter::(IteratorMode::From(slot, IteratorDirection::Forward))?; @@ -2981,7 +2970,7 @@ fn send_signals( completed_slots_senders: &[SyncSender>], should_signal: bool, newly_completed_slots: Vec, -) -> Result<()> { +) { if should_signal { for signal in new_shreds_signals { let _ = signal.try_send(true); @@ -3009,8 +2998,6 @@ fn send_signals( } } } - - Ok(()) } fn commit_slot_meta_working_set( @@ -3051,7 +3038,7 @@ fn find_slot_meta_else_create<'a>( chained_slots: &'a mut HashMap>>, slot_index: u64, ) -> Result>> { - let result = find_slot_meta_in_cached_state(working_set, chained_slots, slot_index)?; + let result = find_slot_meta_in_cached_state(working_set, chained_slots, slot_index); if let Some(slot) = result { Ok(slot) } else { @@ -3061,10 +3048,10 @@ fn find_slot_meta_else_create<'a>( // Search the database for that slot metadata. If still no luck, then // create a dummy orphan slot in the database -fn find_slot_meta_in_db_else_create<'a>( +fn find_slot_meta_in_db_else_create( db: &Database, slot: Slot, - insert_map: &'a mut HashMap>>, + insert_map: &mut HashMap>>, ) -> Result>> { if let Some(slot_meta) = db.column::().get(slot)? { insert_map.insert(slot, Rc::new(RefCell::new(slot_meta))); @@ -3083,13 +3070,13 @@ fn find_slot_meta_in_cached_state<'a>( working_set: &'a HashMap, chained_slots: &'a HashMap>>, slot: Slot, -) -> Result>>> { +) -> Option>> { if let Some(entry) = working_set.get(&slot) { - Ok(Some(entry.new_slot_meta.clone())) + Some(entry.new_slot_meta.clone()) } else if let Some(entry) = chained_slots.get(&slot) { - Ok(Some(entry.clone())) + Some(entry.clone()) } else { - Ok(None) + None } } @@ -3596,7 +3583,7 @@ pub mod tests { use solana_storage_proto::convert::generated; use solana_transaction_status::{InnerInstructions, Reward, Rewards}; use solana_vote_program::{vote_instruction, vote_state::Vote}; - use std::{iter::FromIterator, time::Duration}; + use std::time::Duration; // used for tests only pub(crate) fn make_slot_entries_with_transactions(num_entries: u64) -> Vec { @@ -4062,7 +4049,7 @@ pub mod tests { let blockstore = Blockstore::open(&blockstore_path).unwrap(); // Write entries - let num_slots = 5 as u64; + let num_slots = 5_u64; let mut index = 0; for slot in 0..num_slots { let entries = create_ticks(slot + 1, 0, Hash::default()); @@ -4094,8 +4081,8 @@ pub mod tests { let blockstore_path = get_tmp_ledger_path!(); { let blockstore = Blockstore::open(&blockstore_path).unwrap(); - let num_slots = 5 as u64; - let shreds_per_slot = 5 as u64; + let num_slots = 5_u64; + let shreds_per_slot = 5_u64; let entry_serialized_size = bincode::serialized_size(&create_ticks(1, 0, Hash::default())).unwrap(); let entries_per_slot = @@ -4437,9 +4424,9 @@ pub mod tests { all_shreds.shuffle(&mut thread_rng()); ledger.insert_shreds(all_shreds, None, false).unwrap(); let mut result = recvr.try_recv().unwrap(); - result.sort(); + result.sort_unstable(); slots.push(disconnected_slot); - slots.sort(); + slots.sort_unstable(); assert_eq!(result, slots); } @@ -4799,23 +4786,22 @@ pub mod tests { blockstore.meta_cf.put(0, &meta0).unwrap(); // Slot exists, chains to nothing - let expected: HashMap> = - HashMap::from_iter(vec![(0, vec![])].into_iter()); + let expected: HashMap> = vec![(0, vec![])].into_iter().collect(); 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()); + let expected: HashMap> = vec![(0, vec![1, 2])].into_iter().collect(); 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()); + let expected: HashMap> = vec![(0, vec![1, 2]), (3, vec![10, 5])] + .into_iter() + .collect(); assert_eq!(blockstore.get_slots_since(&[0, 1, 3]).unwrap(), expected); } @@ -4902,7 +4888,7 @@ pub mod tests { let blockstore = Blockstore::open(&blockstore_path).unwrap(); // Create shreds and entries - let num_entries = 20 as u64; + let num_entries = 20_u64; let mut entries = vec![]; let mut shreds = vec![]; let mut num_shreds_per_slot = 0; @@ -5807,8 +5793,10 @@ pub mod tests { ledger.insert_shreds(more_shreds, None, false).unwrap(); ledger.set_roots(&[slot - 1, slot, slot + 1]).unwrap(); - let mut parent_meta = SlotMeta::default(); - parent_meta.parent_slot = std::u64::MAX; + let parent_meta = SlotMeta { + parent_slot: std::u64::MAX, + ..SlotMeta::default() + }; ledger .put_meta_bytes(slot - 1, &serialize(&parent_meta).unwrap()) .unwrap(); diff --git a/ledger/src/blockstore/blockstore_purge.rs b/ledger/src/blockstore/blockstore_purge.rs index 0d171cb091..8f9704c02a 100644 --- a/ledger/src/blockstore/blockstore_purge.rs +++ b/ledger/src/blockstore/blockstore_purge.rs @@ -95,7 +95,7 @@ impl Blockstore { .batch() .expect("Database Error: Failed to get write batch"); // delete range cf is not inclusive - let to_slot = to_slot.checked_add(1).unwrap_or_else(|| std::u64::MAX); + let to_slot = to_slot.checked_add(1).unwrap_or(std::u64::MAX); let mut delete_range_timer = Measure::start("delete_range"); let mut columns_purged = self diff --git a/ledger/src/blockstore_db.rs b/ledger/src/blockstore_db.rs index e77a09c001..c53ed2c9d8 100644 --- a/ledger/src/blockstore_db.rs +++ b/ledger/src/blockstore_db.rs @@ -360,11 +360,7 @@ impl Rocks { Ok(()) } - fn iterator_cf( - &self, - cf: &ColumnFamily, - iterator_mode: IteratorMode, - ) -> Result + fn iterator_cf(&self, cf: &ColumnFamily, iterator_mode: IteratorMode) -> DBIterator where C: Column, { @@ -377,18 +373,15 @@ impl Rocks { IteratorMode::Start => RocksIteratorMode::Start, IteratorMode::End => RocksIteratorMode::End, }; - let iter = self.0.iterator_cf(cf, iterator_mode); - Ok(iter) + self.0.iterator_cf(cf, iterator_mode) } - fn raw_iterator_cf(&self, cf: &ColumnFamily) -> Result { - let raw_iter = self.0.raw_iterator_cf(cf); - - Ok(raw_iter) + fn raw_iterator_cf(&self, cf: &ColumnFamily) -> DBRawIterator { + self.0.raw_iterator_cf(cf) } - fn batch(&self) -> Result { - Ok(RWriteBatch::default()) + fn batch(&self) -> RWriteBatch { + RWriteBatch::default() } fn write(&self, batch: RWriteBatch) -> Result<()> { @@ -766,15 +759,15 @@ impl Database { } } - pub fn iter<'a, C>( - &'a self, + pub fn iter( + &self, iterator_mode: IteratorMode, - ) -> Result)> + 'a> + ) -> Result)> + '_> where C: Column + ColumnName, { let cf = self.cf_handle::(); - let iter = self.backend.iterator_cf::(cf, iterator_mode)?; + let iter = self.backend.iterator_cf::(cf, iterator_mode); Ok(iter.map(|(key, value)| (C::index(&key), value))) } @@ -798,11 +791,11 @@ impl Database { #[inline] pub fn raw_iterator_cf(&self, cf: &ColumnFamily) -> Result { - self.backend.raw_iterator_cf(cf) + Ok(self.backend.raw_iterator_cf(cf)) } pub fn batch(&self) -> Result { - let write_batch = self.backend.batch()?; + let write_batch = self.backend.batch(); let map = self .backend .columns() @@ -845,12 +838,12 @@ where self.backend.get_cf(self.handle(), &C::key(key)) } - pub fn iter<'a>( - &'a self, + pub fn iter( + &self, iterator_mode: IteratorMode, - ) -> Result)> + 'a> { + ) -> Result)> + '_> { let cf = self.handle(); - let iter = self.backend.iterator_cf::(cf, iterator_mode)?; + let iter = self.backend.iterator_cf::(cf, iterator_mode); Ok(iter.map(|(key, value)| (C::index(&key), value))) } @@ -906,7 +899,7 @@ where #[cfg(test)] pub fn is_empty(&self) -> Result { - let mut iter = self.backend.raw_iterator_cf(self.handle())?; + let mut iter = self.backend.raw_iterator_cf(self.handle()); iter.seek_to_first(); Ok(!iter.valid()) } diff --git a/ledger/src/blockstore_processor.rs b/ledger/src/blockstore_processor.rs index 96d32a1e49..d9227d99a6 100644 --- a/ledger/src/blockstore_processor.rs +++ b/ledger/src/blockstore_processor.rs @@ -375,7 +375,7 @@ pub fn process_blockstore( let bank0 = Arc::new(bank0); info!("processing ledger for slot 0..."); let recyclers = VerifyRecyclers::default(); - process_bank_0(&bank0, blockstore, &opts, &recyclers)?; + process_bank_0(&bank0, blockstore, &opts, &recyclers); do_process_blockstore_from_root(blockstore, bank0, &opts, &recyclers, None) } @@ -738,7 +738,7 @@ fn process_bank_0( blockstore: &Blockstore, opts: &ProcessOptions, recyclers: &VerifyRecyclers, -) -> result::Result<(), BlockstoreProcessorError> { +) { assert_eq!(bank0.slot(), 0); let mut progress = ConfirmationProgress::new(bank0.last_blockhash()); confirm_full_slot( @@ -752,7 +752,6 @@ fn process_bank_0( ) .expect("processing for bank 0 must succeed"); bank0.freeze(); - Ok(()) } // Given a bank, add its children to the pending slots queue if those children slots are @@ -2715,7 +2714,7 @@ pub mod tests { ..ProcessOptions::default() }; let recyclers = VerifyRecyclers::default(); - process_bank_0(&bank0, &blockstore, &opts, &recyclers).unwrap(); + process_bank_0(&bank0, &blockstore, &opts, &recyclers); let bank1 = Arc::new(Bank::new_from_parent(&bank0, &Pubkey::default(), 1)); confirm_full_slot( &blockstore, @@ -2901,7 +2900,7 @@ pub mod tests { fn frozen_bank_slots(bank_forks: &BankForks) -> Vec { let mut slots: Vec<_> = bank_forks.frozen_banks().keys().cloned().collect(); - slots.sort(); + slots.sort_unstable(); slots } @@ -3210,6 +3209,7 @@ pub mod tests { } #[test] + #[allow(clippy::field_reassign_with_default)] fn test_supermajority_root_from_vote_accounts() { let convert_to_vote_accounts = |roots_stakes: Vec<(Slot, u64)>| -> Vec<(Pubkey, (u64, ArcVoteAccount))> { diff --git a/ledger/src/leader_schedule_cache.rs b/ledger/src/leader_schedule_cache.rs index 720376ea2b..084989eac5 100644 --- a/ledger/src/leader_schedule_cache.rs +++ b/ledger/src/leader_schedule_cache.rs @@ -322,7 +322,7 @@ mod tests { LeaderScheduleCache::retain_latest(&mut cached_schedules, &mut order, MAX_SCHEDULES); assert_eq!(cached_schedules.len(), MAX_SCHEDULES); let mut keys: Vec<_> = cached_schedules.keys().cloned().collect(); - keys.sort(); + keys.sort_unstable(); let expected: Vec<_> = (1..=MAX_SCHEDULES as u64).collect(); let expected_order: VecDeque<_> = (1..=MAX_SCHEDULES as u64).collect(); assert_eq!(expected, keys); diff --git a/ledger/src/shred.rs b/ledger/src/shred.rs index d964b4efeb..fa6d601021 100644 --- a/ledger/src/shred.rs +++ b/ledger/src/shred.rs @@ -500,6 +500,7 @@ impl Shredder { reference_tick: u8, version: u16, ) -> Result { + #[allow(clippy::manual_range_contains)] if fec_rate > 1.0 || fec_rate < 0.0 { Err(ShredError::InvalidFecRate(fec_rate)) } else if slot < parent_slot || slot - parent_slot > u64::from(std::u16::MAX) { diff --git a/ledger/tests/blockstore.rs b/ledger/tests/blockstore.rs index 50393832af..4840b57a16 100644 --- a/ledger/tests/blockstore.rs +++ b/ledger/tests/blockstore.rs @@ -37,7 +37,7 @@ fn test_multiple_threads_insert_shred() { // Check slot 0 has the correct children let mut meta0 = blockstore.meta(0).unwrap().unwrap(); - meta0.next_slots.sort(); + meta0.next_slots.sort_unstable(); let expected_next_slots: Vec<_> = (1..num_threads + 1).collect(); assert_eq!(meta0.next_slots, expected_next_slots); diff --git a/local-cluster/tests/local_cluster.rs b/local-cluster/tests/local_cluster.rs index 76bfafd400..71d46ef96e 100644 --- a/local-cluster/tests/local_cluster.rs +++ b/local-cluster/tests/local_cluster.rs @@ -68,8 +68,10 @@ fn test_ledger_cleanup_service() { solana_logger::setup(); error!("test_ledger_cleanup_service"); let num_nodes = 3; - let mut validator_config = ValidatorConfig::default(); - validator_config.max_ledger_shreds = Some(100); + let validator_config = ValidatorConfig { + max_ledger_shreds: Some(100), + ..ValidatorConfig::default() + }; let mut config = ClusterConfig { cluster_lamports: 10_000, poh_config: PohConfig::new_sleep(Duration::from_millis(50)), @@ -322,8 +324,10 @@ fn run_cluster_partition( assert_eq!(node_stakes.len(), num_nodes); let cluster_lamports = node_stakes.iter().sum::() * 2; let enable_partition = Arc::new(AtomicBool::new(true)); - let mut validator_config = ValidatorConfig::default(); - validator_config.enable_partition = Some(enable_partition.clone()); + let mut validator_config = ValidatorConfig { + enable_partition: Some(enable_partition.clone()), + ..ValidatorConfig::default() + }; // Returns: // 1) The keys for the validators @@ -702,7 +706,7 @@ fn test_forwarding() { fn test_restart_node() { solana_logger::setup(); error!("test_restart_node"); - let slots_per_epoch = MINIMUM_SLOTS_PER_EPOCH * 2 as u64; + let slots_per_epoch = MINIMUM_SLOTS_PER_EPOCH * 2; let ticks_per_slot = 16; let validator_config = ValidatorConfig::default(); let mut cluster = LocalCluster::new(&mut ClusterConfig { @@ -1326,8 +1330,10 @@ fn test_fake_shreds_broadcast_leader() { fn test_faulty_node(faulty_node_type: BroadcastStageType) { solana_logger::setup(); let num_nodes = 2; - let mut error_validator_config = ValidatorConfig::default(); - error_validator_config.broadcast_stage_type = faulty_node_type; + let error_validator_config = ValidatorConfig { + broadcast_stage_type: faulty_node_type, + ..ValidatorConfig::default() + }; let mut validator_configs = Vec::with_capacity(num_nodes - 1); validator_configs.resize_with(num_nodes - 1, ValidatorConfig::default); @@ -1339,8 +1345,8 @@ fn test_faulty_node(faulty_node_type: BroadcastStageType) { cluster_lamports: 10_000, node_stakes, validator_configs, - slots_per_epoch: MINIMUM_SLOTS_PER_EPOCH * 2 as u64, - stakers_slot_offset: MINIMUM_SLOTS_PER_EPOCH * 2 as u64, + slots_per_epoch: MINIMUM_SLOTS_PER_EPOCH * 2, + stakers_slot_offset: MINIMUM_SLOTS_PER_EPOCH * 2, ..ClusterConfig::default() }; @@ -2156,7 +2162,7 @@ fn test_run_test_load_program_accounts_partition_root() { fn run_test_load_program_accounts_partition(scan_commitment: CommitmentConfig) { let num_slots_per_validator = 8; - let partitions: [&[usize]; 2] = [&[(1 as usize)], &[(1 as usize)]]; + let partitions: [&[usize]; 2] = [&[(1)], &[(1)]]; let (leader_schedule, validator_keys) = create_custom_leader_schedule(partitions.len(), num_slots_per_validator); diff --git a/net-utils/src/lib.rs b/net-utils/src/lib.rs index 75dd997221..4ad65268a1 100644 --- a/net-utils/src/lib.rs +++ b/net-utils/src/lib.rs @@ -581,7 +581,7 @@ mod tests { 3000 ); let port = find_available_port_in_range(ip_addr, (3000, 3050)).unwrap(); - assert!(3000 <= port && port < 3050); + assert!((3000..3050).contains(&port)); let _socket = bind_to(ip_addr, port, false).unwrap(); find_available_port_in_range(ip_addr, (port, port + 1)).unwrap_err(); @@ -591,7 +591,7 @@ mod tests { fn test_bind_common_in_range() { let ip_addr = IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)); let (port, _sockets) = bind_common_in_range(ip_addr, (3100, 3150)).unwrap(); - assert!(3100 <= port && port < 3150); + assert!((3100..3150).contains(&port)); bind_common_in_range(ip_addr, (port, port + 1)).unwrap_err(); } diff --git a/perf/benches/sigverify.rs b/perf/benches/sigverify.rs index fd2bea1ad0..c6fb568471 100644 --- a/perf/benches/sigverify.rs +++ b/perf/benches/sigverify.rs @@ -33,8 +33,6 @@ fn bench_get_offsets(bencher: &mut Bencher) { let recycler = Recycler::default(); // verify packets bencher.iter(|| { - let ans = sigverify::generate_offsets(&batches, &recycler); - assert!(ans.is_ok()); - let _ans = ans.unwrap(); + let _ans = sigverify::generate_offsets(&batches, &recycler); }) } diff --git a/perf/src/sigverify.rs b/perf/src/sigverify.rs index 979c8eafda..67f32f15c8 100644 --- a/perf/src/sigverify.rs +++ b/perf/src/sigverify.rs @@ -192,10 +192,7 @@ fn get_packet_offsets(packet: &Packet, current_offset: u32) -> PacketOffsets { } } -pub fn generate_offsets( - batches: &[Packets], - recycler: &Recycler, -) -> Result { +pub fn generate_offsets(batches: &[Packets], recycler: &Recycler) -> TxOffsets { debug!("allocating.."); let mut signature_offsets: PinnedVec<_> = recycler.allocate("sig_offsets"); signature_offsets.set_pinnable(); @@ -236,13 +233,13 @@ pub fn generate_offsets( }); v_sig_lens.push(sig_lens); }); - Ok(( + ( signature_offsets, pubkey_offsets, msg_start_offsets, msg_sizes, v_sig_lens, - )) + ) } pub fn ed25519_verify_cpu(batches: &[Packets]) -> Vec> { @@ -346,7 +343,7 @@ pub fn ed25519_verify( } let (signature_offsets, pubkey_offsets, msg_start_offsets, msg_sizes, sig_lens) = - generate_offsets(batches, recycler).unwrap(); + generate_offsets(batches, recycler); debug!("CUDA ECDSA for {}", batch_size(batches)); debug!("allocating out.."); diff --git a/program-test/src/lib.rs b/program-test/src/lib.rs index 258a64e80d..3ab5dca7a0 100644 --- a/program-test/src/lib.rs +++ b/program-test/src/lib.rs @@ -74,9 +74,11 @@ pub fn builtin_process_instruction( input: &[u8], invoke_context: &mut dyn InvokeContext, ) -> Result<(), InstructionError> { - let mut mock_invoke_context = MockInvokeContext::default(); - mock_invoke_context.programs = invoke_context.get_programs().to_vec(); - mock_invoke_context.key = *program_id; + let mock_invoke_context = MockInvokeContext { + programs: invoke_context.get_programs().to_vec(), + key: *program_id, + ..MockInvokeContext::default() + }; // TODO: Populate MockInvokeContext more, or rework to avoid MockInvokeContext entirely. // The context being passed into the program is incomplete... let local_invoke_context = RefCell::new(Rc::new(mock_invoke_context)); diff --git a/programs/bpf/rust/128bit/src/lib.rs b/programs/bpf/rust/128bit/src/lib.rs index 8e395103fa..97840af01c 100644 --- a/programs/bpf/rust/128bit/src/lib.rs +++ b/programs/bpf/rust/128bit/src/lib.rs @@ -19,7 +19,7 @@ pub extern "C" fn entrypoint(_input: *mut u8) -> u64 { assert_eq!(z, 340_282_366_920_938_463_463_374_607_431_768_211_454); assert_eq!(u128::from(1u32.to_le()), 1); - assert_eq!(u128::from(1u32.to_be()), 0x1_000_000); + assert_eq!(u128::from(1u32.to_be()), 0x0100_0000); assert_eq!(solana_bpf_rust_128bit_dep::uadd(10, 20), 30u128); assert_eq!(solana_bpf_rust_128bit_dep::usubtract(30, 20), 10u128); diff --git a/programs/bpf/rust/custom_heap/src/lib.rs b/programs/bpf/rust/custom_heap/src/lib.rs index 0e20e7c1e5..fc3ec780f5 100644 --- a/programs/bpf/rust/custom_heap/src/lib.rs +++ b/programs/bpf/rust/custom_heap/src/lib.rs @@ -53,7 +53,8 @@ unsafe impl std::alloc::GlobalAlloc for BumpAllocator { static A: BumpAllocator = BumpAllocator; entrypoint!(process_instruction); -fn process_instruction( +#[allow(clippy::unnecessary_wraps)] +pub fn process_instruction( _program_id: &Pubkey, _accounts: &[AccountInfo], _instruction_data: &[u8], diff --git a/programs/bpf/rust/deprecated_loader/src/lib.rs b/programs/bpf/rust/deprecated_loader/src/lib.rs index a0f03e46c3..0a43d330c0 100644 --- a/programs/bpf/rust/deprecated_loader/src/lib.rs +++ b/programs/bpf/rust/deprecated_loader/src/lib.rs @@ -27,6 +27,7 @@ fn custom_panic(info: &core::panic::PanicInfo<'_>) { } entrypoint_deprecated!(process_instruction); +#[allow(clippy::unnecessary_wraps)] fn process_instruction( program_id: &Pubkey, accounts: &[AccountInfo], diff --git a/programs/bpf/rust/external_spend/src/lib.rs b/programs/bpf/rust/external_spend/src/lib.rs index ecc33da259..55abb31d16 100644 --- a/programs/bpf/rust/external_spend/src/lib.rs +++ b/programs/bpf/rust/external_spend/src/lib.rs @@ -6,6 +6,7 @@ use solana_program::{ }; entrypoint!(process_instruction); +#[allow(clippy::unnecessary_wraps)] fn process_instruction( _program_id: &Pubkey, accounts: &[AccountInfo], diff --git a/programs/bpf/rust/invoke_and_ok/src/lib.rs b/programs/bpf/rust/invoke_and_ok/src/lib.rs index d2ad45999b..99e58f7d9a 100644 --- a/programs/bpf/rust/invoke_and_ok/src/lib.rs +++ b/programs/bpf/rust/invoke_and_ok/src/lib.rs @@ -7,6 +7,7 @@ use solana_program::{ }; entrypoint!(process_instruction); +#[allow(clippy::unnecessary_wraps)] fn process_instruction( _program_id: &Pubkey, accounts: &[AccountInfo], diff --git a/programs/bpf/rust/noop/src/lib.rs b/programs/bpf/rust/noop/src/lib.rs index ac6c3d6c84..9ec6a35917 100644 --- a/programs/bpf/rust/noop/src/lib.rs +++ b/programs/bpf/rust/noop/src/lib.rs @@ -6,6 +6,7 @@ use solana_program::{ }; entrypoint!(process_instruction); +#[allow(clippy::unnecessary_wraps)] fn process_instruction( _program_id: &Pubkey, _accounts: &[AccountInfo], diff --git a/programs/bpf/rust/panic/src/lib.rs b/programs/bpf/rust/panic/src/lib.rs index f79f27c223..67fc3dbfb7 100644 --- a/programs/bpf/rust/panic/src/lib.rs +++ b/programs/bpf/rust/panic/src/lib.rs @@ -14,6 +14,7 @@ use solana_program::{ }; entrypoint!(process_instruction); +#[allow(clippy::unnecessary_wraps)] fn process_instruction( _program_id: &Pubkey, _accounts: &[AccountInfo], diff --git a/programs/bpf/rust/rand/src/lib.rs b/programs/bpf/rust/rand/src/lib.rs index a14392d9d2..4366d2fff1 100644 --- a/programs/bpf/rust/rand/src/lib.rs +++ b/programs/bpf/rust/rand/src/lib.rs @@ -8,6 +8,7 @@ use solana_program::{ }; entrypoint!(process_instruction); +#[allow(clippy::unnecessary_wraps)] fn process_instruction( _program_id: &Pubkey, _accounts: &[AccountInfo], diff --git a/programs/bpf/rust/sanity/src/lib.rs b/programs/bpf/rust/sanity/src/lib.rs index 674fb9bc1a..e4de55f891 100644 --- a/programs/bpf/rust/sanity/src/lib.rs +++ b/programs/bpf/rust/sanity/src/lib.rs @@ -21,6 +21,7 @@ fn return_sstruct() -> SStruct { } entrypoint!(process_instruction); +#[allow(clippy::unnecessary_wraps)] fn process_instruction( program_id: &Pubkey, accounts: &[AccountInfo], diff --git a/programs/bpf/rust/spoof1_system/src/lib.rs b/programs/bpf/rust/spoof1_system/src/lib.rs index 6dc64207fb..8ec25b5abc 100644 --- a/programs/bpf/rust/spoof1_system/src/lib.rs +++ b/programs/bpf/rust/spoof1_system/src/lib.rs @@ -3,6 +3,7 @@ use solana_program::{ }; entrypoint!(process_instruction); +#[allow(clippy::unnecessary_wraps)] fn process_instruction( _program_id: &Pubkey, accounts: &[AccountInfo], diff --git a/programs/bpf/rust/sysval/src/lib.rs b/programs/bpf/rust/sysval/src/lib.rs index 33ef8fca92..062a6fc372 100644 --- a/programs/bpf/rust/sysval/src/lib.rs +++ b/programs/bpf/rust/sysval/src/lib.rs @@ -16,6 +16,7 @@ use solana_program::{ }; entrypoint!(process_instruction); +#[allow(clippy::unnecessary_wraps)] fn process_instruction( _program_id: &Pubkey, accounts: &[AccountInfo], diff --git a/programs/budget/src/budget_processor.rs b/programs/budget/src/budget_processor.rs index f79ff118ce..df32694924 100644 --- a/programs/budget/src/budget_processor.rs +++ b/programs/budget/src/budget_processor.rs @@ -141,9 +141,10 @@ pub fn process_instruction( trace!("contract already exists"); return Err(InstructionError::AccountAlreadyInitialized); } - let mut budget_state = BudgetState::default(); - budget_state.pending_budget = Some(*expr); - budget_state.initialized = true; + let budget_state = BudgetState { + pending_budget: Some(*expr), + initialized: true, + }; budget_state.serialize(&mut contract_keyed_account.try_account_ref_mut()?.data) } BudgetInstruction::ApplyTimestamp(dt) => { diff --git a/programs/noop/src/lib.rs b/programs/noop/src/lib.rs index 2580f4ef53..8bfc2d9d6d 100644 --- a/programs/noop/src/lib.rs +++ b/programs/noop/src/lib.rs @@ -10,7 +10,7 @@ solana_sdk::declare_program!( process_instruction ); -fn process_instruction( +pub fn process_instruction( program_id: &Pubkey, keyed_accounts: &[KeyedAccount], data: &[u8], diff --git a/programs/stake/src/stake_instruction.rs b/programs/stake/src/stake_instruction.rs index ef60070ad0..5baabb677d 100644 --- a/programs/stake/src/stake_instruction.rs +++ b/programs/stake/src/stake_instruction.rs @@ -562,13 +562,15 @@ mod tests { } else if sysvar::rent::check_id(&meta.pubkey) { account::create_account(&Rent::default(), 1) } else if meta.pubkey == invalid_stake_state_pubkey() { - let mut account = Account::default(); - account.owner = id(); - account + Account { + owner: id(), + ..Account::default() + } } else if meta.pubkey == invalid_vote_state_pubkey() { - let mut account = Account::default(); - account.owner = solana_vote_program::id(); - account + Account { + owner: solana_vote_program::id(), + ..Account::default() + } } else { Account::default() }) diff --git a/programs/vote/src/vote_state/mod.rs b/programs/vote/src/vote_state/mod.rs index 897599e19e..6614aca627 100644 --- a/programs/vote/src/vote_state/mod.rs +++ b/programs/vote/src/vote_state/mod.rs @@ -272,16 +272,18 @@ impl VoteState { } fn get_max_sized_vote_state() -> VoteState { - let mut vote_state = Self::default(); - vote_state.votes = VecDeque::from(vec![Lockout::default(); MAX_LOCKOUT_HISTORY]); - vote_state.root_slot = Some(std::u64::MAX); - vote_state.epoch_credits = vec![(0, 0, 0); MAX_EPOCH_CREDITS_HISTORY]; let mut authorized_voters = AuthorizedVoters::default(); for i in 0..=MAX_LEADER_SCHEDULE_EPOCH_OFFSET { authorized_voters.insert(i, solana_sdk::pubkey::new_rand()); } - vote_state.authorized_voters = authorized_voters; - vote_state + + VoteState { + votes: VecDeque::from(vec![Lockout::default(); MAX_LOCKOUT_HISTORY]), + root_slot: Some(std::u64::MAX), + epoch_credits: vec![(0, 0, 0); MAX_EPOCH_CREDITS_HISTORY], + authorized_voters, + ..Self::default() + } } fn check_slots_are_valid( @@ -463,10 +465,7 @@ impl VoteState { where F: Fn(Pubkey) -> Result<(), InstructionError>, { - let epoch_authorized_voter = self.get_and_update_authorized_voter(current_epoch).expect( - "the clock epoch is monotonically increasing, so authorized voter must be known", - ); - + let epoch_authorized_voter = self.get_and_update_authorized_voter(current_epoch); verify(epoch_authorized_voter)?; // The offset in slots `n` on which the target_epoch @@ -514,17 +513,16 @@ impl VoteState { Ok(()) } - fn get_and_update_authorized_voter(&mut self, current_epoch: Epoch) -> Option { + fn get_and_update_authorized_voter(&mut self, current_epoch: Epoch) -> Pubkey { let pubkey = self .authorized_voters .get_and_cache_authorized_voter_for_epoch(current_epoch) .expect( - "Internal functions should - only call this will monotonically increasing current_epoch", + "Internal functions should only call this will monotonically increasing current_epoch", ); self.authorized_voters .purge_authorized_voters(current_epoch); - Some(pubkey) + pubkey } fn pop_expired_votes(&mut self, slot: Slot) { @@ -702,9 +700,7 @@ pub fn process_vote( } let mut vote_state = versioned.convert_to_current(); - let authorized_voter = vote_state - .get_and_update_authorized_voter(clock.epoch) - .expect("the clock epoch is monotonically increasing, so authorized voter must be known"); + let authorized_voter = vote_state.get_and_update_authorized_voter(clock.epoch); verify_authorized_signer(&authorized_voter, signers)?; vote_state.process_vote(vote, slot_hashes, clock.epoch)?; @@ -712,7 +708,7 @@ pub fn process_vote( vote.slots .iter() .max() - .ok_or_else(|| VoteError::EmptySlots) + .ok_or(VoteError::EmptySlots) .and_then(|slot| vote_state.process_timestamp(*slot, timestamp))?; } vote_account.set_state(&VoteStateVersions::Current(Box::new(vote_state))) @@ -1571,8 +1567,10 @@ mod tests { assert_eq!(vote_state.commission_split(1), (0, 1, false)); - let mut vote_state = VoteState::default(); - vote_state.commission = std::u8::MAX; + let mut vote_state = VoteState { + commission: std::u8::MAX, + ..VoteState::default() + }; assert_eq!(vote_state.commission_split(1), (1, 0, false)); vote_state.commission = 99; @@ -1726,8 +1724,10 @@ mod tests { #[test] fn test_vote_process_timestamp() { let (slot, timestamp) = (15, 1_575_412_285); - let mut vote_state = VoteState::default(); - vote_state.last_timestamp = BlockTimestamp { slot, timestamp }; + let mut vote_state = VoteState { + last_timestamp: BlockTimestamp { slot, timestamp }, + ..VoteState::default() + }; assert_eq!( vote_state.process_timestamp(slot - 1, timestamp + 1), @@ -1791,14 +1791,14 @@ mod tests { // If no new authorized voter was set, the same authorized voter // is locked into the next epoch assert_eq!( - vote_state.get_and_update_authorized_voter(1).unwrap(), + vote_state.get_and_update_authorized_voter(1), original_voter ); // Try to get the authorized voter for epoch 5, implies // the authorized voter for epochs 1-4 were unchanged assert_eq!( - vote_state.get_and_update_authorized_voter(5).unwrap(), + vote_state.get_and_update_authorized_voter(5), original_voter ); @@ -1820,7 +1820,7 @@ mod tests { // Try to get the authorized voter for epoch 6, unchanged assert_eq!( - vote_state.get_and_update_authorized_voter(6).unwrap(), + vote_state.get_and_update_authorized_voter(6), original_voter ); @@ -1828,7 +1828,7 @@ mod tests { // be the new authorized voter for i in 7..10 { assert_eq!( - vote_state.get_and_update_authorized_voter(i).unwrap(), + vote_state.get_and_update_authorized_voter(i), new_authorized_voter ); } @@ -1904,31 +1904,22 @@ mod tests { // voters is correct for i in 9..epoch_offset { assert_eq!( - vote_state.get_and_update_authorized_voter(i).unwrap(), + vote_state.get_and_update_authorized_voter(i), original_voter ); } for i in epoch_offset..3 + epoch_offset { - assert_eq!( - vote_state.get_and_update_authorized_voter(i).unwrap(), - new_voter - ); + assert_eq!(vote_state.get_and_update_authorized_voter(i), new_voter); } for i in 3 + epoch_offset..6 + epoch_offset { - assert_eq!( - vote_state.get_and_update_authorized_voter(i).unwrap(), - new_voter2 - ); + assert_eq!(vote_state.get_and_update_authorized_voter(i), new_voter2); } for i in 6 + epoch_offset..9 + epoch_offset { - assert_eq!( - vote_state.get_and_update_authorized_voter(i).unwrap(), - new_voter3 - ); + assert_eq!(vote_state.get_and_update_authorized_voter(i), new_voter3); } for i in 9 + epoch_offset..=10 + epoch_offset { assert_eq!( - vote_state.get_and_update_authorized_voter(i).unwrap(), + vote_state.get_and_update_authorized_voter(i), original_voter ); } diff --git a/ramp-tps/src/results.rs b/ramp-tps/src/results.rs index d201b4417d..03e1a7f708 100644 --- a/ramp-tps/src/results.rs +++ b/ramp-tps/src/results.rs @@ -30,6 +30,7 @@ pub struct Results { impl Results { /// Keep any result entries which occurred before the starting round. + #[allow(clippy::manual_strip)] pub fn new( file_path: String, mut previous_results: HashMap>, @@ -39,7 +40,6 @@ impl Results { previous_results.drain().for_each(|(key, value)| { if key.starts_with(ROUND_KEY_PREFIX) { let round_str = &key[ROUND_KEY_PREFIX.len()..]; - dbg!(round_str); if let Ok(round) = u32::from_str(round_str) { if round < start_round { results.insert(Round(round), value); diff --git a/remote-wallet/src/remote_wallet.rs b/remote-wallet/src/remote_wallet.rs index 52821cc0e8..1488d00fd0 100644 --- a/remote-wallet/src/remote_wallet.rs +++ b/remote-wallet/src/remote_wallet.rs @@ -260,11 +260,13 @@ impl RemoteWalletInfo { )); } - let mut wallet_info = RemoteWalletInfo::default(); - wallet_info.manufacturer = wallet_path.host_str().unwrap().to_string(); + let mut wallet_info = RemoteWalletInfo { + manufacturer: wallet_path.host_str().unwrap().to_string(), + ..RemoteWalletInfo::default() + }; if let Some(wallet_id) = wallet_path.path_segments().map(|c| c.collect::>()) { - if wallet_id[0] != "" { + if !wallet_id[0].is_empty() { wallet_info.pubkey = Pubkey::from_str(wallet_id[0]).map_err(|e| { RemoteWalletError::InvalidDerivationPath(format!( "pubkey from_str error: {:?}", @@ -597,8 +599,10 @@ mod tests { pubkey, error: None, }; - let mut test_info = RemoteWalletInfo::default(); - test_info.manufacturer = "Not Ledger".to_string(); + let mut test_info = RemoteWalletInfo { + manufacturer: "Not Ledger".to_string(), + ..RemoteWalletInfo::default() + }; assert!(!info.matches(&test_info)); test_info.manufacturer = "Ledger".to_string(); assert!(info.matches(&test_info)); diff --git a/runtime/benches/bank.rs b/runtime/benches/bank.rs index b5a589af8b..865dc2f45f 100644 --- a/runtime/benches/bank.rs +++ b/runtime/benches/bank.rs @@ -30,6 +30,7 @@ const NOOP_PROGRAM_ID: [u8; 32] = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, ]; +#[allow(clippy::unnecessary_wraps)] fn process_instruction( _program_id: &Pubkey, _keyed_accounts: &[KeyedAccount], diff --git a/runtime/benches/bloom.rs b/runtime/benches/bloom.rs index a1b953bd4f..2a964e55cf 100644 --- a/runtime/benches/bloom.rs +++ b/runtime/benches/bloom.rs @@ -16,7 +16,7 @@ use test::Bencher; #[bench] #[ignore] fn bench_bits_set(bencher: &mut Bencher) { - let mut bits: BitVec = BitVec::new_fill(false, 38_340_234 as u64); + let mut bits: BitVec = BitVec::new_fill(false, 38_340_234_u64); let mut hasher = FnvHasher::default(); bencher.iter(|| { @@ -31,7 +31,7 @@ fn bench_bits_set(bencher: &mut Bencher) { #[bench] #[ignore] fn bench_bits_set_hasher(bencher: &mut Bencher) { - let bits: BitVec = BitVec::new_fill(false, 38_340_234 as u64); + let bits: BitVec = BitVec::new_fill(false, 38_340_234_u64); let mut hasher = FnvHasher::default(); bencher.iter(|| { diff --git a/runtime/src/accounts.rs b/runtime/src/accounts.rs index 51f9e96ed2..e7df609fd6 100644 --- a/runtime/src/accounts.rs +++ b/runtime/src/accounts.rs @@ -118,8 +118,10 @@ impl Accounts { } fn construct_instructions_account(message: &Message) -> Account { - let mut account = Account::default(); - account.data = message.serialize_instructions(); + let mut account = Account { + data: message.serialize_instructions(), + ..Account::default() + }; // add room for current instruction index. account.data.resize(account.data.len() + 2, 0); diff --git a/runtime/src/accounts_background_service.rs b/runtime/src/accounts_background_service.rs index e29eac6f9c..4c559da268 100644 --- a/runtime/src/accounts_background_service.rs +++ b/runtime/src/accounts_background_service.rs @@ -188,7 +188,7 @@ impl ABSRequestHandler { }) } - pub fn handle_pruned_banks<'a>(&'a self, bank: &Bank) -> usize { + pub fn handle_pruned_banks(&self, bank: &Bank) -> usize { let mut count = 0; for pruned_slot in self.pruned_banks_receiver.try_iter() { count += 1; diff --git a/runtime/src/accounts_db.rs b/runtime/src/accounts_db.rs index 295c00fe46..c92f39895b 100644 --- a/runtime/src/accounts_db.rs +++ b/runtime/src/accounts_db.rs @@ -44,7 +44,6 @@ use std::{ collections::{HashMap, HashSet}, convert::TryInto, io::{Error as IOError, Result as IOResult}, - iter::FromIterator, ops::RangeBounds, path::{Path, PathBuf}, sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}, @@ -901,10 +900,7 @@ impl AccountsDB { let pubkey_to_slot_set: Vec<_> = purges .into_iter() .map(|(key, (slots_list, _ref_count))| { - ( - key, - HashSet::from_iter(slots_list.into_iter().map(|(slot, _)| slot)), - ) + (key, slots_list.into_iter().map(|(slot, _)| slot).collect()) }) .collect(); @@ -2875,6 +2871,7 @@ impl AccountsDB { pub fn generate_index(&self) { let mut slots = self.storage.all_slots(); + #[allow(clippy::stable_sort_primitive)] slots.sort(); let mut last_log_update = Instant::now(); @@ -2982,6 +2979,7 @@ impl AccountsDB { fn print_index(&self, label: &str) { let mut roots: Vec<_> = self.accounts_index.all_roots(); + #[allow(clippy::stable_sort_primitive)] roots.sort(); info!("{}: accounts_index roots: {:?}", label, roots,); for (pubkey, account_entry) in self.accounts_index.account_maps.read().unwrap().iter() { @@ -2995,12 +2993,14 @@ impl AccountsDB { fn print_count_and_status(&self, label: &str) { let mut slots: Vec<_> = self.storage.all_slots(); + #[allow(clippy::stable_sort_primitive)] slots.sort(); info!("{}: count_and status for {} slots:", label, slots.len()); for slot in &slots { let slot_stores = self.storage.get_slot_stores(*slot).unwrap(); let r_slot_stores = slot_stores.read().unwrap(); let mut ids: Vec<_> = r_slot_stores.keys().cloned().collect(); + #[allow(clippy::stable_sort_primitive)] ids.sort(); for id in &ids { let entry = r_slot_stores.get(id).unwrap(); @@ -3033,7 +3033,7 @@ pub mod tests { use assert_matches::assert_matches; use rand::{thread_rng, Rng}; use solana_sdk::{account::Account, hash::HASH_BYTES}; - use std::{fs, str::FromStr}; + use std::{fs, iter::FromIterator, str::FromStr}; fn linear_ancestors(end_slot: u64) -> Ancestors { let mut ancestors: Ancestors = vec![(0, 0)].into_iter().collect(); @@ -3155,8 +3155,10 @@ pub mod tests { let idx = thread_rng().gen_range(0, 99); let ancestors = vec![(0, 0)].into_iter().collect(); let account = db.load_slow(&ancestors, &pubkeys[idx]).unwrap(); - let mut default_account = Account::default(); - default_account.lamports = (idx + 1) as u64; + let default_account = Account { + lamports: (idx + 1) as u64, + ..Account::default() + }; assert_eq!((default_account, 0), account); } @@ -3169,8 +3171,10 @@ pub mod tests { let account0 = db.load_slow(&ancestors, &pubkeys[idx]).unwrap(); let ancestors = vec![(1, 1)].into_iter().collect(); let account1 = db.load_slow(&ancestors, &pubkeys[idx]).unwrap(); - let mut default_account = Account::default(); - default_account.lamports = (idx + 1) as u64; + let default_account = Account { + lamports: (idx + 1) as u64, + ..Account::default() + }; assert_eq!(&default_account, &account0.0); assert_eq!(&default_account, &account1.0); } @@ -3361,8 +3365,10 @@ pub mod tests { let ancestors = vec![(slot, 0)].into_iter().collect(); assert!(accounts.load_slow(&ancestors, &pubkeys[idx]).is_none()); } else { - let mut default_account = Account::default(); - default_account.lamports = account.lamports; + let default_account = Account { + lamports: account.lamports, + ..Account::default() + }; assert_eq!(default_account, account); } } @@ -3443,8 +3449,10 @@ pub mod tests { create_account(&db, &mut pubkeys, 0, 1, 0, 0); let ancestors = vec![(0, 0)].into_iter().collect(); let account = db.load_slow(&ancestors, &pubkeys[0]).unwrap(); - let mut default_account = Account::default(); - default_account.lamports = 1; + let default_account = Account { + lamports: 1, + ..Account::default() + }; assert_eq!((default_account, 0), account); } @@ -4434,7 +4442,7 @@ pub mod tests { db.print_accounts_stats("pre"); - let slots: HashSet = HashSet::from_iter(vec![1].into_iter()); + let slots: HashSet = vec![1].into_iter().collect(); let purge_keys = vec![(key1, slots)]; let (_reclaims, dead_keys) = db.purge_keys_exact(purge_keys); @@ -5242,7 +5250,7 @@ pub mod tests { accounts.reset_uncleaned_roots(); let mut actual_slots = accounts.shrink_candidate_slots.lock().unwrap().clone(); - actual_slots.sort(); + actual_slots.sort_unstable(); assert_eq!(actual_slots, vec![0, 1, 2]); accounts.accounts_index.clear_roots(); @@ -5435,7 +5443,7 @@ pub mod tests { store_counts.insert(3, (1, HashSet::from_iter(vec![key2]))); AccountsDB::calc_delete_dependencies(&purges, &mut store_counts); let mut stores: Vec<_> = store_counts.keys().cloned().collect(); - stores.sort(); + stores.sort_unstable(); for store in &stores { info!( "store: {:?} : {:?}", diff --git a/runtime/src/accounts_index.rs b/runtime/src/accounts_index.rs index 58454492a2..0a96dcf173 100644 --- a/runtime/src/accounts_index.rs +++ b/runtime/src/accounts_index.rs @@ -196,12 +196,8 @@ impl AccountsIndex { AccountsIndexIterator::new(&self.account_maps, range) } - fn do_checked_scan_accounts<'a, F, R>( - &'a self, - ancestors: &Ancestors, - func: F, - range: Option, - ) where + fn do_checked_scan_accounts(&self, ancestors: &Ancestors, func: F, range: Option) + where F: FnMut(&Pubkey, (&T, Slot)), R: RangeBounds, { @@ -349,12 +345,8 @@ impl AccountsIndex { } } - fn do_unchecked_scan_accounts<'a, F, R>( - &'a self, - ancestors: &Ancestors, - func: F, - range: Option, - ) where + fn do_unchecked_scan_accounts(&self, ancestors: &Ancestors, func: F, range: Option) + where F: FnMut(&Pubkey, (&T, Slot)), R: RangeBounds, { @@ -364,8 +356,8 @@ impl AccountsIndex { // Scan accounts and return latest version of each account that is either: // 1) rooted or // 2) present in ancestors - fn do_scan_accounts<'a, F, R>( - &'a self, + fn do_scan_accounts( + &self, ancestors: &Ancestors, mut func: F, range: Option, @@ -922,7 +914,7 @@ mod tests { run_test_range_indexes( &index, &pubkeys, - Some(ITER_BATCH_SIZE - 1 as usize), + Some(ITER_BATCH_SIZE - 1_usize), Some(2 * ITER_BATCH_SIZE as usize + 1), ); } diff --git a/runtime/src/append_vec.rs b/runtime/src/append_vec.rs index dd3df5a81d..27a83838f9 100644 --- a/runtime/src/append_vec.rs +++ b/runtime/src/append_vec.rs @@ -397,7 +397,7 @@ impl AppendVec { self.path.clone() } - pub fn accounts<'a>(&'a self, mut start: usize) -> Vec> { + pub fn accounts(&self, mut start: usize) -> Vec { let mut accounts = vec![]; while let Some((account, next)) = self.get_account(start) { accounts.push(account); @@ -685,7 +685,7 @@ pub mod tests { let pubkey = solana_sdk::pubkey::new_rand(); let owner = Pubkey::default(); - let data_len = 3 as u64; + let data_len = 3_u64; let mut account = Account::new(0, data_len as usize, &owner); account.data = b"abc".to_vec(); let stored_meta = StoredMeta { diff --git a/runtime/src/bank.rs b/runtime/src/bank.rs index dfdc91a56f..39f174672b 100644 --- a/runtime/src/bank.rs +++ b/runtime/src/bank.rs @@ -832,6 +832,7 @@ pub struct Bank { bpf_compute_budget: Option, /// Builtin programs activated dynamically by feature + #[allow(clippy::rc_buffer)] feature_builtins: Arc>, /// Last time when the cluster info vote listener has synced with this bank @@ -887,9 +888,9 @@ impl Bank { additional_builtins: Option<&Builtins>, ) -> Self { let mut bank = Self::default(); + bank.ancestors.insert(bank.slot(), 0); bank.transaction_debug_keys = debug_keys; bank.cluster_type = Some(genesis_config.cluster_type); - bank.ancestors.insert(bank.slot(), 0); bank.rc.accounts = Arc::new(Accounts::new(paths, &genesis_config.cluster_type)); bank.process_genesis_config(genesis_config); @@ -1257,6 +1258,7 @@ impl Bank { } let mut ancestors: Vec<_> = roots.into_iter().collect(); + #[allow(clippy::stable_sort_primitive)] ancestors.sort(); ancestors } @@ -4940,13 +4942,13 @@ pub(crate) mod tests { impl Bank { fn epoch_stake_keys(&self) -> Vec { let mut keys: Vec = self.epoch_stakes.keys().copied().collect(); - keys.sort(); + keys.sort_unstable(); keys } fn epoch_stake_key_info(&self) -> (Epoch, Epoch, usize) { let mut keys: Vec = self.epoch_stakes.keys().copied().collect(); - keys.sort(); + keys.sort_unstable(); (*keys.first().unwrap(), *keys.last().unwrap(), keys.len()) } } @@ -9521,6 +9523,7 @@ pub(crate) mod tests { let (genesis_config, mint_keypair) = create_genesis_config(500); let mut bank = Bank::new(&genesis_config); + #[allow(clippy::unnecessary_wraps)] fn mock_process_instruction( _program_id: &Pubkey, _keyed_accounts: &[KeyedAccount], @@ -9704,6 +9707,7 @@ pub(crate) mod tests { assert_eq!(result, Err(TransactionError::SanitizeFailure)); } + #[allow(clippy::unnecessary_wraps)] fn mock_ok_vote_processor( _pubkey: &Pubkey, _ka: &[KeyedAccount], @@ -10035,7 +10039,7 @@ pub(crate) mod tests { let mut consumed_budgets = (0..3) .map(|_| bank.process_stale_slot_with_budget(0, force_to_return_alive_account)) .collect::>(); - consumed_budgets.sort(); + consumed_budgets.sort_unstable(); // consumed_budgets represents the count of alive accounts in the three slots 0,1,2 assert_eq!(consumed_budgets, vec![0, 1, 9]); } @@ -10136,6 +10140,7 @@ pub(crate) mod tests { fn test_add_builtin_no_overwrite() { let (genesis_config, _mint_keypair) = create_genesis_config(100_000); + #[allow(clippy::unnecessary_wraps)] fn mock_ix_processor( _pubkey: &Pubkey, _ka: &[KeyedAccount], @@ -10181,6 +10186,7 @@ pub(crate) mod tests { fn test_add_builtin_loader_no_overwrite() { let (genesis_config, _mint_keypair) = create_genesis_config(100_000); + #[allow(clippy::unnecessary_wraps)] fn mock_ix_processor( _pubkey: &Pubkey, _ka: &[KeyedAccount], diff --git a/runtime/src/bloom.rs b/runtime/src/bloom.rs index 9c2c1818a6..476e5af9b2 100644 --- a/runtime/src/bloom.rs +++ b/runtime/src/bloom.rs @@ -254,8 +254,8 @@ mod test { fn test_random() { let mut b1: Bloom = Bloom::random(10, 0.1, 100); let mut b2: Bloom = Bloom::random(10, 0.1, 100); - b1.keys.sort(); - b2.keys.sort(); + b1.keys.sort_unstable(); + b2.keys.sort_unstable(); assert_ne!(b1.keys, b2.keys); } // Bloom filter math in python diff --git a/runtime/src/hardened_unpack.rs b/runtime/src/hardened_unpack.rs index 4a414b4905..4fb30f7685 100644 --- a/runtime/src/hardened_unpack.rs +++ b/runtime/src/hardened_unpack.rs @@ -255,6 +255,7 @@ fn unpack_genesis>( fn is_valid_genesis_archive_entry(parts: &[&str], kind: tar::EntryType) -> bool { trace!("validating: {:?} {:?}", parts, kind); + #[allow(clippy::match_like_matches_macro)] match (parts, kind) { (["genesis.bin"], GNUSparse) => true, (["genesis.bin"], Regular) => true, diff --git a/runtime/src/message_processor.rs b/runtime/src/message_processor.rs index 5c47e1779b..9c35df6ec5 100644 --- a/runtime/src/message_processor.rs +++ b/runtime/src/message_processor.rs @@ -422,7 +422,7 @@ impl MessageProcessor { instruction: &'a CompiledInstruction, executable_accounts: &'a [(Pubkey, RefCell)], accounts: &'a [Rc>], - ) -> Result>, InstructionError> { + ) -> Vec> { let mut keyed_accounts = create_keyed_readonly_accounts(&executable_accounts); let mut keyed_accounts2: Vec<_> = instruction .accounts @@ -440,7 +440,7 @@ impl MessageProcessor { }) .collect(); keyed_accounts.append(&mut keyed_accounts2); - Ok(keyed_accounts) + keyed_accounts } /// Process an instruction @@ -604,7 +604,7 @@ impl MessageProcessor { // Construct keyed accounts let keyed_accounts = - Self::create_keyed_accounts(message, instruction, executable_accounts, accounts)?; + Self::create_keyed_accounts(message, instruction, executable_accounts, accounts); // Invoke callee invoke_context.push(instruction.program_id(&message.account_keys))?; @@ -794,7 +794,7 @@ impl MessageProcessor { feature_set, ); let keyed_accounts = - Self::create_keyed_accounts(message, instruction, executable_accounts, accounts)?; + Self::create_keyed_accounts(message, instruction, executable_accounts, accounts); self.process_instruction(&keyed_accounts, &instruction.data, &mut invoke_context)?; Self::verify( message, @@ -854,7 +854,6 @@ mod tests { message::Message, native_loader::create_loadable_account, }; - use std::iter::FromIterator; #[test] fn test_invoke_context() { @@ -920,8 +919,7 @@ mod tests { // modify account owned by the program accounts[owned_index].borrow_mut().data[0] = (MAX_DEPTH + owned_index) as u8; - let mut these_accounts = - Vec::from_iter(accounts[not_owned_index..owned_index + 1].iter().cloned()); + let mut these_accounts = accounts[not_owned_index..owned_index + 1].to_vec(); these_accounts.push(Rc::new(RefCell::new(Account::new( 1, 1, @@ -1805,6 +1803,7 @@ mod tests { #[test] fn test_debug() { let mut message_processor = MessageProcessor::default(); + #[allow(clippy::unnecessary_wraps)] fn mock_process_instruction( _program_id: &Pubkey, _keyed_accounts: &[KeyedAccount], @@ -1813,6 +1812,7 @@ mod tests { ) -> Result<(), InstructionError> { Ok(()) } + #[allow(clippy::unnecessary_wraps)] fn mock_ix_processor( _pubkey: &Pubkey, _ka: &[KeyedAccount], diff --git a/runtime/src/rent_collector.rs b/runtime/src/rent_collector.rs index 655ee6e0f4..462a129237 100644 --- a/runtime/src/rent_collector.rs +++ b/runtime/src/rent_collector.rs @@ -127,9 +127,11 @@ mod tests { let new_epoch = 3; let (mut created_account, mut existing_account) = { - let mut account = Account::default(); - account.lamports = old_lamports; - account.rent_epoch = old_epoch; + let account = Account { + lamports: old_lamports, + rent_epoch: old_epoch, + ..Account::default() + }; (account.clone(), account) }; diff --git a/runtime/src/serde_snapshot/tests.rs b/runtime/src/serde_snapshot/tests.rs index d9560b0328..6f3879dbb8 100644 --- a/runtime/src/serde_snapshot/tests.rs +++ b/runtime/src/serde_snapshot/tests.rs @@ -261,7 +261,7 @@ mod test_bank_serialize { // These some what long test harness is required to freeze the ABI of // Bank's serialization due to versioned nature - #[frozen_abi(digest = "8bNY87hccyDYCRar1gM3NSvpvtiUM3W3rGeJLJayz42e")] + #[frozen_abi(digest = "5NHt6PLRJPWJH9FUcweSsUWgN5hXMfXj1BduDrDHH73w")] #[derive(Serialize, AbiExample)] pub struct BankAbiTestWrapperFuture { #[serde(serialize_with = "wrapper_future")] diff --git a/runtime/src/stakes.rs b/runtime/src/stakes.rs index 216e824faf..00abfb8880 100644 --- a/runtime/src/stakes.rs +++ b/runtime/src/stakes.rs @@ -272,7 +272,7 @@ pub mod tests { ) } - // add stake to a vote_pubkey ( stake ) + // add stake to a vote_pubkey ( stake ) pub fn create_warming_stake_account( stake: u64, epoch: Epoch, @@ -295,8 +295,10 @@ pub mod tests { #[test] fn test_stakes_basic() { for i in 0..4 { - let mut stakes = Stakes::default(); - stakes.epoch = i; + let mut stakes = Stakes { + epoch: i, + ..Stakes::default() + }; let ((vote_pubkey, vote_account), (stake_pubkey, mut stake_account)) = create_staked_node_accounts(10); @@ -372,8 +374,10 @@ pub mod tests { #[test] fn test_stakes_vote_account_disappear_reappear() { - let mut stakes = Stakes::default(); - stakes.epoch = 4; + let mut stakes = Stakes { + epoch: 4, + ..Stakes::default() + }; let ((vote_pubkey, mut vote_account), (stake_pubkey, stake_account)) = create_staked_node_accounts(10); @@ -406,8 +410,10 @@ pub mod tests { #[test] fn test_stakes_change_delegate() { - let mut stakes = Stakes::default(); - stakes.epoch = 4; + let mut stakes = Stakes { + epoch: 4, + ..Stakes::default() + }; let ((vote_pubkey, vote_account), (stake_pubkey, stake_account)) = create_staked_node_accounts(10); @@ -450,8 +456,10 @@ pub mod tests { } #[test] fn test_stakes_multiple_stakers() { - let mut stakes = Stakes::default(); - stakes.epoch = 4; + let mut stakes = Stakes { + epoch: 4, + ..Stakes::default() + }; let ((vote_pubkey, vote_account), (stake_pubkey, stake_account)) = create_staked_node_accounts(10); @@ -500,8 +508,10 @@ pub mod tests { #[test] fn test_stakes_not_delegate() { - let mut stakes = Stakes::default(); - stakes.epoch = 4; + let mut stakes = Stakes { + epoch: 4, + ..Stakes::default() + }; let ((vote_pubkey, vote_account), (stake_pubkey, stake_account)) = create_staked_node_accounts(10); diff --git a/runtime/src/status_cache.rs b/runtime/src/status_cache.rs index 80da95b86d..ee59283a7f 100644 --- a/runtime/src/status_cache.rs +++ b/runtime/src/status_cache.rs @@ -226,7 +226,7 @@ impl StatusCache { ( *slot, self.roots.contains(slot), - self.slot_deltas.get(slot).unwrap_or_else(|| &empty).clone(), + self.slot_deltas.get(slot).unwrap_or(&empty).clone(), ) }) .collect() diff --git a/sdk/program/src/fee_calculator.rs b/sdk/program/src/fee_calculator.rs index 018aafffc3..a0edd64d51 100644 --- a/sdk/program/src/fee_calculator.rs +++ b/sdk/program/src/fee_calculator.rs @@ -309,9 +309,11 @@ mod tests { fn test_fee_rate_governor_derived_adjust() { solana_logger::setup(); - let mut f = FeeRateGovernor::default(); - f.target_lamports_per_signature = 100; - f.target_signatures_per_slot = 100; + let mut f = FeeRateGovernor { + target_lamports_per_signature: 100, + target_signatures_per_slot: 100, + ..FeeRateGovernor::default() + }; f = FeeRateGovernor::new_derived(&f, 0); // Ramp fees up diff --git a/sdk/program/src/rent.rs b/sdk/program/src/rent.rs index e4216e5c61..6e431fdde2 100644 --- a/sdk/program/src/rent.rs +++ b/sdk/program/src/rent.rs @@ -109,9 +109,11 @@ mod tests { (0, true) ); - let mut custom_rent = Rent::default(); - custom_rent.lamports_per_byte_year = 5; - custom_rent.exemption_threshold = 2.5; + let custom_rent = Rent { + lamports_per_byte_year: 5, + exemption_threshold: 2.5, + ..Rent::default() + }; assert_eq!( custom_rent.due(0, 2, 1.2), diff --git a/sdk/program/src/short_vec.rs b/sdk/program/src/short_vec.rs index 4e0c59dee2..87feb3a9a0 100644 --- a/sdk/program/src/short_vec.rs +++ b/sdk/program/src/short_vec.rs @@ -199,6 +199,7 @@ impl<'de, T: Deserialize<'de>> Deserialize<'de> for ShortVec { } /// Return the decoded value and how many bytes it consumed. +#[allow(clippy::result_unit_err)] pub fn decode_len(bytes: &[u8]) -> Result<(usize, usize), ()> { let mut len = 0; let mut size = 0; diff --git a/sdk/program/src/sysvar/recent_blockhashes.rs b/sdk/program/src/sysvar/recent_blockhashes.rs index 974908f6dc..ca916e331d 100644 --- a/sdk/program/src/sysvar/recent_blockhashes.rs +++ b/sdk/program/src/sysvar/recent_blockhashes.rs @@ -136,7 +136,7 @@ pub fn create_test_recent_blockhashes(start: usize) -> RecentBlockhashes { .iter() .map(|(i, hash, fee_calc)| IterItem(*i, hash, fee_calc)) .collect(); - RecentBlockhashes::from_iter(bhq.into_iter()) + bhq.into_iter().collect() } #[cfg(test)] diff --git a/sdk/src/hard_forks.rs b/sdk/src/hard_forks.rs index 42a2b2e568..5781b60a26 100644 --- a/sdk/src/hard_forks.rs +++ b/sdk/src/hard_forks.rs @@ -22,6 +22,7 @@ impl HardForks { } else { self.hard_forks.push((new_slot, 1)); } + #[allow(clippy::stable_sort_primitive)] self.hard_forks.sort(); } diff --git a/sdk/src/nonce_keyed_account.rs b/sdk/src/nonce_keyed_account.rs index e44feaecd9..43eb5fe8f5 100644 --- a/sdk/src/nonce_keyed_account.rs +++ b/sdk/src/nonce_keyed_account.rs @@ -178,10 +178,9 @@ mod test { nonce::{self, State}, nonce_account::verify_nonce_account, system_instruction::NonceError, - sysvar::recent_blockhashes::{create_test_recent_blockhashes, RecentBlockhashes}, + sysvar::recent_blockhashes::create_test_recent_blockhashes, }; use solana_program::hash::Hash; - use std::iter::FromIterator; #[test] fn default_is_uninitialized() { @@ -322,7 +321,7 @@ mod test { keyed_account .initialize_nonce_account(&authorized, &recent_blockhashes, &rent) .unwrap(); - let recent_blockhashes = RecentBlockhashes::from_iter(vec![].into_iter()); + let recent_blockhashes = vec![].into_iter().collect(); let result = keyed_account.advance_nonce_account(&recent_blockhashes, &signers); assert_eq!(result, Err(NonceError::NoRecentBlockhashes.into())); }) @@ -764,7 +763,7 @@ mod test { with_test_keyed_account(min_lamports + 42, true, |keyed_account| { let mut signers = HashSet::new(); signers.insert(*keyed_account.signer_key().unwrap()); - let recent_blockhashes = RecentBlockhashes::from_iter(vec![].into_iter()); + let recent_blockhashes = vec![].into_iter().collect(); let authorized = *keyed_account.unsigned_key(); let result = keyed_account.initialize_nonce_account(&authorized, &recent_blockhashes, &rent); diff --git a/sdk/src/packet.rs b/sdk/src/packet.rs index 3e667684ed..8e10470f35 100644 --- a/sdk/src/packet.rs +++ b/sdk/src/packet.rs @@ -85,7 +85,7 @@ impl PartialEq for Packet { fn eq(&self, other: &Packet) -> bool { let self_data: &[u8] = self.data.as_ref(); let other_data: &[u8] = other.data.as_ref(); - self.meta == other.meta && self_data[..self.meta.size] == other_data[..other.meta.size] + self.meta == other.meta && self_data[..self.meta.size] == other_data[..self.meta.size] } } diff --git a/sdk/src/process_instruction.rs b/sdk/src/process_instruction.rs index 10bbcc6da3..c5e0f93749 100644 --- a/sdk/src/process_instruction.rs +++ b/sdk/src/process_instruction.rs @@ -282,7 +282,7 @@ pub struct MockInvokeContext { pub bpf_compute_budget: BpfComputeBudget, pub compute_meter: MockComputeMeter, pub programs: Vec<(Pubkey, ProcessInstructionWithContext)>, - invoke_depth: usize, + pub invoke_depth: usize, } impl Default for MockInvokeContext { fn default() -> Self { diff --git a/sdk/src/recent_blockhashes_account.rs b/sdk/src/recent_blockhashes_account.rs index b91f13773f..2efd8c1cc8 100644 --- a/sdk/src/recent_blockhashes_account.rs +++ b/sdk/src/recent_blockhashes_account.rs @@ -11,7 +11,7 @@ where let sorted = BinaryHeap::from_iter(recent_blockhash_iter); let sorted_iter = IntoIterSorted::new(sorted); let recent_blockhash_iter = sorted_iter.take(MAX_ENTRIES); - let recent_blockhashes = RecentBlockhashes::from_iter(recent_blockhash_iter); + let recent_blockhashes: RecentBlockhashes = recent_blockhash_iter.collect(); to_account(&recent_blockhashes, account) } diff --git a/stake-o-matic/src/main.rs b/stake-o-matic/src/main.rs index af59f64271..3a90e3754e 100644 --- a/stake-o-matic/src/main.rs +++ b/stake-o-matic/src/main.rs @@ -27,7 +27,6 @@ use std::{ collections::{HashMap, HashSet}, error, fs::File, - iter::FromIterator, path::PathBuf, process, str::FromStr, @@ -296,7 +295,7 @@ fn classify_block_producers( }; let confirmed_blocks = rpc_client.get_confirmed_blocks(first_slot, Some(last_slot_in_epoch))?; - let confirmed_blocks: HashSet = HashSet::from_iter(confirmed_blocks.into_iter()); + let confirmed_blocks: HashSet = confirmed_blocks.into_iter().collect(); let mut poor_block_producers = HashSet::new(); let mut quality_block_producers = HashSet::new(); diff --git a/storage-bigtable/src/bigtable.rs b/storage-bigtable/src/bigtable.rs index c774b2370a..259aa20cbe 100644 --- a/storage-bigtable/src/bigtable.rs +++ b/storage-bigtable/src/bigtable.rs @@ -445,7 +445,7 @@ impl BigTable { rows.into_iter() .next() .map(|r| r.1) - .ok_or_else(|| Error::RowNotFound) + .ok_or(Error::RowNotFound) } /// Store data for one or more `table` rows in the `family_name` Column family diff --git a/streamer/src/recvmmsg.rs b/streamer/src/recvmmsg.rs index b30e6e376a..fb6da391ed 100644 --- a/streamer/src/recvmmsg.rs +++ b/streamer/src/recvmmsg.rs @@ -37,7 +37,7 @@ pub fn recv_mmsg(socket: &UdpSocket, packets: &mut [Packet]) -> io::Result<(usiz #[cfg(target_os = "linux")] pub fn recv_mmsg(sock: &UdpSocket, packets: &mut [Packet]) -> io::Result<(usize, usize)> { use libc::{ - c_void, iovec, mmsghdr, recvmmsg, sockaddr_in, socklen_t, time_t, timespec, MSG_WAITFORONE, + c_void, iovec, mmsghdr, recvmmsg, sockaddr_in, socklen_t, timespec, MSG_WAITFORONE, }; use nix::sys::socket::InetAddr; use std::mem; @@ -62,7 +62,7 @@ pub fn recv_mmsg(sock: &UdpSocket, packets: &mut [Packet]) -> io::Result<(usize, hdrs[i].msg_hdr.msg_iovlen = 1; } let mut ts = timespec { - tv_sec: 1 as time_t, + tv_sec: 1, tv_nsec: 0, }; diff --git a/streamer/src/streamer.rs b/streamer/src/streamer.rs index 759697a8ef..6bbdb9fcf0 100644 --- a/streamer/src/streamer.rs +++ b/streamer/src/streamer.rs @@ -169,7 +169,7 @@ mod test { use std::sync::Arc; use std::time::Duration; - fn get_msgs(r: PacketReceiver, num: &mut usize) -> Result<()> { + fn get_msgs(r: PacketReceiver, num: &mut usize) { for _ in 0..10 { let m = r.recv_timeout(Duration::new(1, 0)); if m.is_err() { @@ -182,9 +182,8 @@ mod test { break; } } - - Ok(()) } + #[test] fn streamer_debug() { write!(io::sink(), "{:?}", Packet::default()).unwrap(); @@ -218,7 +217,7 @@ mod test { }; let mut num = 5; - get_msgs(r_reader, &mut num).expect("get_msgs"); + get_msgs(r_reader, &mut num); assert_eq!(num, 0); exit.store(true, Ordering::Relaxed); t_receiver.join().expect("join"); diff --git a/tokens/src/commands.rs b/tokens/src/commands.rs index 45b170c75d..a3affe6f8b 100644 --- a/tokens/src/commands.rs +++ b/tokens/src/commands.rs @@ -265,7 +265,7 @@ fn build_messages( return Err(Error::ExitSignal); } let new_stake_account_keypair = Keypair::new(); - let lockup_date = if allocation.lockup_date == "" { + let lockup_date = if allocation.lockup_date.is_empty() { None } else { Some(allocation.lockup_date.parse::>().unwrap()) @@ -336,7 +336,7 @@ fn send_messages( signers.push(&*stake_args.stake_authority); signers.push(&*stake_args.withdraw_authority); signers.push(&new_stake_account_keypair); - if allocation.lockup_date != "" { + if !allocation.lockup_date.is_empty() { if let Some(lockup_authority) = &stake_args.lockup_authority { signers.push(&**lockup_authority); } else { diff --git a/transaction-status/src/parse_accounts.rs b/transaction-status/src/parse_accounts.rs index d20afd067f..ebef018e71 100644 --- a/transaction-status/src/parse_accounts.rs +++ b/transaction-status/src/parse_accounts.rs @@ -31,13 +31,15 @@ mod test { let pubkey1 = solana_sdk::pubkey::new_rand(); let pubkey2 = solana_sdk::pubkey::new_rand(); let pubkey3 = solana_sdk::pubkey::new_rand(); - let mut message = Message::default(); - message.header = MessageHeader { - num_required_signatures: 2, - num_readonly_signed_accounts: 1, - num_readonly_unsigned_accounts: 1, + let message = Message { + header: MessageHeader { + num_required_signatures: 2, + num_readonly_signed_accounts: 1, + num_readonly_unsigned_accounts: 1, + }, + account_keys: vec![pubkey0, pubkey1, pubkey2, pubkey3], + ..Message::default() }; - message.account_keys = vec![pubkey0, pubkey1, pubkey2, pubkey3]; assert_eq!( parse_accounts(&message), diff --git a/transaction-status/src/parse_instruction.rs b/transaction-status/src/parse_instruction.rs index 972b15b3db..b3a286a183 100644 --- a/transaction-status/src/parse_instruction.rs +++ b/transaction-status/src/parse_instruction.rs @@ -82,7 +82,7 @@ pub fn parse( ) -> Result { let program_name = PARSABLE_PROGRAM_IDS .get(program_id) - .ok_or_else(|| ParseInstructionError::ProgramNotParsable)?; + .ok_or(ParseInstructionError::ProgramNotParsable)?; let parsed_json = match program_name { ParsableProgram::SplMemo => parse_memo(instruction), ParsableProgram::SplToken => serde_json::to_value(parse_token(instruction, account_keys)?)?,