From 9524c9dbff3ff8c93cd36675a895ebf2a022e6cd Mon Sep 17 00:00:00 2001 From: behzad nouri Date: Tue, 6 Dec 2022 09:30:06 -0500 Subject: [PATCH] patches errors from clippy::uninlined_format_args https://rust-lang.github.io/rust-clippy/master/index.html#uninlined_format_args --- account-decoder/src/parse_account_data.rs | 2 +- accounts-bench/src/main.rs | 10 +- accounts-cluster-bench/src/main.rs | 18 +- banking-bench/src/main.rs | 4 +- bench-tps/src/bench_tps_client/bank_client.rs | 4 +- bench-tps/src/bench_tps_client/rpc_client.rs | 2 +- bench-tps/src/bench_tps_client/thin_client.rs | 2 +- bench-tps/src/bench_tps_client/tpu_client.rs | 2 +- bench-tps/src/cli.rs | 2 +- bench-tps/src/keypairs.rs | 4 +- bench-tps/src/main.rs | 13 +- bloom/src/bloom.rs | 12 +- bucket_map/src/bucket_map.rs | 2 +- clap-utils/src/input_parsers.rs | 6 +- clap-utils/src/input_validators.rs | 73 +++---- clap-utils/src/keypair.rs | 32 ++- clap-v3-utils/src/input_parsers.rs | 6 +- clap-v3-utils/src/input_validators.rs | 73 +++---- clap-v3-utils/src/keypair.rs | 32 ++- cli-config/src/lib.rs | 4 +- cli-output/src/cli_output.rs | 96 +++++---- cli-output/src/cli_version.rs | 2 +- cli-output/src/display.rs | 68 +++---- cli-output/src/lib.rs | 4 +- cli/src/address_lookup_table.rs | 10 +- cli/src/cli.rs | 8 +- cli/src/cluster_query.rs | 133 ++++++------- cli/src/feature.rs | 29 +-- cli/src/inflation.rs | 4 +- cli/src/main.rs | 8 +- cli/src/nonce.rs | 13 +- cli/src/program.rs | 103 ++++------ cli/src/stake.rs | 94 ++++----- cli/src/validator_info.rs | 43 ++-- cli/src/vote.rs | 20 +- cli/src/wallet.rs | 17 +- cli/tests/program.rs | 4 +- client/src/connection_cache.rs | 2 +- client/src/nonblocking/tpu_client.rs | 14 +- client/src/thin_client.rs | 8 +- core/src/banking_stage.rs | 17 +- core/src/consensus.rs | 27 +-- core/src/duplicate_repair_status.rs | 8 +- core/src/heaviest_subtree_fork_choice.rs | 5 +- core/src/optimistic_confirmation_verifier.rs | 2 +- core/src/poh_timing_reporter.rs | 2 +- core/src/progress_map.rs | 2 +- core/src/repair_generic_traversal.rs | 3 +- core/src/replay_stage.rs | 12 +- core/src/retransmit_stage.rs | 2 +- core/src/snapshot_packager_service.rs | 4 +- core/src/tower_storage.rs | 10 +- core/src/validator.rs | 45 ++--- core/src/window_service.rs | 2 +- core/tests/ledger_cleanup.rs | 2 +- core/tests/snapshots.rs | 8 +- dos/src/main.rs | 6 +- download-utils/src/lib.rs | 12 +- entry/src/entry.rs | 4 +- faucet/src/faucet.rs | 3 +- frozen-abi/macro/src/lib.rs | 4 +- frozen-abi/src/abi_digester.rs | 25 ++- frozen-abi/src/abi_example.rs | 10 +- genesis-utils/src/lib.rs | 11 +- genesis/src/address_generator.rs | 2 +- genesis/src/main.rs | 15 +- .../src/geyser_plugin_service.rs | 17 +- gossip/src/cluster_info.rs | 16 +- gossip/src/crds.rs | 10 +- gossip/src/crds_gossip_pull.rs | 6 +- gossip/src/crds_value.rs | 4 +- gossip/src/main.rs | 23 +-- gossip/tests/cluster_info.rs | 3 +- gossip/tests/crds_gossip.rs | 2 +- install/src/bin/solana-install-init.rs | 2 +- install/src/command.rs | 132 ++++++------- install/src/config.rs | 17 +- install/src/lib.rs | 4 +- install/src/stop_process.rs | 8 +- keygen/src/keygen.rs | 14 +- ledger-tool/src/bigtable.rs | 31 ++- ledger-tool/src/main.rs | 186 ++++++++---------- ledger/src/bigtable_delete.rs | 2 +- ledger/src/bigtable_upload.rs | 13 +- ledger/src/blockstore.rs | 58 +++--- ledger/src/blockstore_options.rs | 2 +- ledger/src/blockstore_processor.rs | 14 +- ledger/src/shredder.rs | 2 +- ledger/src/sigverify_shreds.rs | 2 +- .../src/local_cluster_snapshot_utils.rs | 4 +- local-cluster/tests/common.rs | 4 +- local-cluster/tests/local_cluster.rs | 5 +- local-cluster/tests/local_cluster_slow_2.rs | 2 +- log-analyzer/src/main.rs | 2 +- measure/src/measure.rs | 10 +- merkle-root-bench/src/main.rs | 2 +- metrics/src/metrics.rs | 12 +- metrics/src/poh_timing_point.rs | 18 +- net-shaper/src/main.rs | 18 +- net-utils/src/bin/ip_address.rs | 6 +- net-utils/src/bin/ip_address_server.rs | 2 +- net-utils/src/ip_echo_server.rs | 4 +- net-utils/src/lib.rs | 28 ++- notifier/src/lib.rs | 21 +- perf/src/cuda_runtime.rs | 9 +- perf/src/sigverify.rs | 2 +- perf/src/thread.rs | 2 +- program-runtime/src/invoke_context.rs | 2 +- program-test/src/lib.rs | 22 +-- programs/bpf-loader-tests/tests/common.rs | 3 +- programs/bpf_loader/gen-syscall-list/build.rs | 2 +- programs/bpf_loader/src/lib.rs | 2 +- programs/bpf_loader/src/serialization.rs | 3 +- programs/bpf_loader/src/syscalls/logging.rs | 5 +- programs/stake/src/stake_state.rs | 4 +- .../src/nonblocking/pubsub_client.rs | 6 +- pubsub-client/src/pubsub_client.rs | 14 +- quic-client/src/nonblocking/quic_client.rs | 2 +- rbpf-cli/src/main.rs | 10 +- remote-wallet/src/ledger.rs | 5 +- remote-wallet/src/locator.rs | 10 +- remote-wallet/src/remote_wallet.rs | 2 +- rpc-client-api/src/client_error.rs | 10 +- rpc-client-api/src/custom_error.rs | 26 ++- rpc-client-api/src/request.rs | 4 +- rpc-client-api/src/response.rs | 2 +- rpc-client-api/src/version_req.rs | 2 +- rpc-client-nonce-utils/src/blockhash_query.rs | 4 +- rpc-client-nonce-utils/src/lib.rs | 4 +- .../src/nonblocking/blockhash_query.rs | 2 +- rpc-client-nonce-utils/src/nonblocking/mod.rs | 4 +- rpc-client/src/nonblocking/rpc_client.rs | 42 ++-- .../optimistically_confirmed_bank_tracker.rs | 2 +- rpc/src/rpc.rs | 186 +++++++----------- rpc/src/rpc_pubsub.rs | 11 +- rpc/src/rpc_pubsub_service.rs | 2 +- rpc/src/rpc_subscriptions.rs | 24 ++- runtime/benches/append_vec.rs | 2 +- runtime/src/accounts.rs | 3 +- runtime/src/accounts_background_service.rs | 2 +- runtime/src/accounts_db.rs | 61 +++--- runtime/src/accounts_hash.rs | 19 +- runtime/src/accounts_index_storage.rs | 2 +- runtime/src/append_vec.rs | 8 +- runtime/src/append_vec/test_utils.rs | 4 +- runtime/src/bank.rs | 47 ++--- runtime/src/bucket_map_holder.rs | 2 +- runtime/src/cache_hash_data.rs | 12 +- runtime/src/epoch_stakes.rs | 2 +- runtime/src/hardened_unpack.rs | 18 +- runtime/src/in_mem_accounts_index.rs | 23 +-- runtime/src/pubkey_bins.rs | 2 +- runtime/src/serde_snapshot.rs | 3 +- runtime/src/shared_buffer_reader.rs | 4 +- runtime/src/snapshot_utils.rs | 6 +- runtime/src/snapshot_utils/archive_format.rs | 2 +- .../snapshot_storage_rebuilder.rs | 3 +- runtime/src/sorted_storages.rs | 8 +- runtime/src/stakes.rs | 4 +- runtime/src/status_cache.rs | 8 +- sdk/cargo-build-sbf/src/main.rs | 18 +- sdk/cargo-test-bpf/src/main.rs | 2 +- sdk/cargo-test-sbf/src/main.rs | 2 +- sdk/gen-headers/src/main.rs | 24 ++- sdk/program/src/account_info.rs | 6 +- sdk/program/src/borsh.rs | 2 +- sdk/program/src/debug_account_data.rs | 2 +- sdk/program/src/message/legacy.rs | 2 +- sdk/program/src/program_error.rs | 2 +- sdk/program/src/program_stubs.rs | 5 +- sdk/program/src/serde_varint.rs | 16 +- sdk/program/src/slot_history.rs | 10 +- sdk/src/commitment_config.rs | 2 +- sdk/src/derivation_path.rs | 25 ++- sdk/src/genesis_config.rs | 10 +- sdk/src/pubkey.rs | 2 +- sdk/src/signer/keypair.rs | 2 +- sdk/src/transaction/mod.rs | 9 +- stake-accounts/src/main.rs | 8 +- storage-bigtable/src/access_token.rs | 8 +- storage-bigtable/src/bigtable.rs | 12 +- storage-bigtable/src/compression.rs | 2 +- storage-bigtable/src/lib.rs | 7 +- storage-bigtable/src/root_ca_certificate.rs | 2 +- storage-proto/src/convert.rs | 12 +- streamer/src/sendmmsg.rs | 2 +- streamer/src/streamer.rs | 2 +- sys-tuner/src/main.rs | 6 +- test-validator/src/lib.rs | 20 +- thin-client/src/thin_client.rs | 8 +- tokens/src/commands.rs | 4 +- tokens/src/db.rs | 5 +- tokens/src/spl_token.rs | 4 +- tokens/src/token_display.rs | 4 +- tpu-client/src/nonblocking/tpu_client.rs | 14 +- tpu-client/src/tpu_connection_cache.rs | 2 +- transaction-dos/src/main.rs | 20 +- transaction-status/src/extract_memos.rs | 2 +- transaction-status/src/lib.rs | 2 +- transaction-status/src/parse_instruction.rs | 2 +- .../src/parse_token/extension/cpi_guard.rs | 2 +- .../extension/default_account_state.rs | 4 +- .../parse_token/extension/memo_transfer.rs | 2 +- upload-perf/src/upload-perf.rs | 12 +- validator/src/admin_rpc_service.rs | 17 +- validator/src/bin/solana-test-validator.rs | 24 +-- validator/src/bootstrap.rs | 25 ++- validator/src/cli.rs | 16 +- validator/src/dashboard.rs | 18 +- validator/src/lib.rs | 8 +- validator/src/main.rs | 120 +++++------ version/src/lib.rs | 2 +- watchtower/src/main.rs | 12 +- zk-token-sdk/src/encryption/discrete_log.rs | 10 +- 214 files changed, 1306 insertions(+), 1862 deletions(-) diff --git a/account-decoder/src/parse_account_data.rs b/account-decoder/src/parse_account_data.rs index 173ad03fb..23db5f311 100644 --- a/account-decoder/src/parse_account_data.rs +++ b/account-decoder/src/parse_account_data.rs @@ -119,7 +119,7 @@ pub fn parse_account_data( ParsableAccount::Vote => serde_json::to_value(parse_vote(data)?)?, }; Ok(ParsedAccount { - program: format!("{:?}", program_name).to_kebab_case(), + program: format!("{program_name:?}").to_kebab_case(), parsed: parsed_json, space: data.len() as u64, }) diff --git a/accounts-bench/src/main.rs b/accounts-bench/src/main.rs index 8f0201fdf..4863465c9 100644 --- a/accounts-bench/src/main.rs +++ b/accounts-bench/src/main.rs @@ -60,13 +60,13 @@ fn main() { let num_accounts = value_t!(matches, "num_accounts", usize).unwrap_or(10_000); let iterations = value_t!(matches, "iterations", usize).unwrap_or(20); let clean = matches.is_present("clean"); - println!("clean: {:?}", clean); + println!("clean: {clean:?}"); let path = PathBuf::from(env::var("FARF_DIR").unwrap_or_else(|_| "farf".to_owned())) .join("accounts-bench"); - println!("cleaning file system: {:?}", path); + println!("cleaning file system: {path:?}"); if fs::remove_dir_all(path.clone()).is_err() { - println!("Warning: Couldn't remove {:?}", path); + println!("Warning: Couldn't remove {path:?}"); } let accounts = Accounts::new_with_config_for_benches( vec![path], @@ -75,7 +75,7 @@ fn main() { false, AccountShrinkThreshold::default(), ); - println!("Creating {} accounts", num_accounts); + println!("Creating {num_accounts} accounts"); let mut create_time = Measure::start("create accounts"); let pubkeys: Vec<_> = (0..num_slots) .into_par_iter() @@ -112,7 +112,7 @@ fn main() { let mut time = Measure::start("clean"); accounts.accounts_db.clean_accounts_for_tests(); time.stop(); - println!("{}", time); + println!("{time}"); for slot in 0..num_slots { update_accounts_bench(&accounts, &pubkeys, ((x + 1) * num_slots + slot) as u64); accounts.add_root((x * num_slots + slot) as u64); diff --git a/accounts-cluster-bench/src/main.rs b/accounts-cluster-bench/src/main.rs index 8af302e11..3de2020dc 100644 --- a/accounts-cluster-bench/src/main.rs +++ b/accounts-cluster-bench/src/main.rs @@ -67,22 +67,20 @@ pub fn airdrop_lamports( } if tries >= 5 { panic!( - "Error requesting airdrop: to addr: {:?} amount: {} {:?}", - faucet_addr, airdrop_amount, result + "Error requesting airdrop: to addr: {faucet_addr:?} amount: {airdrop_amount} {result:?}" ) } } } Err(err) => { panic!( - "Error requesting airdrop: {:?} to addr: {:?} amount: {}", - err, faucet_addr, airdrop_amount + "Error requesting airdrop: {err:?} to addr: {faucet_addr:?} amount: {airdrop_amount}" ); } }; let current_balance = client.get_balance(&id.pubkey()).unwrap_or_else(|e| { - panic!("airdrop error {}", e); + panic!("airdrop error {e}"); }); info!("current balance {}...", current_balance); @@ -575,14 +573,14 @@ fn main() { let mut entrypoint_addr = SocketAddr::from(([127, 0, 0, 1], port)); if let Some(addr) = matches.value_of("entrypoint") { entrypoint_addr = solana_net_utils::parse_host_port(addr).unwrap_or_else(|e| { - eprintln!("failed to parse entrypoint address: {}", e); + eprintln!("failed to parse entrypoint address: {e}"); exit(1) }); } let mut faucet_addr = SocketAddr::from(([127, 0, 0, 1], FAUCET_PORT)); if let Some(addr) = matches.value_of("faucet_addr") { faucet_addr = solana_net_utils::parse_host_port(addr).unwrap_or_else(|e| { - eprintln!("failed to parse entrypoint address: {}", e); + eprintln!("failed to parse entrypoint address: {e}"); exit(1) }); } @@ -594,7 +592,7 @@ fn main() { let iterations = value_t!(matches, "iterations", usize).unwrap_or(10); let num_instructions = value_t!(matches, "num_instructions", usize).unwrap_or(1); if num_instructions == 0 || num_instructions > 500 { - eprintln!("bad num_instructions: {}", num_instructions); + eprintln!("bad num_instructions: {num_instructions}"); exit(1); } @@ -604,7 +602,7 @@ fn main() { .iter() .map(|keypair_string| { read_keypair_file(keypair_string) - .unwrap_or_else(|_| panic!("bad keypair {:?}", keypair_string)) + .unwrap_or_else(|_| panic!("bad keypair {keypair_string:?}")) }) .collect(); let mut payer_keypair_refs: Vec<&Keypair> = vec![]; @@ -626,7 +624,7 @@ fn main() { SocketAddrSpace::Unspecified, ) .unwrap_or_else(|err| { - eprintln!("Failed to discover {} node: {:?}", entrypoint_addr, err); + eprintln!("Failed to discover {entrypoint_addr} node: {err:?}"); exit(1); }); diff --git a/banking-bench/src/main.rs b/banking-bench/src/main.rs index f1077140e..80294ad73 100644 --- a/banking-bench/src/main.rs +++ b/banking-bench/src/main.rs @@ -384,7 +384,7 @@ fn main() { .iter() .for_each(|tx| { let res = bank.process_transaction(tx); - assert!(res.is_ok(), "sanity test transactions error: {:?}", res); + assert!(res.is_ok(), "sanity test transactions error: {res:?}"); }); }); bank.clear_signatures(); @@ -395,7 +395,7 @@ fn main() { let res = bank.process_transactions(packets_for_single_iteration.transactions.iter()); for r in res { - assert!(r.is_ok(), "sanity parallel execution error: {:?}", r); + assert!(r.is_ok(), "sanity parallel execution error: {r:?}"); } bank.clear_signatures(); }); diff --git a/bench-tps/src/bench_tps_client/bank_client.rs b/bench-tps/src/bench_tps_client/bank_client.rs index a61cc1b7d..1aef7284c 100644 --- a/bench-tps/src/bench_tps_client/bank_client.rs +++ b/bench-tps/src/bench_tps_client/bank_client.rs @@ -89,7 +89,7 @@ impl BenchTpsClient for BankClient { .map_err(|err| err.into()) .and_then(|account| { account.ok_or_else(|| { - BenchTpsError::Custom(format!("AccountNotFound: pubkey={}", pubkey)) + BenchTpsError::Custom(format!("AccountNotFound: pubkey={pubkey}")) }) }) } @@ -103,7 +103,7 @@ impl BenchTpsClient for BankClient { .map_err(|err| err.into()) .and_then(|account| { account.ok_or_else(|| { - BenchTpsError::Custom(format!("AccountNotFound: pubkey={}", pubkey)) + BenchTpsError::Custom(format!("AccountNotFound: pubkey={pubkey}")) }) }) } diff --git a/bench-tps/src/bench_tps_client/rpc_client.rs b/bench-tps/src/bench_tps_client/rpc_client.rs index 4f5007ad9..57e97120d 100644 --- a/bench-tps/src/bench_tps_client/rpc_client.rs +++ b/bench-tps/src/bench_tps_client/rpc_client.rs @@ -95,7 +95,7 @@ impl BenchTpsClient for RpcClient { .map_err(|err| err.into()) .and_then(|account| { account.ok_or_else(|| { - BenchTpsError::Custom(format!("AccountNotFound: pubkey={}", pubkey)) + BenchTpsError::Custom(format!("AccountNotFound: pubkey={pubkey}")) }) }) } diff --git a/bench-tps/src/bench_tps_client/thin_client.rs b/bench-tps/src/bench_tps_client/thin_client.rs index be4770849..6696774d6 100644 --- a/bench-tps/src/bench_tps_client/thin_client.rs +++ b/bench-tps/src/bench_tps_client/thin_client.rs @@ -100,7 +100,7 @@ impl BenchTpsClient for ThinClient { .map_err(|err| err.into()) .and_then(|account| { account.ok_or_else(|| { - BenchTpsError::Custom(format!("AccountNotFound: pubkey={}", pubkey)) + BenchTpsError::Custom(format!("AccountNotFound: pubkey={pubkey}")) }) }) } diff --git a/bench-tps/src/bench_tps_client/tpu_client.rs b/bench-tps/src/bench_tps_client/tpu_client.rs index b4f06ac6b..0f348837a 100644 --- a/bench-tps/src/bench_tps_client/tpu_client.rs +++ b/bench-tps/src/bench_tps_client/tpu_client.rs @@ -112,7 +112,7 @@ impl BenchTpsClient for TpuClient { .map_err(|err| err.into()) .and_then(|account| { account.ok_or_else(|| { - BenchTpsError::Custom(format!("AccountNotFound: pubkey={}", pubkey)) + BenchTpsError::Custom(format!("AccountNotFound: pubkey={pubkey}")) }) }) } diff --git a/bench-tps/src/cli.rs b/bench-tps/src/cli.rs index ed4730fe1..3f23ae70d 100644 --- a/bench-tps/src/cli.rs +++ b/bench-tps/src/cli.rs @@ -400,7 +400,7 @@ pub fn extract_args(matches: &ArgMatches) -> Config { if let Some(addr) = matches.value_of("entrypoint") { args.entrypoint_addr = solana_net_utils::parse_host_port(addr).unwrap_or_else(|e| { - eprintln!("failed to parse entrypoint address: {}", e); + eprintln!("failed to parse entrypoint address: {e}"); exit(1) }); } diff --git a/bench-tps/src/keypairs.rs b/bench-tps/src/keypairs.rs index 601f74c06..e55a8597c 100644 --- a/bench-tps/src/keypairs.rs +++ b/bench-tps/src/keypairs.rs @@ -58,14 +58,14 @@ where last_balance, ) .unwrap_or_else(|e| { - eprintln!("Error could not fund keys: {:?}", e); + eprintln!("Error could not fund keys: {e:?}"); exit(1); }); keypairs } else { generate_and_fund_keypairs(client, id, keypair_count, num_lamports_per_account) .unwrap_or_else(|e| { - eprintln!("Error could not fund keys: {:?}", e); + eprintln!("Error could not fund keys: {e:?}"); exit(1); }) } diff --git a/bench-tps/src/main.rs b/bench-tps/src/main.rs index 06488ed93..534f661d7 100644 --- a/bench-tps/src/main.rs +++ b/bench-tps/src/main.rs @@ -62,7 +62,7 @@ fn create_client( let nodes = discover_cluster(entrypoint_addr, num_nodes, SocketAddrSpace::Unspecified) .unwrap_or_else(|err| { - eprintln!("Failed to discover {} nodes: {:?}", num_nodes, err); + eprintln!("Failed to discover {num_nodes} nodes: {err:?}"); exit(1); }); if multi_client { @@ -70,8 +70,7 @@ fn create_client( get_multi_client(&nodes, &SocketAddrSpace::Unspecified, connection_cache); if nodes.len() < num_clients { eprintln!( - "Error: Insufficient nodes discovered. Expecting {} or more", - num_nodes + "Error: Insufficient nodes discovered. Expecting {num_nodes} or more" ); exit(1); } @@ -90,7 +89,7 @@ fn create_client( } } Arc::new(target_client.unwrap_or_else(|| { - eprintln!("Target node {} not found", target_node); + eprintln!("Target node {target_node} not found"); exit(1); })) } else { @@ -120,7 +119,7 @@ fn create_client( Arc::new(connection_cache), ) .unwrap_or_else(|err| { - eprintln!("Could not create TpuClient {:?}", err); + eprintln!("Could not create TpuClient {err:?}"); exit(1); }), ) @@ -198,14 +197,14 @@ fn main() { let rpc_tpu_sockets: Option<(SocketAddr, SocketAddr)> = if let Ok(rpc_addr) = value_t!(matches, "rpc_addr", String) { let rpc = rpc_addr.parse().unwrap_or_else(|e| { - eprintln!("RPC address should parse as socketaddr {:?}", e); + eprintln!("RPC address should parse as socketaddr {e:?}"); exit(1); }); let tpu = value_t!(matches, "tpu_addr", String) .unwrap() .parse() .unwrap_or_else(|e| { - eprintln!("TPU address should parse to a socket: {:?}", e); + eprintln!("TPU address should parse to a socket: {e:?}"); exit(1); }); Some((rpc, tpu)) diff --git a/bloom/src/bloom.rs b/bloom/src/bloom.rs index 1c95e842d..7d1f98403 100644 --- a/bloom/src/bloom.rs +++ b/bloom/src/bloom.rs @@ -308,7 +308,7 @@ mod test { let mut b: Bloom = Bloom::new(3, vec![100]); b.add(&Hash::default()); assert_eq!( - format!("{:?}", b), + format!("{b:?}"), "Bloom { keys.len: 1 bits.len: 3 num_set: 1 bits: 001 }" ); @@ -316,7 +316,7 @@ mod test { b.add(&Hash::default()); b.add(&hash(&[1, 2])); assert_eq!( - format!("{:?}", b), + format!("{b:?}"), "Bloom { keys.len: 1 bits.len: 1000 num_set: 2 bits: 0000000000.. }" ); } @@ -345,7 +345,7 @@ mod test { .take(10_000) .filter(|hash_value| bloom.contains(hash_value)) .count(); - assert!(false_positive < 2_000, "false_positive: {}", false_positive); + assert!(false_positive < 2_000, "false_positive: {false_positive}"); } #[test] @@ -360,7 +360,7 @@ mod test { bloom.add(hash_value); } let num_bits_set = bloom.num_bits_set; - assert!(num_bits_set > 2000, "# bits set: {}", num_bits_set); + assert!(num_bits_set > 2000, "# bits set: {num_bits_set}"); // Round-trip with no inserts. let bloom: AtomicBloom<_> = bloom.into(); assert_eq!(bloom.num_bits, 9731); @@ -408,7 +408,7 @@ mod test { .take(10_000) .filter(|hash_value| bloom.contains(hash_value)) .count(); - assert!(false_positive < 2000, "false_positive: {}", false_positive); + assert!(false_positive < 2000, "false_positive: {false_positive}"); let bloom: Bloom<_> = bloom.into(); assert_eq!(bloom.bits.len(), 9731); assert!(bloom.num_bits_set > num_bits_set); @@ -427,7 +427,7 @@ mod test { .take(10_000) .filter(|hash_value| bloom.contains(hash_value)) .count(); - assert!(false_positive < 2000, "false_positive: {}", false_positive); + assert!(false_positive < 2000, "false_positive: {false_positive}"); // Assert that the bits vector precisely match if no atomic ops were // used. let bits = bloom.bits; diff --git a/bucket_map/src/bucket_map.rs b/bucket_map/src/bucket_map.rs index a3811a934..460f47091 100644 --- a/bucket_map/src/bucket_map.rs +++ b/bucket_map/src/bucket_map.rs @@ -559,7 +559,7 @@ mod tests { map.insert(&k, (&v, rc)) } else { map.update(&k, |current| { - assert_eq!(current, v_old.map(|(v, rc)| (&v[..], *rc)), "{}", k); + assert_eq!(current, v_old.map(|(v, rc)| (&v[..], *rc)), "{k}"); Some((v.clone(), rc)) }) } diff --git a/clap-utils/src/input_parsers.rs b/clap-utils/src/input_parsers.rs index 1965d6f7b..15a1b3acd 100644 --- a/clap-utils/src/input_parsers.rs +++ b/clap-utils/src/input_parsers.rs @@ -219,7 +219,7 @@ mod tests { use std::env; let out_dir = env::var("FARF_DIR").unwrap_or_else(|_| "farf".to_string()); - format!("{}/tmp/{}-{}", out_dir, name, pubkey) + format!("{out_dir}/tmp/{name}-{pubkey}") } #[test] @@ -338,8 +338,8 @@ mod tests { let key2 = solana_sdk::pubkey::new_rand(); let sig1 = Keypair::new().sign_message(&[0u8]); let sig2 = Keypair::new().sign_message(&[1u8]); - let signer1 = format!("{}={}", key1, sig1); - let signer2 = format!("{}={}", key2, sig2); + let signer1 = format!("{key1}={sig1}"); + let signer2 = format!("{key2}={sig2}"); let matches = app().clone().get_matches_from(vec![ "test", "--multiple", diff --git a/clap-utils/src/input_validators.rs b/clap-utils/src/input_validators.rs index 15e8a87a4..c600d5017 100644 --- a/clap-utils/src/input_validators.rs +++ b/clap-utils/src/input_validators.rs @@ -20,7 +20,7 @@ where .as_ref() .parse::() .map(|_| ()) - .map_err(|err| format!("error parsing '{}': {}", string, err)) + .map_err(|err| format!("error parsing '{string}': {err}")) } // Return an error if string cannot be parsed as type T. @@ -45,14 +45,13 @@ where let range = range_min..range_max + 1.into(); if !range.contains(&input) { Err(format!( - "input '{:?}' out of range ({:?}..{:?}]", - input, range_min, range_max + "input '{input:?}' out of range ({range_min:?}..{range_max:?}]" )) } else { Ok(()) } } - Err(err) => Err(format!("error parsing '{}': {}", string, err)), + Err(err) => Err(format!("error parsing '{string}': {err}")), } } @@ -79,7 +78,7 @@ where { read_keypair_file(string.as_ref()) .map(|_| ()) - .map_err(|err| format!("{}", err)) + .map_err(|err| format!("{err}")) } // Return an error if a keypair file cannot be parsed @@ -92,7 +91,7 @@ where } read_keypair_file(string.as_ref()) .map(|_| ()) - .map_err(|err| format!("{}", err)) + .map_err(|err| format!("{err}")) } // Return an error if a `SignerSourceKind::Prompt` cannot be parsed @@ -104,13 +103,12 @@ where return Ok(()); } match parse_signer_source(string.as_ref()) - .map_err(|err| format!("{}", err))? + .map_err(|err| format!("{err}"))? .kind { SignerSourceKind::Prompt => Ok(()), _ => Err(format!( - "Unable to parse input as `prompt:` URI scheme or `ASK` keyword: {}", - string + "Unable to parse input as `prompt:` URI scheme or `ASK` keyword: {string}" )), } } @@ -130,7 +128,7 @@ where T: AsRef + Display, { match parse_signer_source(string.as_ref()) - .map_err(|err| format!("{}", err))? + .map_err(|err| format!("{err}"))? .kind { SignerSourceKind::Filepath(path) => is_keypair(path), @@ -171,10 +169,10 @@ where .ok_or_else(|| "Malformed signer string".to_string())?, ) { Ok(_) => Ok(()), - Err(err) => Err(format!("{}", err)), + Err(err) => Err(format!("{err}")), } } - Err(err) => Err(format!("{}", err)), + Err(err) => Err(format!("{err}")), } } @@ -191,7 +189,7 @@ where Err("no host provided".to_string()) } } - Err(err) => Err(format!("{}", err)), + Err(err) => Err(format!("{err}")), } } @@ -207,7 +205,7 @@ where Err("no host provided".to_string()) } } - Err(err) => Err(format!("{}", err)), + Err(err) => Err(format!("{err}")), } } @@ -242,10 +240,10 @@ where { bins.as_ref() .parse::() - .map_err(|e| format!("Unable to parse, provided: {}, err: {}", bins, e)) + .map_err(|e| format!("Unable to parse, provided: {bins}, err: {e}")) .and_then(|v| { if !v.is_power_of_two() { - Err(format!("Must be a power of 2: {}", v)) + Err(format!("Must be a power of 2: {v}")) } else { Ok(()) } @@ -266,17 +264,11 @@ where percentage .as_ref() .parse::() - .map_err(|e| { - format!( - "Unable to parse input percentage, provided: {}, err: {}", - percentage, e - ) - }) + .map_err(|e| format!("Unable to parse input percentage, provided: {percentage}, err: {e}")) .and_then(|v| { if v > 100 { Err(format!( - "Percentage must be in range of 0 to 100, provided: {}", - v + "Percentage must be in range of 0 to 100, provided: {v}" )) } else { Ok(()) @@ -292,8 +284,7 @@ where Ok(()) } else { Err(format!( - "Unable to parse input amount as integer or float, provided: {}", - amount + "Unable to parse input amount as integer or float, provided: {amount}" )) } } @@ -309,8 +300,7 @@ where Ok(()) } else { Err(format!( - "Unable to parse input amount as integer or float, provided: {}", - amount + "Unable to parse input amount as integer or float, provided: {amount}" )) } } @@ -321,7 +311,7 @@ where { DateTime::parse_from_rfc3339(value.as_ref()) .map(|_| ()) - .map_err(|e| format!("{}", e)) + .map_err(|e| format!("{e}")) } pub fn is_derivation(value: T) -> Result<(), String> @@ -333,19 +323,11 @@ where let account = parts.next().unwrap(); account .parse::() - .map_err(|e| { - format!( - "Unable to parse derivation, provided: {}, err: {}", - account, e - ) - }) + .map_err(|e| format!("Unable to parse derivation, provided: {account}, err: {e}")) .and_then(|_| { if let Some(change) = parts.next() { change.parse::().map_err(|e| { - format!( - "Unable to parse derivation, provided: {}, err: {}", - change, e - ) + format!("Unable to parse derivation, provided: {change}, err: {e}") }) } else { Ok(0) @@ -361,8 +343,7 @@ where let value = value.as_ref(); if value.len() > MAX_SEED_LEN { Err(format!( - "Address seed must not be longer than {} bytes", - MAX_SEED_LEN + "Address seed must not be longer than {MAX_SEED_LEN} bytes" )) } else { Ok(()) @@ -373,12 +354,10 @@ pub fn is_niceness_adjustment_valid(value: T) -> Result<(), String> where T: AsRef + Display, { - let adjustment = value.as_ref().parse::().map_err(|err| { - format!( - "error parsing niceness adjustment value '{}': {}", - value, err - ) - })?; + let adjustment = value + .as_ref() + .parse::() + .map_err(|err| format!("error parsing niceness adjustment value '{value}': {err}"))?; if solana_perf::thread::is_renice_allowed(adjustment) { Ok(()) } else { diff --git a/clap-utils/src/keypair.rs b/clap-utils/src/keypair.rs index 8d26a7d1d..0d4807f27 100644 --- a/clap-utils/src/keypair.rs +++ b/clap-utils/src/keypair.rs @@ -423,7 +423,7 @@ impl AsRef for SignerSourceKind { impl std::fmt::Debug for SignerSourceKind { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { let s: &str = self.as_ref(); - write!(f, "{}", s) + write!(f, "{s}") } } @@ -775,7 +775,7 @@ pub fn signer_from_path_with_config( SignerSourceKind::Filepath(path) => match read_keypair_file(&path) { Err(e) => Err(std::io::Error::new( std::io::ErrorKind::Other, - format!("could not read keypair file \"{}\". Run \"solana-keygen new\" to create a keypair file: {}", path, e), + format!("could not read keypair file \"{path}\". Run \"solana-keygen new\" to create a keypair file: {e}"), ) .into()), Ok(file) => Ok(Box::new(file)), @@ -811,7 +811,7 @@ pub fn signer_from_path_with_config( } else { Err(std::io::Error::new( std::io::ErrorKind::Other, - format!("missing signature for supplied pubkey: {}", pubkey), + format!("missing signature for supplied pubkey: {pubkey}"), ) .into()) } @@ -898,9 +898,8 @@ pub fn resolve_signer_from_path( Err(e) => Err(std::io::Error::new( std::io::ErrorKind::Other, format!( - "could not read keypair file \"{}\". \ - Run \"solana-keygen new\" to create a keypair file: {}", - path, e + "could not read keypair file \"{path}\". \ + Run \"solana-keygen new\" to create a keypair file: {e}" ), ) .into()), @@ -1021,9 +1020,8 @@ pub fn keypair_from_path( Err(e) => Err(std::io::Error::new( std::io::ErrorKind::Other, format!( - "could not read keypair file \"{}\". \ - Run \"solana-keygen new\" to create a keypair file: {}", - path, e + "could not read keypair file \"{path}\". \ + Run \"solana-keygen new\" to create a keypair file: {e}" ), ) .into()), @@ -1035,10 +1033,7 @@ pub fn keypair_from_path( } _ => Err(std::io::Error::new( std::io::ErrorKind::Other, - format!( - "signer of type `{:?}` does not support Keypair output", - kind - ), + format!("signer of type `{kind:?}` does not support Keypair output"), ) .into()), } @@ -1055,11 +1050,10 @@ pub fn keypair_from_seed_phrase( derivation_path: Option, legacy: bool, ) -> Result> { - let seed_phrase = prompt_password(format!("[{}] seed phrase: ", keypair_name))?; + let seed_phrase = prompt_password(format!("[{keypair_name}] seed phrase: "))?; let seed_phrase = seed_phrase.trim(); let passphrase_prompt = format!( - "[{}] If this seed phrase has an associated passphrase, enter it now. Otherwise, press ENTER to continue: ", - keypair_name, + "[{keypair_name}] If this seed phrase has an associated passphrase, enter it now. Otherwise, press ENTER to continue: ", ); let keypair = if skip_validation { @@ -1101,7 +1095,7 @@ pub fn keypair_from_seed_phrase( if confirm_pubkey { let pubkey = keypair.pubkey(); - print!("Recovered pubkey `{:?}`. Continue? (y/n): ", pubkey); + print!("Recovered pubkey `{pubkey:?}`. Continue? (y/n): "); let _ignored = stdout().flush(); let mut input = String::new(); stdin().read_line(&mut input).expect("Unexpected input"); @@ -1275,14 +1269,14 @@ mod tests { } )); assert!( - matches!(parse_signer_source(format!("file:{}", absolute_path_str)).unwrap(), SignerSource { + matches!(parse_signer_source(format!("file:{absolute_path_str}")).unwrap(), SignerSource { kind: SignerSourceKind::Filepath(p), derivation_path: None, legacy: false, } if p == absolute_path_str) ); assert!( - matches!(parse_signer_source(format!("file:{}", relative_path_str)).unwrap(), SignerSource { + matches!(parse_signer_source(format!("file:{relative_path_str}")).unwrap(), SignerSource { kind: SignerSourceKind::Filepath(p), derivation_path: None, legacy: false, diff --git a/clap-v3-utils/src/input_parsers.rs b/clap-v3-utils/src/input_parsers.rs index 53972f625..617d61348 100644 --- a/clap-v3-utils/src/input_parsers.rs +++ b/clap-v3-utils/src/input_parsers.rs @@ -220,7 +220,7 @@ mod tests { use std::env; let out_dir = env::var("FARF_DIR").unwrap_or_else(|_| "farf".to_string()); - format!("{}/tmp/{}-{}", out_dir, name, pubkey) + format!("{out_dir}/tmp/{name}-{pubkey}") } #[test] @@ -339,8 +339,8 @@ mod tests { let key2 = solana_sdk::pubkey::new_rand(); let sig1 = Keypair::new().sign_message(&[0u8]); let sig2 = Keypair::new().sign_message(&[1u8]); - let signer1 = format!("{}={}", key1, sig1); - let signer2 = format!("{}={}", key2, sig2); + let signer1 = format!("{key1}={sig1}"); + let signer2 = format!("{key2}={sig2}"); let matches = app().clone().get_matches_from(vec![ "test", "--multiple", diff --git a/clap-v3-utils/src/input_validators.rs b/clap-v3-utils/src/input_validators.rs index a3dfc380b..78eef2b54 100644 --- a/clap-v3-utils/src/input_validators.rs +++ b/clap-v3-utils/src/input_validators.rs @@ -20,7 +20,7 @@ where .as_ref() .parse::() .map(|_| ()) - .map_err(|err| format!("error parsing '{}': {}", string, err)) + .map_err(|err| format!("error parsing '{string}': {err}")) } // Return an error if string cannot be parsed as type T. @@ -45,14 +45,13 @@ where let range = range_min..range_max + 1.into(); if !range.contains(&input) { Err(format!( - "input '{:?}' out of range ({:?}..{:?}]", - input, range_min, range_max + "input '{input:?}' out of range ({range_min:?}..{range_max:?}]" )) } else { Ok(()) } } - Err(err) => Err(format!("error parsing '{}': {}", string, err)), + Err(err) => Err(format!("error parsing '{string}': {err}")), } } @@ -76,7 +75,7 @@ where { read_keypair_file(string.as_ref()) .map(|_| ()) - .map_err(|err| format!("{}", err)) + .map_err(|err| format!("{err}")) } // Return an error if a keypair file cannot be parsed @@ -89,7 +88,7 @@ where } read_keypair_file(string.as_ref()) .map(|_| ()) - .map_err(|err| format!("{}", err)) + .map_err(|err| format!("{err}")) } // Return an error if a `SignerSourceKind::Prompt` cannot be parsed @@ -98,13 +97,12 @@ pub fn is_prompt_signer_source(string: &str) -> Result<(), String> { return Ok(()); } match parse_signer_source(string) - .map_err(|err| format!("{}", err))? + .map_err(|err| format!("{err}"))? .kind { SignerSourceKind::Prompt => Ok(()), _ => Err(format!( - "Unable to parse input as `prompt:` URI scheme or `ASK` keyword: {}", - string + "Unable to parse input as `prompt:` URI scheme or `ASK` keyword: {string}" )), } } @@ -124,7 +122,7 @@ where T: AsRef + Display, { match parse_signer_source(string.as_ref()) - .map_err(|err| format!("{}", err))? + .map_err(|err| format!("{err}"))? .kind { SignerSourceKind::Filepath(path) => is_keypair(path), @@ -165,10 +163,10 @@ where .ok_or_else(|| "Malformed signer string".to_string())?, ) { Ok(_) => Ok(()), - Err(err) => Err(format!("{}", err)), + Err(err) => Err(format!("{err}")), } } - Err(err) => Err(format!("{}", err)), + Err(err) => Err(format!("{err}")), } } @@ -185,7 +183,7 @@ where Err("no host provided".to_string()) } } - Err(err) => Err(format!("{}", err)), + Err(err) => Err(format!("{err}")), } } @@ -201,7 +199,7 @@ where Err("no host provided".to_string()) } } - Err(err) => Err(format!("{}", err)), + Err(err) => Err(format!("{err}")), } } @@ -236,10 +234,10 @@ where { bins.as_ref() .parse::() - .map_err(|e| format!("Unable to parse, provided: {}, err: {}", bins, e)) + .map_err(|e| format!("Unable to parse, provided: {bins}, err: {e}")) .and_then(|v| { if !v.is_power_of_two() { - Err(format!("Must be a power of 2: {}", v)) + Err(format!("Must be a power of 2: {v}")) } else { Ok(()) } @@ -260,17 +258,11 @@ where percentage .as_ref() .parse::() - .map_err(|e| { - format!( - "Unable to parse input percentage, provided: {}, err: {}", - percentage, e - ) - }) + .map_err(|e| format!("Unable to parse input percentage, provided: {percentage}, err: {e}")) .and_then(|v| { if v > 100 { Err(format!( - "Percentage must be in range of 0 to 100, provided: {}", - v + "Percentage must be in range of 0 to 100, provided: {v}" )) } else { Ok(()) @@ -286,8 +278,7 @@ where Ok(()) } else { Err(format!( - "Unable to parse input amount as integer or float, provided: {}", - amount + "Unable to parse input amount as integer or float, provided: {amount}" )) } } @@ -303,8 +294,7 @@ where Ok(()) } else { Err(format!( - "Unable to parse input amount as integer or float, provided: {}", - amount + "Unable to parse input amount as integer or float, provided: {amount}" )) } } @@ -315,7 +305,7 @@ where { DateTime::parse_from_rfc3339(value.as_ref()) .map(|_| ()) - .map_err(|e| format!("{}", e)) + .map_err(|e| format!("{e}")) } pub fn is_derivation(value: T) -> Result<(), String> @@ -327,19 +317,11 @@ where let account = parts.next().unwrap(); account .parse::() - .map_err(|e| { - format!( - "Unable to parse derivation, provided: {}, err: {}", - account, e - ) - }) + .map_err(|e| format!("Unable to parse derivation, provided: {account}, err: {e}")) .and_then(|_| { if let Some(change) = parts.next() { change.parse::().map_err(|e| { - format!( - "Unable to parse derivation, provided: {}, err: {}", - change, e - ) + format!("Unable to parse derivation, provided: {change}, err: {e}") }) } else { Ok(0) @@ -355,8 +337,7 @@ where let value = value.as_ref(); if value.len() > MAX_SEED_LEN { Err(format!( - "Address seed must not be longer than {} bytes", - MAX_SEED_LEN + "Address seed must not be longer than {MAX_SEED_LEN} bytes" )) } else { Ok(()) @@ -367,12 +348,10 @@ pub fn is_niceness_adjustment_valid(value: T) -> Result<(), String> where T: AsRef + Display, { - let adjustment = value.as_ref().parse::().map_err(|err| { - format!( - "error parsing niceness adjustment value '{}': {}", - value, err - ) - })?; + let adjustment = value + .as_ref() + .parse::() + .map_err(|err| format!("error parsing niceness adjustment value '{value}': {err}"))?; if solana_perf::thread::is_renice_allowed(adjustment) { Ok(()) } else { diff --git a/clap-v3-utils/src/keypair.rs b/clap-v3-utils/src/keypair.rs index 509d57f51..d10c1776b 100644 --- a/clap-v3-utils/src/keypair.rs +++ b/clap-v3-utils/src/keypair.rs @@ -423,7 +423,7 @@ impl AsRef for SignerSourceKind { impl std::fmt::Debug for SignerSourceKind { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { let s: &str = self.as_ref(); - write!(f, "{}", s) + write!(f, "{s}") } } @@ -775,7 +775,7 @@ pub fn signer_from_path_with_config( SignerSourceKind::Filepath(path) => match read_keypair_file(&path) { Err(e) => Err(std::io::Error::new( std::io::ErrorKind::Other, - format!("could not read keypair file \"{}\". Run \"solana-keygen new\" to create a keypair file: {}", path, e), + format!("could not read keypair file \"{path}\". Run \"solana-keygen new\" to create a keypair file: {e}"), ) .into()), Ok(file) => Ok(Box::new(file)), @@ -811,7 +811,7 @@ pub fn signer_from_path_with_config( } else { Err(std::io::Error::new( std::io::ErrorKind::Other, - format!("missing signature for supplied pubkey: {}", pubkey), + format!("missing signature for supplied pubkey: {pubkey}"), ) .into()) } @@ -898,9 +898,8 @@ pub fn resolve_signer_from_path( Err(e) => Err(std::io::Error::new( std::io::ErrorKind::Other, format!( - "could not read keypair file \"{}\". \ - Run \"solana-keygen new\" to create a keypair file: {}", - path, e + "could not read keypair file \"{path}\". \ + Run \"solana-keygen new\" to create a keypair file: {e}" ), ) .into()), @@ -1021,9 +1020,8 @@ pub fn keypair_from_path( Err(e) => Err(std::io::Error::new( std::io::ErrorKind::Other, format!( - "could not read keypair file \"{}\". \ - Run \"solana-keygen new\" to create a keypair file: {}", - path, e + "could not read keypair file \"{path}\". \ + Run \"solana-keygen new\" to create a keypair file: {e}" ), ) .into()), @@ -1035,10 +1033,7 @@ pub fn keypair_from_path( } _ => Err(std::io::Error::new( std::io::ErrorKind::Other, - format!( - "signer of type `{:?}` does not support Keypair output", - kind - ), + format!("signer of type `{kind:?}` does not support Keypair output"), ) .into()), } @@ -1055,11 +1050,10 @@ pub fn keypair_from_seed_phrase( derivation_path: Option, legacy: bool, ) -> Result> { - let seed_phrase = prompt_password(format!("[{}] seed phrase: ", keypair_name))?; + let seed_phrase = prompt_password(format!("[{keypair_name}] seed phrase: "))?; let seed_phrase = seed_phrase.trim(); let passphrase_prompt = format!( - "[{}] If this seed phrase has an associated passphrase, enter it now. Otherwise, press ENTER to continue: ", - keypair_name, + "[{keypair_name}] If this seed phrase has an associated passphrase, enter it now. Otherwise, press ENTER to continue: ", ); let keypair = if skip_validation { @@ -1101,7 +1095,7 @@ pub fn keypair_from_seed_phrase( if confirm_pubkey { let pubkey = keypair.pubkey(); - print!("Recovered pubkey `{:?}`. Continue? (y/n): ", pubkey); + print!("Recovered pubkey `{pubkey:?}`. Continue? (y/n): "); let _ignored = stdout().flush(); let mut input = String::new(); stdin().read_line(&mut input).expect("Unexpected input"); @@ -1275,14 +1269,14 @@ mod tests { } )); assert!( - matches!(parse_signer_source(format!("file:{}", absolute_path_str)).unwrap(), SignerSource { + matches!(parse_signer_source(format!("file:{absolute_path_str}")).unwrap(), SignerSource { kind: SignerSourceKind::Filepath(p), derivation_path: None, legacy: false, } if p == absolute_path_str) ); assert!( - matches!(parse_signer_source(format!("file:{}", relative_path_str)).unwrap(), SignerSource { + matches!(parse_signer_source(format!("file:{relative_path_str}")).unwrap(), SignerSource { kind: SignerSourceKind::Filepath(p), derivation_path: None, legacy: false, diff --git a/cli-config/src/lib.rs b/cli-config/src/lib.rs index a75e29d65..7bf3ce194 100644 --- a/cli-config/src/lib.rs +++ b/cli-config/src/lib.rs @@ -83,7 +83,7 @@ where { let file = File::open(config_file)?; let config = serde_yaml::from_reader(file) - .map_err(|err| io::Error::new(io::ErrorKind::Other, format!("{:?}", err)))?; + .map_err(|err| io::Error::new(io::ErrorKind::Other, format!("{err:?}")))?; Ok(config) } @@ -106,7 +106,7 @@ where P: AsRef, { let serialized = serde_yaml::to_string(config) - .map_err(|err| io::Error::new(io::ErrorKind::Other, format!("{:?}", err)))?; + .map_err(|err| io::Error::new(io::ErrorKind::Other, format!("{err:?}")))?; if let Some(outdir) = config_file.as_ref().parent() { create_dir_all(outdir)?; diff --git a/cli-output/src/cli_output.rs b/cli-output/src/cli_output.rs index 9b569e1eb..4e3cb2730 100644 --- a/cli-output/src/cli_output.rs +++ b/cli-output/src/cli_output.rs @@ -71,7 +71,7 @@ impl OutputFormat { T: Serialize + fmt::Display + QuietDisplay + VerboseDisplay, { match self { - OutputFormat::Display => format!("{}", item), + OutputFormat::Display => format!("{item}"), OutputFormat::DisplayQuiet => { let mut s = String::new(); QuietDisplay::write_str(item, &mut s).unwrap(); @@ -342,7 +342,7 @@ impl fmt::Display for CliEpochInfo { writeln_name_value( f, "Epoch Slot Range:", - &format!("[{}..{})", start_slot, end_slot), + &format!("[{start_slot}..{end_slot})"), )?; writeln_name_value( f, @@ -387,7 +387,7 @@ impl fmt::Display for CliEpochInfo { )?; if let Some(annotation) = annotation { writeln!(f)?; - writeln!(f, "{}", annotation)?; + writeln!(f, "{annotation}")?; } Ok(()) } @@ -457,11 +457,11 @@ impl fmt::Display for CliValidators { if v == 0 { " - ".into() } else if v == max_v { - format!("{:>9} ( 0)", v) + format!("{v:>9} ( 0)") } else if v > max_v.saturating_sub(100) { format!("{:>9} ({:>3})", v, -(max_v.saturating_sub(v) as isize)) } else { - format!("{:>9} ", v) + format!("{v:>9} ") } } @@ -479,7 +479,7 @@ impl fmt::Display for CliValidators { non_zero_or_dash(validator.last_vote, highest_last_vote), non_zero_or_dash(validator.root_slot, highest_root), if let Some(skip_rate) = validator.skip_rate { - format!("{:.2}%", skip_rate) + format!("{skip_rate:.2}%") } else { "- ".to_string() }, @@ -518,7 +518,7 @@ impl fmt::Display for CliValidators { padding = padding + 2 )) .bold(); - writeln!(f, "{}", header)?; + writeln!(f, "{header}")?; let mut sorted_validators = self.validators.clone(); match self.validators_sort_order { @@ -590,7 +590,7 @@ impl fmt::Display for CliValidators { } else { sorted_validators.len() - i }; - write!(f, "{:padding$} ", num, padding = padding)?; + write!(f, "{num:padding$} ")?; } write_vote_account( f, @@ -604,7 +604,7 @@ impl fmt::Display for CliValidators { // The actual header has long scrolled away. Print the header once more as a footer if self.validators.len() > 100 { - writeln!(f, "{}", header)?; + writeln!(f, "{header}")?; } writeln!(f)?; @@ -794,14 +794,14 @@ impl fmt::Display for CliNonceAccount { ) )?; let nonce = self.nonce.as_deref().unwrap_or("uninitialized"); - writeln!(f, "Nonce blockhash: {}", nonce)?; + writeln!(f, "Nonce blockhash: {nonce}")?; if let Some(fees) = self.lamports_per_signature { - writeln!(f, "Fee: {} lamports per signature", fees)?; + writeln!(f, "Fee: {fees} lamports per signature")?; } else { writeln!(f, "Fees: uninitialized")?; } let authority = self.authority.as_deref().unwrap_or("uninitialized"); - writeln!(f, "Authority: {}", authority) + writeln!(f, "Authority: {authority}") } } @@ -829,7 +829,7 @@ impl fmt::Display for CliStakeVec { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for state in &self.0 { writeln!(f)?; - write!(f, "{}", state)?; + write!(f, "{state}")?; } Ok(()) } @@ -927,11 +927,11 @@ impl fmt::Display for CliKeyedEpochRewards { reward.percent_change, reward .apr - .map(|apr| format!("{:.2}%", apr)) + .map(|apr| format!("{apr:.2}%")) .unwrap_or_default(), reward .commission - .map(|commission| format!("{}%", commission)) + .map(|commission| format!("{commission}%")) .unwrap_or_else(|| "-".to_string()) )?; } @@ -1028,8 +1028,7 @@ fn show_votes_and_credits( writeln!( f, - "- ... (omitting {} past rooted votes, which have already been credited)", - count + "- ... (omitting {count} past rooted votes, which have already been credited)" )?; } } @@ -1063,11 +1062,11 @@ fn show_epoch_rewards( reward.percent_change, reward .apr - .map(|apr| format!("{:.2}%", apr)) + .map(|apr| format!("{apr:.2}%")) .unwrap_or_default(), reward .commission - .map(|commission| format!("{}%", commission)) + .map(|commission| format!("{commission}%")) .unwrap_or_else(|| "-".to_string()) )?; } @@ -1113,9 +1112,9 @@ pub struct CliStakeState { impl QuietDisplay for CliStakeState {} impl VerboseDisplay for CliStakeState { fn write_str(&self, w: &mut dyn std::fmt::Write) -> std::fmt::Result { - write!(w, "{}", self)?; + write!(w, "{self}")?; if let Some(credits) = self.credits_observed { - writeln!(w, "Credits Observed: {}", credits)?; + writeln!(w, "Credits Observed: {credits}")?; } Ok(()) } @@ -1246,8 +1245,7 @@ impl fmt::Display for CliStakeState { } writeln!( f, - "Stake deactivates starting from epoch: {}", - deactivation_epoch + "Stake deactivates starting from epoch: {deactivation_epoch}" )?; } if let Some(delegated_vote_account_address) = @@ -1255,8 +1253,7 @@ impl fmt::Display for CliStakeState { { writeln!( f, - "Delegated Vote Account Address: {}", - delegated_vote_account_address + "Delegated Vote Account Address: {delegated_vote_account_address}" )?; } } else { @@ -1405,7 +1402,7 @@ impl fmt::Display for CliValidatorInfoVec { } for validator_info in &self.0 { writeln!(f)?; - write!(f, "{}", validator_info)?; + write!(f, "{validator_info}")?; } Ok(()) } @@ -1695,19 +1692,19 @@ impl fmt::Display for CliSignOnlyData { if !self.signers.is_empty() { writeln!(f, "{}", style("Signers (Pubkey=Signature):").bold())?; for signer in self.signers.iter() { - writeln!(f, " {}", signer)?; + writeln!(f, " {signer}")?; } } if !self.absent.is_empty() { writeln!(f, "{}", style("Absent Signers (Pubkey):").bold())?; for pubkey in self.absent.iter() { - writeln!(f, " {}", pubkey)?; + writeln!(f, " {pubkey}")?; } } if !self.bad_sig.is_empty() { writeln!(f, "{}", style("Bad Signatures (Pubkey):").bold())?; for pubkey in self.bad_sig.iter() { - writeln!(f, " {}", pubkey)?; + writeln!(f, " {pubkey}")?; } } Ok(()) @@ -1802,7 +1799,7 @@ impl fmt::Display for CliSupply { writeln!(f)?; writeln_name_value(f, "Non-Circulating Accounts:", " ")?; for account in &self.non_circulating_accounts { - writeln!(f, " {}", account)?; + writeln!(f, " {account}")?; } } Ok(()) @@ -1851,7 +1848,7 @@ impl VerboseDisplay for CliFees {} impl fmt::Display for CliFees { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.inner.as_ref() { - Some(inner) => write!(f, "{}", inner), + Some(inner) => write!(f, "{inner}"), None => write!(f, "Fees unavailable"), } } @@ -2217,7 +2214,7 @@ impl fmt::Display for CliAddressLookupTable { style(format!(" {:<5} {}", "Index", "Address")).bold() )?; for (index, address) in self.addresses.iter().enumerate() { - writeln!(f, " {:<5} {}", index, address)?; + writeln!(f, " {index:<5} {address}")?; } } Ok(()) @@ -2273,7 +2270,7 @@ pub fn return_signers_data(tx: &Transaction, config: &ReturnSignersConfig) -> Cl .zip(verify_results.into_iter()) .for_each(|((sig, key), res)| { if res { - signers.push(format!("{}={}", key, sig)) + signers.push(format!("{key}={sig}")) } else if *sig == Signature::default() { absent.push(key.to_string()); } else { @@ -2418,7 +2415,7 @@ impl fmt::Display for CliBlock { writeln!(f, "Block Time: {:?}", Local.timestamp(block_time, 0))?; } if let Some(block_height) = self.encoded_confirmed_block.block_height { - writeln!(f, "Block Height: {:?}", block_height)?; + writeln!(f, "Block Height: {block_height:?}")?; } if !self.encoded_confirmed_block.rewards.is_empty() { let mut rewards = self.encoded_confirmed_block.rewards.clone(); @@ -2440,7 +2437,7 @@ impl fmt::Display for CliBlock { " {:<44} {:^15} {:>15} {} {}", reward.pubkey, if let Some(reward_type) = reward.reward_type { - format!("{}", reward_type) + format!("{reward_type}") } else { "-".to_string() }, @@ -2462,7 +2459,7 @@ impl fmt::Display for CliBlock { }, reward .commission - .map(|commission| format!("{:>9}%", commission)) + .map(|commission| format!("{commission:>9}%")) .unwrap_or_else(|| " -".to_string()) )?; } @@ -2478,7 +2475,7 @@ impl fmt::Display for CliBlock { for (index, transaction_with_meta) in self.encoded_confirmed_block.transactions.iter().enumerate() { - writeln!(f, "Transaction {}:", index)?; + writeln!(f, "Transaction {index}:")?; writeln_transaction( f, &transaction_with_meta.transaction.decode().unwrap(), @@ -2549,7 +2546,7 @@ impl VerboseDisplay for CliTransactionConfirmation { "\nTransaction executed in slot {}:", transaction.slot.expect("slot should exist") )?; - write!(w, "{}", transaction)?; + write!(w, "{transaction}")?; } else if let Some(confirmation_status) = &self.confirmation_status { if confirmation_status != &TransactionConfirmationStatus::Finalized { writeln!(w)?; @@ -2559,11 +2556,11 @@ impl VerboseDisplay for CliTransactionConfirmation { )?; } else if let Some(err) = &self.get_transaction_error { writeln!(w)?; - writeln!(w, "Unable to get finalized transaction details: {}", err)?; + writeln!(w, "Unable to get finalized transaction details: {err}")?; } } writeln!(w)?; - write!(w, "{}", self) + write!(w, "{self}") } } @@ -2573,9 +2570,9 @@ impl fmt::Display for CliTransactionConfirmation { None => write!(f, "Not found"), Some(confirmation_status) => { if let Some(err) = &self.err { - write!(f, "Transaction failed: {}", err) + write!(f, "Transaction failed: {err}") } else { - write!(f, "{:?}", confirmation_status) + write!(f, "{confirmation_status:?}") } } } @@ -2668,7 +2665,7 @@ impl fmt::Display for CliGossipNodes { --------+-------+-----------------------+---------+----------------", )?; for node in self.0.iter() { - writeln!(f, "{}", node)?; + writeln!(f, "{node}")?; } writeln!(f, "Nodes: {}", self.0.len()) } @@ -2703,19 +2700,18 @@ impl fmt::Display for CliPing { }; writeln!( f, - "Fixed blockhash is used: {} ({})", - fixed_blockhash, blockhash_origin + "Fixed blockhash is used: {fixed_blockhash} ({blockhash_origin})" )?; } writeln!(f)?; for ping in &self.pings { - write!(f, "{}", ping)?; + write!(f, "{ping}")?; } writeln!(f)?; writeln!(f, "--- transaction statistics ---")?; write!(f, "{}", self.transaction_stats)?; if let Some(confirmation_stats) = &self.confirmation_stats { - write!(f, "{}", confirmation_stats)?; + write!(f, "{confirmation_stats}")?; } Ok(()) } @@ -2859,7 +2855,7 @@ impl QuietDisplay for CliBalance { ..self.config }; let balance_message = build_balance_message_with_config(self.lamports, &config); - write!(w, "{}", balance_message) + write!(w, "{balance_message}") } } @@ -2871,14 +2867,14 @@ impl VerboseDisplay for CliBalance { ..self.config }; let balance_message = build_balance_message_with_config(self.lamports, &config); - write!(w, "{}", balance_message) + write!(w, "{balance_message}") } } impl fmt::Display for CliBalance { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let balance_message = build_balance_message_with_config(self.lamports, &self.config); - write!(f, "{}", balance_message) + write!(f, "{balance_message}") } } diff --git a/cli-output/src/cli_version.rs b/cli-output/src/cli_version.rs index b163f99bc..aa0e3698d 100644 --- a/cli-output/src/cli_version.rs +++ b/cli-output/src/cli_version.rs @@ -18,7 +18,7 @@ impl fmt::Display for CliVersion { None => "unknown".to_string(), Some(version) => version.to_string(), }; - write!(f, "{}", s) + write!(f, "{s}") } } diff --git a/cli-output/src/display.rs b/cli-output/src/display.rs index a2f12e034..649ac39d7 100644 --- a/cli-output/src/display.rs +++ b/cli-output/src/display.rs @@ -53,7 +53,7 @@ pub fn build_balance_message_with_config( lamports.to_string() } else { let sol = lamports_to_sol(lamports); - let sol_str = format!("{:.9}", sol); + let sol_str = format!("{sol:.9}"); if config.trim_trailing_zeros { sol_str .trim_end_matches('0') @@ -66,14 +66,14 @@ pub fn build_balance_message_with_config( let unit = if config.show_unit { if config.use_lamports_unit { let ess = if lamports == 1 { "" } else { "s" }; - format!(" lamport{}", ess) + format!(" lamport{ess}") } else { " SOL".to_string() } } else { "".to_string() }; - format!("{}{}", value, unit) + format!("{value}{unit}") } pub fn build_balance_message(lamports: u64, use_lamports_unit: bool, show_unit: bool) -> String { @@ -141,18 +141,18 @@ pub fn println_signers( bad_sig: &[String], ) { println!(); - println!("Blockhash: {}", blockhash); + println!("Blockhash: {blockhash}"); if !signers.is_empty() { println!("Signers (Pubkey=Signature):"); - signers.iter().for_each(|signer| println!(" {}", signer)) + signers.iter().for_each(|signer| println!(" {signer}")) } if !absent.is_empty() { println!("Absent Signers (Pubkey):"); - absent.iter().for_each(|pubkey| println!(" {}", pubkey)) + absent.iter().for_each(|pubkey| println!(" {pubkey}")) } if !bad_sig.is_empty() { println!("Bad Signatures (Pubkey):"); - bad_sig.iter().for_each(|pubkey| println!(" {}", pubkey)) + bad_sig.iter().for_each(|pubkey| println!(" {pubkey}")) } println!(); } @@ -272,7 +272,7 @@ fn write_transaction( write_return_data(w, transaction_status.return_data.as_ref().into(), prefix)?; write_rewards(w, transaction_status.rewards.as_ref().into(), prefix)?; } else { - writeln!(w, "{}Status: Unavailable", prefix)?; + writeln!(w, "{prefix}Status: Unavailable")?; } Ok(()) @@ -325,7 +325,7 @@ fn write_block_time( CliTimezone::Local => format!("{:?}", Local.timestamp(block_time, 0)), CliTimezone::Utc => format!("{:?}", Utc.timestamp(block_time, 0)), }; - writeln!(w, "{}Block Time: {}", prefix, block_time_output,)?; + writeln!(w, "{prefix}Block Time: {block_time_output}",)?; } Ok(()) } @@ -339,7 +339,7 @@ fn write_version( TransactionVersion::Legacy(_) => "legacy".to_string(), TransactionVersion::Number(number) => number.to_string(), }; - writeln!(w, "{}Version: {}", prefix, version) + writeln!(w, "{prefix}Version: {version}") } fn write_recent_blockhash( @@ -347,7 +347,7 @@ fn write_recent_blockhash( recent_blockhash: &Hash, prefix: &str, ) -> io::Result<()> { - writeln!(w, "{}Recent Blockhash: {:?}", prefix, recent_blockhash) + writeln!(w, "{prefix}Recent Blockhash: {recent_blockhash:?}") } fn write_signatures( @@ -357,10 +357,7 @@ fn write_signatures( prefix: &str, ) -> io::Result<()> { let sigverify_statuses = if let Some(sigverify_status) = sigverify_status { - sigverify_status - .iter() - .map(|s| format!(" ({})", s)) - .collect() + sigverify_status.iter().map(|s| format!(" ({s})")).collect() } else { vec!["".to_string(); signatures.len()] }; @@ -369,8 +366,7 @@ fn write_signatures( { writeln!( w, - "{}Signature {}: {:?}{}", - prefix, signature_index, signature, sigverify_status, + "{prefix}Signature {signature_index}: {signature:?}{sigverify_status}", )?; } Ok(()) @@ -388,15 +384,14 @@ enum AccountKeyType<'a> { impl fmt::Display for AccountKeyType<'_> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - Self::Known(address) => write!(f, "{}", address), + Self::Known(address) => write!(f, "{address}"), Self::Unknown { lookup_index, table_index, } => { write!( f, - "Unknown Address (uses lookup {} and index {})", - lookup_index, table_index + "Unknown Address (uses lookup {lookup_index} and index {table_index})" ) } } @@ -430,7 +425,7 @@ fn write_instruction<'a, W: io::Write>( instruction_accounts: impl Iterator, u8)>, prefix: &str, ) -> io::Result<()> { - writeln!(w, "{}Instruction {}", prefix, instruction_index)?; + writeln!(w, "{prefix}Instruction {instruction_index}")?; writeln!( w, "{} Program: {} ({})", @@ -439,8 +434,7 @@ fn write_instruction<'a, W: io::Write>( for (index, (account_address, account_index)) in instruction_accounts.enumerate() { writeln!( w, - "{} Account {}: {} ({})", - prefix, index, account_address, account_index + "{prefix} Account {index}: {account_address} ({account_index})" )?; } @@ -451,14 +445,14 @@ fn write_instruction<'a, W: io::Write>( solana_vote_program::vote_instruction::VoteInstruction, >(&instruction.data) { - writeln!(w, "{} {:?}", prefix, vote_instruction)?; + writeln!(w, "{prefix} {vote_instruction:?}")?; raw = false; } } else if program_pubkey == &stake::program::id() { if let Ok(stake_instruction) = limited_deserialize::(&instruction.data) { - writeln!(w, "{} {:?}", prefix, stake_instruction)?; + writeln!(w, "{prefix} {stake_instruction:?}")?; raw = false; } } else if program_pubkey == &solana_sdk::system_program::id() { @@ -466,12 +460,12 @@ fn write_instruction<'a, W: io::Write>( solana_sdk::system_instruction::SystemInstruction, >(&instruction.data) { - writeln!(w, "{} {:?}", prefix, system_instruction)?; + writeln!(w, "{prefix} {system_instruction:?}")?; raw = false; } } else if is_memo_program(program_pubkey) { if let Ok(s) = std::str::from_utf8(&instruction.data) { - writeln!(w, "{} Data: \"{}\"", prefix, s)?; + writeln!(w, "{prefix} Data: \"{s}\"")?; raw = false; } } @@ -490,7 +484,7 @@ fn write_address_table_lookups( prefix: &str, ) -> io::Result<()> { for (lookup_index, lookup) in address_table_lookups.iter().enumerate() { - writeln!(w, "{}Address Table Lookup {}", prefix, lookup_index,)?; + writeln!(w, "{prefix}Address Table Lookup {lookup_index}",)?; writeln!(w, "{} Table Account: {}", prefix, lookup.account_key,)?; writeln!( w, @@ -515,7 +509,7 @@ fn write_rewards( ) -> io::Result<()> { if let Some(rewards) = rewards { if !rewards.is_empty() { - writeln!(w, "{}Rewards:", prefix,)?; + writeln!(w, "{prefix}Rewards:",)?; writeln!( w, "{} {:<44} {:^15} {:<16} {:<20}", @@ -529,7 +523,7 @@ fn write_rewards( prefix, reward.pubkey, if let Some(reward_type) = reward.reward_type { - format!("{}", reward_type) + format!("{reward_type}") } else { "-".to_string() }, @@ -611,7 +605,7 @@ fn write_return_data( UiReturnDataEncoding::Base64 => base64::decode(data).map_err(|err| { io::Error::new( io::ErrorKind::Other, - format!("could not parse data as {:?}: {:?}", encoding, err), + format!("could not parse data as {encoding:?}: {err:?}"), ) })?, }; @@ -634,7 +628,7 @@ fn write_compute_units_consumed( prefix: &str, ) -> io::Result<()> { if let Some(cus) = compute_units_consumed { - writeln!(w, "{}Compute Units Consumed: {}", prefix, cus)?; + writeln!(w, "{prefix}Compute Units Consumed: {cus}")?; } Ok(()) } @@ -646,9 +640,9 @@ fn write_log_messages( ) -> io::Result<()> { if let Some(log_messages) = log_messages { if !log_messages.is_empty() { - writeln!(w, "{}Log Messages:", prefix,)?; + writeln!(w, "{prefix}Log Messages:",)?; for log_message in log_messages { - writeln!(w, "{} {}", prefix, log_message)?; + writeln!(w, "{prefix} {log_message}")?; } } } @@ -675,7 +669,7 @@ pub fn println_transaction( .is_ok() { if let Ok(s) = String::from_utf8(w) { - print!("{}", s); + print!("{s}"); } } } @@ -701,7 +695,7 @@ pub fn writeln_transaction( if write_result.is_ok() { if let Ok(s) = String::from_utf8(w) { - write!(f, "{}", s)?; + write!(f, "{s}")?; } } Ok(()) @@ -722,7 +716,7 @@ pub fn new_spinner_progress_bar() -> ProgressBar { pub fn unix_timestamp_to_string(unix_timestamp: UnixTimestamp) -> String { match NaiveDateTime::from_timestamp_opt(unix_timestamp, 0) { Some(ndt) => DateTime::::from_utc(ndt, Utc).to_rfc3339_opts(SecondsFormat::Secs, true), - None => format!("UnixTimestamp {}", unix_timestamp), + None => format!("UnixTimestamp {unix_timestamp}"), } } diff --git a/cli-output/src/lib.rs b/cli-output/src/lib.rs index 2b413716d..3e85d825e 100644 --- a/cli-output/src/lib.rs +++ b/cli-output/src/lib.rs @@ -6,12 +6,12 @@ pub use cli_output::*; pub trait QuietDisplay: std::fmt::Display { fn write_str(&self, w: &mut dyn std::fmt::Write) -> std::fmt::Result { - write!(w, "{}", self) + write!(w, "{self}") } } pub trait VerboseDisplay: std::fmt::Display { fn write_str(&self, w: &mut dyn std::fmt::Write) -> std::fmt::Result { - write!(w, "{}", self) + write!(w, "{self}") } } diff --git a/cli/src/address_lookup_table.rs b/cli/src/address_lookup_table.rs index 3b0c341bb..e0dd2412a 100644 --- a/cli/src/address_lookup_table.rs +++ b/cli/src/address_lookup_table.rs @@ -576,7 +576,7 @@ fn process_create_lookup_table( }, ); match result { - Err(err) => Err(format!("Create failed: {}", err).into()), + Err(err) => Err(format!("Create failed: {err}").into()), Ok(signature) => Ok(config .output_format .formatted_string(&CliAddressLookupTableCreated { @@ -635,7 +635,7 @@ fn process_freeze_lookup_table( }, ); match result { - Err(err) => Err(format!("Freeze failed: {}", err).into()), + Err(err) => Err(format!("Freeze failed: {err}").into()), Ok(signature) => Ok(config.output_format.formatted_string(&CliSignature { signature: signature.to_string(), })), @@ -695,7 +695,7 @@ fn process_extend_lookup_table( }, ); match result { - Err(err) => Err(format!("Extend failed: {}", err).into()), + Err(err) => Err(format!("Extend failed: {err}").into()), Ok(signature) => Ok(config.output_format.formatted_string(&CliSignature { signature: signature.to_string(), })), @@ -753,7 +753,7 @@ fn process_deactivate_lookup_table( }, ); match result { - Err(err) => Err(format!("Deactivate failed: {}", err).into()), + Err(err) => Err(format!("Deactivate failed: {err}").into()), Ok(signature) => Ok(config.output_format.formatted_string(&CliSignature { signature: signature.to_string(), })), @@ -810,7 +810,7 @@ fn process_close_lookup_table( }, ); match result { - Err(err) => Err(format!("Close failed: {}", err).into()), + Err(err) => Err(format!("Close failed: {err}").into()), Ok(signature) => Ok(config.output_format.formatted_string(&CliSignature { signature: signature.to_string(), })), diff --git a/cli/src/cli.rs b/cli/src/cli.rs index c63a5650c..99fb3ca00 100644 --- a/cli/src/cli.rs +++ b/cli/src/cli.rs @@ -838,7 +838,7 @@ pub fn process_command(config: &CliConfig) -> ProcessResult { if config.keypair_path.starts_with("usb://") { let pubkey = config .pubkey() - .map(|pubkey| format!("{:?}", pubkey)) + .map(|pubkey| format!("{pubkey:?}")) .unwrap_or_else(|_| "Unavailable".to_string()); println_name_value("Pubkey:", &pubkey); } @@ -1817,7 +1817,7 @@ mod tests { let test_commands = get_clap_app("test", "desc", "version"); let pubkey = solana_sdk::pubkey::new_rand(); - let pubkey_string = format!("{}", pubkey); + let pubkey_string = format!("{pubkey}"); let default_keypair = Keypair::new(); let keypair_file = make_tmp_path("keypair_file"); @@ -1889,7 +1889,7 @@ mod tests { // Test Confirm Subcommand let signature = Signature::new(&[1; 64]); - let signature_string = format!("{:?}", signature); + let signature_string = format!("{signature:?}"); let test_confirm = test_commands .clone() @@ -2520,7 +2520,7 @@ mod tests { //Test Transfer Subcommand, submit offline `from` let from_sig = from_keypair.sign_message(&[0u8]); - let from_signer = format!("{}={}", from_pubkey, from_sig); + let from_signer = format!("{from_pubkey}={from_sig}"); let test_transfer = test_commands.clone().get_matches_from(vec![ "test", "transfer", diff --git a/cli/src/cluster_query.rs b/cli/src/cluster_query.rs index 40b07b83e..0ed46a361 100644 --- a/cli/src/cluster_query.rs +++ b/cli/src/cluster_query.rs @@ -680,7 +680,7 @@ pub fn parse_transaction_history( Some(signature) => Some( signature .parse() - .map_err(|err| CliError::BadParameter(format!("Invalid signature: {}", err)))?, + .map_err(|err| CliError::BadParameter(format!("Invalid signature: {err}")))?, ), None => None, }; @@ -688,7 +688,7 @@ pub fn parse_transaction_history( Some(signature) => Some( signature .parse() - .map_err(|err| CliError::BadParameter(format!("Invalid signature: {}", err)))?, + .map_err(|err| CliError::BadParameter(format!("Invalid signature: {err}")))?, ), None => None, }; @@ -722,7 +722,7 @@ pub fn process_catchup( progress_bar.set_message("Connecting..."); if let Some(our_localhost_port) = our_localhost_port { - let gussed_default = Some(format!("http://localhost:{}", our_localhost_port)); + let gussed_default = Some(format!("http://localhost:{our_localhost_port}")); if node_json_rpc_url.is_some() && node_json_rpc_url != gussed_default { // go to new line to leave this message on console println!( @@ -766,10 +766,10 @@ pub fn process_catchup( if let Some(rpc_addr) = contact_info.rpc { break rpc_addr; } - progress_bar.set_message(format!("RPC service not found for {}", node_pubkey)); + progress_bar.set_message(format!("RPC service not found for {node_pubkey}")); } else { progress_bar - .set_message(format!("Contact information not found for {}", node_pubkey)); + .set_message(format!("Contact information not found for {node_pubkey}")); } sleep(Duration::from_secs(sleep_interval as u64)); }; @@ -785,7 +785,7 @@ pub fn process_catchup( Ok(reported_node_pubkey) => break reported_node_pubkey, Err(err) => { if let ClientErrorKind::Reqwest(err) = err.kind() { - progress_bar.set_message(format!("Connection failed: {}", err)); + progress_bar.set_message(format!("Connection failed: {err}")); sleep(Duration::from_secs(sleep_interval as u64)); continue; } @@ -796,8 +796,7 @@ pub fn process_catchup( if reported_node_pubkey != node_pubkey { return Err(format!( - "The identity reported by node RPC URL does not match. Expected: {:?}. Reported: {:?}", - node_pubkey, reported_node_pubkey + "The identity reported by node RPC URL does not match. Expected: {node_pubkey:?}. Reported: {reported_node_pubkey:?}" ) .into()); } @@ -824,7 +823,7 @@ pub fn process_catchup( retry_count += 1; if log { // go to new line to leave this message on console - println!("Retrying({}/{}): {}\n", retry_count, max_retry_count, e); + println!("Retrying({retry_count}/{max_retry_count}): {e}\n"); } sleep(Duration::from_secs(1)); } @@ -844,8 +843,7 @@ pub fn process_catchup( if !follow && node_slot > std::cmp::min(previous_rpc_slot, rpc_slot) { progress_bar.finish_and_clear(); return Ok(format!( - "{} has caught up (us:{} them:{})", - node_pubkey, node_slot, rpc_slot, + "{node_pubkey} has caught up (us:{node_slot} them:{rpc_slot})", )); } @@ -864,10 +862,7 @@ pub fn process_catchup( if !average_time_remaining.is_normal() { "".to_string() } else if average_time_remaining < 0.0 { - format!( - " (AVG: {:.1} slots/second (falling))", - average_catchup_slots_per_second - ) + format!(" (AVG: {average_catchup_slots_per_second:.1} slots/second (falling))") } else { // important not to miss next scheduled lead slots let total_node_slot_delta = node_slot as i64 - start_node_slot as i64; @@ -942,7 +937,7 @@ pub fn process_cluster_version(rpc_client: &RpcClient, config: &CliConfig) -> Pr let remote_version = rpc_client.get_version()?; if config.verbose { - Ok(format!("{:?}", remote_version)) + Ok(format!("{remote_version:?}")) } else { Ok(remote_version.to_string()) } @@ -986,7 +981,7 @@ pub fn process_fees( pub fn process_first_available_block(rpc_client: &RpcClient) -> ProcessResult { let first_available_block = rpc_client.get_first_available_block()?; - Ok(format!("{}", first_available_block)) + Ok(format!("{first_available_block}")) } pub fn parse_leader_schedule(matches: &ArgMatches<'_>) -> Result { @@ -1005,7 +1000,7 @@ pub fn process_leader_schedule( let epoch_info = rpc_client.get_epoch_info()?; let epoch = epoch.unwrap_or(epoch_info.epoch); if epoch > epoch_info.epoch { - return Err(format!("Epoch {} is in the future", epoch).into()); + return Err(format!("Epoch {epoch} is in the future").into()); } let epoch_schedule = rpc_client.get_epoch_schedule()?; @@ -1013,11 +1008,9 @@ pub fn process_leader_schedule( let leader_schedule = rpc_client.get_leader_schedule(Some(first_slot_in_epoch))?; if leader_schedule.is_none() { - return Err(format!( - "Unable to fetch leader schedule for slot {}", - first_slot_in_epoch - ) - .into()); + return Err( + format!("Unable to fetch leader schedule for slot {first_slot_in_epoch}").into(), + ); } let leader_schedule = leader_schedule.unwrap(); @@ -1180,7 +1173,7 @@ pub fn process_show_block_production( let epoch = epoch.unwrap_or(epoch_info.epoch); if epoch > epoch_info.epoch { - return Err(format!("Epoch {} is in the future", epoch).into()); + return Err(format!("Epoch {epoch} is in the future").into()); } let first_slot_in_epoch = epoch_schedule.get_first_slot_in_epoch(epoch); @@ -1197,8 +1190,7 @@ pub fn process_show_block_production( let progress_bar = new_spinner_progress_bar(); progress_bar.set_message(format!( - "Fetching confirmed blocks between slots {} and {}...", - start_slot, end_slot + "Fetching confirmed blocks between slots {start_slot} and {end_slot}..." )); let slot_history_account = rpc_client @@ -1210,45 +1202,44 @@ pub fn process_show_block_production( CliError::RpcRequestError("Failed to deserialize slot history".to_string()) })?; - let (confirmed_blocks, start_slot) = - if start_slot >= slot_history.oldest() && end_slot <= slot_history.newest() { - // Fast, more reliable path using the SlotHistory sysvar + let (confirmed_blocks, start_slot) = if start_slot >= slot_history.oldest() + && end_slot <= slot_history.newest() + { + // Fast, more reliable path using the SlotHistory sysvar - let confirmed_blocks: Vec<_> = (start_slot..=end_slot) - .filter(|slot| slot_history.check(*slot) == slot_history::Check::Found) - .collect(); - (confirmed_blocks, start_slot) - } else { - // Slow, less reliable path using `getBlocks`. - // - // "less reliable" because if the RPC node has holds in its ledger then the block production data will be - // incorrect. This condition currently can't be detected over RPC - // + let confirmed_blocks: Vec<_> = (start_slot..=end_slot) + .filter(|slot| slot_history.check(*slot) == slot_history::Check::Found) + .collect(); + (confirmed_blocks, start_slot) + } else { + // Slow, less reliable path using `getBlocks`. + // + // "less reliable" because if the RPC node has holds in its ledger then the block production data will be + // incorrect. This condition currently can't be detected over RPC + // - let minimum_ledger_slot = rpc_client.minimum_ledger_slot()?; - if minimum_ledger_slot > end_slot { - return Err(format!( - "Ledger data not available for slots {} to {} (minimum ledger slot is {})", - start_slot, end_slot, minimum_ledger_slot + let minimum_ledger_slot = rpc_client.minimum_ledger_slot()?; + if minimum_ledger_slot > end_slot { + return Err(format!( + "Ledger data not available for slots {start_slot} to {end_slot} (minimum ledger slot is {minimum_ledger_slot})" ) .into()); - } + } - if minimum_ledger_slot > start_slot { - progress_bar.println(format!( + if minimum_ledger_slot > start_slot { + progress_bar.println(format!( "{}", style(format!( - "Note: Requested start slot was {} but minimum ledger slot is {}", - start_slot, minimum_ledger_slot + "Note: Requested start slot was {start_slot} but minimum ledger slot is {minimum_ledger_slot}" )) .italic(), )); - start_slot = minimum_ledger_slot; - } + start_slot = minimum_ledger_slot; + } - let confirmed_blocks = rpc_client.get_blocks(start_slot, Some(end_slot))?; - (confirmed_blocks, start_slot) - }; + let confirmed_blocks = rpc_client.get_blocks(start_slot, Some(end_slot))?; + (confirmed_blocks, start_slot) + }; let start_slot_index = (start_slot - first_slot_in_epoch) as usize; let end_slot_index = (end_slot - first_slot_in_epoch) as usize; @@ -1259,11 +1250,11 @@ pub fn process_show_block_production( let mut leader_slot_count = HashMap::new(); let mut leader_skipped_slots = HashMap::new(); - progress_bar.set_message(format!("Fetching leader schedule for epoch {}...", epoch)); + progress_bar.set_message(format!("Fetching leader schedule for epoch {epoch}...")); let leader_schedule = rpc_client .get_leader_schedule_with_commitment(Some(start_slot), CommitmentConfig::finalized())?; if leader_schedule.is_none() { - return Err(format!("Unable to fetch leader schedule for slot {}", start_slot).into()); + return Err(format!("Unable to fetch leader schedule for slot {start_slot}").into()); } let leader_schedule = leader_schedule.unwrap(); @@ -1279,8 +1270,7 @@ pub fn process_show_block_production( } progress_bar.set_message(format!( - "Processing {} slots containing {} blocks and {} empty slots...", - total_slots, total_blocks_produced, total_slots_skipped + "Processing {total_slots} slots containing {total_blocks_produced} blocks and {total_slots_skipped} empty slots..." )); let mut confirmed_blocks_index = 0; @@ -1480,7 +1470,7 @@ pub fn process_ping( sequence: seq, lamports: Some(lamports), }; - eprint!("{}", cli_ping_data); + eprint!("{cli_ping_data}"); cli_pings.push(cli_ping_data); confirmed_count += 1; } @@ -1495,7 +1485,7 @@ pub fn process_ping( sequence: seq, lamports: None, }; - eprint!("{}", cli_ping_data); + eprint!("{cli_ping_data}"); cli_pings.push(cli_ping_data); } } @@ -1513,7 +1503,7 @@ pub fn process_ping( sequence: seq, lamports: None, }; - eprint!("{}", cli_ping_data); + eprint!("{cli_ping_data}"); cli_pings.push(cli_ping_data); break; } @@ -1538,7 +1528,7 @@ pub fn process_ping( sequence: seq, lamports: None, }; - eprint!("{}", cli_ping_data); + eprint!("{cli_ping_data}"); cli_pings.push(cli_ping_data); } } @@ -1637,11 +1627,11 @@ pub fn process_logs(config: &CliConfig, filter: &RpcTransactionLogsFilter) -> Pr ); println!(" Log Messages:"); for log in logs.value.logs { - println!(" {}", log); + println!(" {log}"); } } Err(err) => { - return Ok(format!("Disconnected: {}", err)); + return Ok(format!("Disconnected: {err}")); } } } @@ -1666,7 +1656,7 @@ pub fn process_live_slots(config: &CliConfig) -> ProcessResult { let mut slots_per_second = std::f64::NAN; loop { if exit.load(Ordering::Relaxed) { - eprintln!("{}", message); + eprintln!("{message}"); client.shutdown().unwrap(); break; } @@ -1686,11 +1676,10 @@ pub fn process_live_slots(config: &CliConfig) -> ProcessResult { } message = if slots_per_second.is_nan() { - format!("{:?}", new_info) + format!("{new_info:?}") } else { format!( - "{:?} | root slot advancing at {:.2} slots/second", - new_info, slots_per_second + "{new_info:?} | root slot advancing at {slots_per_second:.2} slots/second" ) }; slot_progress.set_message(message.clone()); @@ -1723,7 +1712,7 @@ pub fn process_live_slots(config: &CliConfig) -> ProcessResult { current = Some(new_info); } Err(err) => { - eprintln!("disconnected: {}", err); + eprintln!("disconnected: {err}"); break; } } @@ -2051,11 +2040,11 @@ pub fn process_transaction_history( format!("timestamp={} ", unix_timestamp_to_string(block_time)), }, if let Some(err) = result.err { - format!("Failed: {:?}", err) + format!("Failed: {err:?}") } else { match result.confirmation_status { None => "Finalized".to_string(), - Some(status) => format!("{:?}", status), + Some(status) => format!("{status:?}"), } }, result.memo.unwrap_or_default(), @@ -2087,7 +2076,7 @@ pub fn process_transaction_history( None, ); } - Err(err) => println!(" Unable to get confirmed transaction details: {}", err), + Err(err) => println!(" Unable to get confirmed transaction details: {err}"), } } println!(); diff --git a/cli/src/feature.rs b/cli/src/feature.rs index c75ac6abc..c31254cf2 100644 --- a/cli/src/feature.rs +++ b/cli/src/feature.rs @@ -142,7 +142,7 @@ impl fmt::Display for CliFeatures { } CliFeatureStatus::Active(activation_slot) => { let activation_epoch = self.epoch_schedule.get_epoch(activation_slot); - style(format!("active since epoch {}", activation_epoch)).green() + style(format!("active since epoch {activation_epoch}")).green() } }, match feature.status { @@ -154,11 +154,11 @@ impl fmt::Display for CliFeatures { } if let Some(software_versions) = &self.cluster_software_versions { - write!(f, "{}", software_versions)?; + write!(f, "{software_versions}")?; } if let Some(feature_sets) = &self.cluster_feature_sets { - write!(f, "{}", feature_sets)?; + write!(f, "{feature_sets}")?; } if self.inactive && !self.feature_activation_allowed { @@ -233,13 +233,7 @@ impl fmt::Display for CliClusterSoftwareVersions { f, "{}", style(format!( - "{1:<0$} {3:>2$} {5:>4$}", - max_software_version_len, - software_version_title, - max_stake_percent_len, - stake_percent_title, - max_rpc_percent_len, - rpc_percent_title, + "{software_version_title:max_stake_percent_len$} {rpc_percent_title:>max_rpc_percent_len$}", )) .bold(), )?; @@ -348,15 +342,7 @@ impl fmt::Display for CliClusterFeatureSets { f, "{}", style(format!( - "{1:<0$} {3:<2$} {5:>4$} {7:>6$}", - max_software_versions_len, - software_versions_title, - max_feature_set_len, - feature_set_title, - max_stake_percent_len, - stake_percent_title, - max_rpc_percent_len, - rpc_percent_title, + "{software_versions_title:max_stake_percent_len$} {rpc_percent_title:>max_rpc_percent_len$}", )) .bold(), )?; @@ -454,8 +440,7 @@ fn known_feature(feature: &Pubkey) -> Result<(), CliError> { Ok(()) } else { Err(CliError::BadParameter(format!( - "Unknown feature: {}", - feature + "Unknown feature: {feature}" ))) } } @@ -867,7 +852,7 @@ fn process_activate( if let Some(account) = account { if feature::from_account(&account).is_some() { - return Err(format!("{} has already been activated", feature_id).into()); + return Err(format!("{feature_id} has already been activated").into()); } } diff --git a/cli/src/inflation.rs b/cli/src/inflation.rs index 58b34d422..a166f366e 100644 --- a/cli/src/inflation.rs +++ b/cli/src/inflation.rs @@ -107,9 +107,9 @@ fn process_rewards( .get_inflation_reward(addresses, rewards_epoch) .map_err(|err| { if let Some(epoch) = rewards_epoch { - format!("Rewards not available for epoch {}", epoch) + format!("Rewards not available for epoch {epoch}") } else { - format!("Rewards not available {}", err) + format!("Rewards not available {err}") } })?; let epoch_schedule = rpc_client.get_epoch_schedule()?; diff --git a/cli/src/main.rs b/cli/src/main.rs index 58733cf0b..703e80be9 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -63,7 +63,7 @@ fn parse_settings(matches: &ArgMatches<'_>) -> Result unreachable!(), }; - println_name_value_or(&format!("{}:", field_name), &value, setting_type); + println_name_value_or(&format!("{field_name}:"), &value, setting_type); } else { println_name_value("Config File:", config_file); println_name_value_or("RPC URL:", &json_rpc_url, url_setting_type); @@ -123,12 +123,12 @@ fn parse_settings(matches: &ArgMatches<'_>) -> Result { let filename = value_t_or_exit!(subcommand_matches, "filename", PathBuf); config.export_address_labels(&filename)?; - println!("Address labels exported to {:?}", filename); + println!("Address labels exported to {filename:?}"); } _ => unreachable!(), } @@ -247,7 +247,7 @@ fn do_main(matches: &ArgMatches<'_>) -> Result<(), Box> { let (mut config, signers) = parse_args(matches, &mut wallet_manager)?; config.signers = signers.iter().map(|s| s.as_ref()).collect(); let result = process_command(&config)?; - println!("{}", result); + println!("{result}"); }; Ok(()) } diff --git a/cli/src/nonce.rs b/cli/src/nonce.rs index 33bc01d8a..61a1824e9 100644 --- a/cli/src/nonce.rs +++ b/cli/src/nonce.rs @@ -507,12 +507,9 @@ pub fn process_create_nonce_account( if let Ok(nonce_account) = get_account(rpc_client, &nonce_account_address) { let err_msg = if state_from_account(&nonce_account).is_ok() { - format!("Nonce account {} already exists", nonce_account_address) + format!("Nonce account {nonce_account_address} already exists") } else { - format!( - "Account {} already exists and is not a nonce account", - nonce_account_address - ) + format!("Account {nonce_account_address} already exists and is not a nonce account") }; return Err(CliError::BadParameter(err_msg).into()); } @@ -520,8 +517,7 @@ pub fn process_create_nonce_account( let minimum_balance = rpc_client.get_minimum_balance_for_rent_exemption(State::size())?; if lamports < minimum_balance { return Err(CliError::BadParameter(format!( - "need at least {} lamports for nonce account to be rent exempt, provided lamports: {}", - minimum_balance, lamports + "need at least {minimum_balance} lamports for nonce account to be rent exempt, provided lamports: {lamports}" )) .into()); } @@ -593,8 +589,7 @@ pub fn process_new_nonce( if let Err(err) = rpc_client.get_account(nonce_account) { return Err(CliError::BadParameter(format!( - "Unable to advance nonce account {}. error: {}", - nonce_account, err + "Unable to advance nonce account {nonce_account}. error: {err}" )) .into()); } diff --git a/cli/src/program.rs b/cli/src/program.rs index edd4683fe..b632cacda 100644 --- a/cli/src/program.rs +++ b/cli/src/program.rs @@ -843,8 +843,7 @@ fn process_program_deploy( { if account.owner != bpf_loader_upgradeable::id() { return Err(format!( - "Account {} is not an upgradeable program or already in use", - program_pubkey + "Account {program_pubkey} is not an upgradeable program or already in use" ) .into()); } @@ -867,7 +866,7 @@ fn process_program_deploy( { if program_authority_pubkey.is_none() { return Err( - format!("Program {} is no longer upgradeable", program_pubkey).into(), + format!("Program {program_pubkey} is no longer upgradeable").into() ); } if program_authority_pubkey != Some(upgrade_authority_signer.pubkey()) { @@ -882,20 +881,18 @@ fn process_program_deploy( false } else { return Err(format!( - "Program {} has been closed, use a new Program Id", - program_pubkey + "Program {program_pubkey} has been closed, use a new Program Id" ) .into()); } } else { return Err(format!( - "Program {} has been closed, use a new Program Id", - program_pubkey + "Program {program_pubkey} has been closed, use a new Program Id" ) .into()); } } else { - return Err(format!("{} is not an upgradeable program", program_pubkey).into()); + return Err(format!("{program_pubkey} is not an upgradeable program").into()); } } else { // do new deploy @@ -1056,7 +1053,7 @@ fn process_write_buffer( { if let Ok(UpgradeableLoaderState::Buffer { authority_address }) = account.state() { if authority_address.is_none() { - return Err(format!("Buffer {} is immutable", buffer_pubkey).into()); + return Err(format!("Buffer {buffer_pubkey} is immutable").into()); } if authority_address != Some(buffer_authority.pubkey()) { return Err(format!( @@ -1067,11 +1064,9 @@ fn process_write_buffer( .into()); } } else { - return Err(format!( - "{} is not an upgradeable loader buffer account", - buffer_pubkey - ) - .into()); + return Err( + format!("{buffer_pubkey} is not an upgradeable loader buffer account").into(), + ); } } @@ -1161,7 +1156,7 @@ fn process_set_authority( ..RpcSendTransactionConfig::default() }, ) - .map_err(|e| format!("Setting authority failed: {}", e))?; + .map_err(|e| format!("Setting authority failed: {e}"))?; let authority = CliProgramAuthority { authority: new_authority @@ -1220,7 +1215,7 @@ fn get_buffers( use_lamports_unit, }); } else { - return Err(format!("Error parsing Buffer account {}", address).into()); + return Err(format!("Error parsing Buffer account {address}").into()); } } Ok(CliUpgradeableBuffers { @@ -1269,8 +1264,7 @@ fn get_programs( let results = get_accounts_with_filter(rpc_client, filters, 0)?; if results.len() != 1 { return Err(format!( - "Error: More than one Program associated with ProgramData account {}", - programdata_address + "Error: More than one Program associated with ProgramData account {programdata_address}" ) .into()); } @@ -1288,9 +1282,7 @@ fn get_programs( use_lamports_unit, }); } else { - return Err( - format!("Error parsing ProgramData account {}", programdata_address).into(), - ); + return Err(format!("Error parsing ProgramData account {programdata_address}").into()); } } Ok(CliUpgradeablePrograms { @@ -1370,10 +1362,10 @@ fn process_show( use_lamports_unit, })) } else { - Err(format!("Program {} has been closed", account_pubkey).into()) + Err(format!("Program {account_pubkey} has been closed").into()) } } else { - Err(format!("Program {} has been closed", account_pubkey).into()) + Err(format!("Program {account_pubkey} has been closed").into()) } } else if let Ok(UpgradeableLoaderState::Buffer { authority_address }) = account.state() @@ -1392,16 +1384,15 @@ fn process_show( })) } else { Err(format!( - "{} is not an upgradeable loader Buffer or Program account", - account_pubkey + "{account_pubkey} is not an upgradeable loader Buffer or Program account" ) .into()) } } else { - Err(format!("{} is not an SBF program", account_pubkey).into()) + Err(format!("{account_pubkey} is not an SBF program").into()) } } else { - Err(format!("Unable to find the account {}", account_pubkey).into()) + Err(format!("Unable to find the account {account_pubkey}").into()) } } else if programs { let authority_pubkey = if all { None } else { Some(authority_pubkey) }; @@ -1430,7 +1421,7 @@ fn process_dump( if account.owner == bpf_loader::id() || account.owner == bpf_loader_deprecated::id() { let mut f = File::create(output_location)?; f.write_all(&account.data)?; - Ok(format!("Wrote program to {}", output_location)) + Ok(format!("Wrote program to {output_location}")) } else if account.owner == bpf_loader_upgradeable::id() { if let Ok(UpgradeableLoaderState::Program { programdata_address, @@ -1447,31 +1438,30 @@ fn process_dump( let program_data = &programdata_account.data[offset..]; let mut f = File::create(output_location)?; f.write_all(program_data)?; - Ok(format!("Wrote program to {}", output_location)) + Ok(format!("Wrote program to {output_location}")) } else { - Err(format!("Program {} has been closed", account_pubkey).into()) + Err(format!("Program {account_pubkey} has been closed").into()) } } else { - Err(format!("Program {} has been closed", account_pubkey).into()) + Err(format!("Program {account_pubkey} has been closed").into()) } } else if let Ok(UpgradeableLoaderState::Buffer { .. }) = account.state() { let offset = UpgradeableLoaderState::size_of_buffer_metadata(); let program_data = &account.data[offset..]; let mut f = File::create(output_location)?; f.write_all(program_data)?; - Ok(format!("Wrote program to {}", output_location)) + Ok(format!("Wrote program to {output_location}")) } else { Err(format!( - "{} is not an upgradeable loader buffer or program account", - account_pubkey + "{account_pubkey} is not an upgradeable loader buffer or program account" ) .into()) } } else { - Err(format!("{} is not an SBF program", account_pubkey).into()) + Err(format!("{account_pubkey} is not an SBF program").into()) } } else { - Err(format!("Unable to find the account {}", account_pubkey).into()) + Err(format!("Unable to find the account {account_pubkey}").into()) } } else { Err("No account specified".into()) @@ -1522,7 +1512,7 @@ fn close( { return Err("Closing a program account is not supported by the cluster".into()); } else { - return Err(format!("Close failed: {}", err).into()); + return Err(format!("Close failed: {err}").into()); } } Ok(()) @@ -1618,16 +1608,16 @@ fn process_close( )) } } else { - Err(format!("Program {} has been closed", account_pubkey).into()) + Err(format!("Program {account_pubkey} has been closed").into()) } } else { - Err(format!("Program {} has been closed", account_pubkey).into()) + Err(format!("Program {account_pubkey} has been closed").into()) } } - _ => Err(format!("{} is not a Program or Buffer account", account_pubkey).into()), + _ => Err(format!("{account_pubkey} is not a Program or Buffer account").into()), } } else { - Err(format!("Unable to find the account {}", account_pubkey).into()) + Err(format!("Unable to find the account {account_pubkey}").into()) } } else { let buffers = get_buffers( @@ -1996,10 +1986,10 @@ fn do_process_program_upgrade( fn read_and_verify_elf(program_location: &str) -> Result, Box> { let mut file = File::open(program_location) - .map_err(|err| format!("Unable to open program file: {}", err))?; + .map_err(|err| format!("Unable to open program file: {err}"))?; let mut program_data = Vec::new(); file.read_to_end(&mut program_data) - .map_err(|err| format!("Unable to read program file: {}", err))?; + .map_err(|err| format!("Unable to read program file: {err}"))?; let mut transaction_context = TransactionContext::new(Vec::new(), Some(Rent::default()), 1, 1); let invoke_context = InvokeContext::new_mock(&mut transaction_context, &[]); @@ -2012,10 +2002,10 @@ fn read_and_verify_elf(program_location: &str) -> Result, Box::from_executable(executable) - .map_err(|err| format!("ELF error: {}", err))?; + .map_err(|err| format!("ELF error: {err}"))?; Ok(program_data) } @@ -2132,7 +2122,7 @@ fn send_deploy_messages( } let result = rpc_client.send_and_confirm_transaction_with_spinner(&initial_transaction); log_instruction_custom_error::(result, config) - .map_err(|err| format!("Account allocation failed: {}", err))?; + .map_err(|err| format!("Account allocation failed: {err}"))?; } else { return Err("Buffer account not created yet, must provide a key pair".into()); } @@ -2157,7 +2147,7 @@ fn send_deploy_messages( write_messages, &[payer_signer, write_signer], ) - .map_err(|err| format!("Data writes to account failed: {}", err))? + .map_err(|err| format!("Data writes to account failed: {err}"))? .into_iter() .flatten() .collect::>(); @@ -2192,7 +2182,7 @@ fn send_deploy_messages( ..RpcSendTransactionConfig::default() }, ) - .map_err(|e| format!("Deploying program failed: {}", e))?; + .map_err(|e| format!("Deploying program failed: {e}"))?; } } @@ -2212,22 +2202,13 @@ fn create_ephemeral_keypair( fn report_ephemeral_mnemonic(words: usize, mnemonic: bip39::Mnemonic) { let phrase: &str = mnemonic.phrase(); let divider = String::from_utf8(vec![b'='; phrase.len()]).unwrap(); - eprintln!( - "{}\nRecover the intermediate account's ephemeral keypair file with", - divider - ); - eprintln!( - "`solana-keygen recover` and the following {}-word seed phrase:", - words - ); - eprintln!("{}\n{}\n{}", divider, phrase, divider); + eprintln!("{divider}\nRecover the intermediate account's ephemeral keypair file with"); + eprintln!("`solana-keygen recover` and the following {words}-word seed phrase:"); + eprintln!("{divider}\n{phrase}\n{divider}"); eprintln!("To resume a deploy, pass the recovered keypair as the"); eprintln!("[BUFFER_SIGNER] to `solana program deploy` or `solana program write-buffer'."); eprintln!("Or to recover the account's lamports, pass it as the"); - eprintln!( - "[BUFFER_ACCOUNT_ADDRESS] argument to `solana program close`.\n{}", - divider - ); + eprintln!("[BUFFER_ACCOUNT_ADDRESS] argument to `solana program close`.\n{divider}"); } #[cfg(test)] diff --git a/cli/src/stake.rs b/cli/src/stake.rs index 430cad30b..a77314053 100644 --- a/cli/src/stake.rs +++ b/cli/src/stake.rs @@ -1400,12 +1400,9 @@ pub fn process_create_stake_account( if !sign_only { if let Ok(stake_account) = rpc_client.get_account(&stake_account_address) { let err_msg = if stake_account.owner == stake::program::id() { - format!("Stake account {} already exists", stake_account_address) + format!("Stake account {stake_account_address} already exists") } else { - format!( - "Account {} already exists and is not a stake account", - stake_account_address - ) + format!("Account {stake_account_address} already exists and is not a stake account") }; return Err(CliError::BadParameter(err_msg).into()); } @@ -1415,8 +1412,7 @@ pub fn process_create_stake_account( if lamports < minimum_balance { return Err(CliError::BadParameter(format!( - "need at least {} lamports for stake account to be rent exempt, provided lamports: {}", - minimum_balance, lamports + "need at least {minimum_balance} lamports for stake account to be rent exempt, provided lamports: {lamports}" )) .into()); } @@ -1506,8 +1502,7 @@ pub fn process_stake_authorize( } } else { return Err(CliError::RpcRequestError(format!( - "{:?} is not an Initialized or Delegated stake account", - stake_account_pubkey, + "{stake_account_pubkey:?} is not an Initialized or Delegated stake account", )) .into()); } @@ -1614,8 +1609,7 @@ pub fn process_deactivate_stake_account( let stake_account = rpc_client.get_account(&stake_account_address)?; if stake_account.owner != stake::program::id() { return Err(CliError::BadParameter(format!( - "{} is not a stake account", - stake_account_address, + "{stake_account_address} is not a stake account", )) .into()); } @@ -1625,16 +1619,14 @@ pub fn process_deactivate_stake_account( StakeState::Stake(_, stake) => stake.delegation.voter_pubkey, _ => { return Err(CliError::BadParameter(format!( - "{} is not a delegated stake account", - stake_account_address, + "{stake_account_address} is not a delegated stake account", )) .into()) } }, Err(err) => { return Err(CliError::RpcRequestError(format!( - "Account data could not be deserialized to stake state: {}", - err + "Account data could not be deserialized to stake state: {err}" )) .into()) } @@ -1879,14 +1871,10 @@ pub fn process_split_stake( if !sign_only { if let Ok(stake_account) = rpc_client.get_account(&split_stake_account_address) { let err_msg = if stake_account.owner == stake::program::id() { - format!( - "Stake account {} already exists", - split_stake_account_address - ) + format!("Stake account {split_stake_account_address} already exists") } else { format!( - "Account {} already exists and is not a stake account", - split_stake_account_address + "Account {split_stake_account_address} already exists and is not a stake account" ) }; return Err(CliError::BadParameter(err_msg).into()); @@ -1897,8 +1885,7 @@ pub fn process_split_stake( if lamports < minimum_balance { return Err(CliError::BadParameter(format!( - "need at least {} lamports for stake account to be rent exempt, provided lamports: {}", - minimum_balance, lamports + "need at least {minimum_balance} lamports for stake account to be rent exempt, provided lamports: {lamports}" )) .into()); } @@ -2016,8 +2003,7 @@ pub fn process_merge_stake( if let Ok(stake_account) = rpc_client.get_account(stake_account_address) { if stake_account.owner != stake::program::id() { return Err(CliError::BadParameter(format!( - "Account {} is not a stake account", - stake_account_address + "Account {stake_account_address} is not a stake account" )) .into()); } @@ -2126,8 +2112,7 @@ pub fn process_stake_set_lockup( } } else { return Err(CliError::RpcRequestError(format!( - "{:?} is not an Initialized or Delegated stake account", - stake_account_pubkey, + "{stake_account_pubkey:?} is not an Initialized or Delegated stake account", )) .into()); } @@ -2287,19 +2272,17 @@ fn get_stake_account_state( .get_account_with_commitment(stake_account_pubkey, commitment_config)? .value .ok_or_else(|| { - CliError::RpcRequestError(format!("{:?} account does not exist", stake_account_pubkey)) + CliError::RpcRequestError(format!("{stake_account_pubkey:?} account does not exist")) })?; if stake_account.owner != stake::program::id() { return Err(CliError::RpcRequestError(format!( - "{:?} is not a stake account", - stake_account_pubkey, + "{stake_account_pubkey:?} is not a stake account", )) .into()); } stake_account.state().map_err(|err| { CliError::RpcRequestError(format!( - "Account data could not be deserialized to stake state: {}", - err + "Account data could not be deserialized to stake state: {err}" )) .into() }) @@ -2311,8 +2294,7 @@ pub(crate) fn check_current_authority( ) -> Result<(), CliError> { if !permitted_authorities.contains(provided_current_authority) { Err(CliError::RpcRequestError(format!( - "Invalid authority provided: {:?}, expected {:?}", - provided_current_authority, permitted_authorities + "Invalid authority provided: {provided_current_authority:?}, expected {permitted_authorities:?}" ))) } else { Ok(()) @@ -2396,7 +2378,7 @@ pub(crate) fn fetch_epoch_rewards( if let Ok(rewards) = rpc_client.get_inflation_reward(&[*address], Some(rewards_epoch)) { process_reward(&rewards[0])?; } else { - eprintln!("Rewards not available for epoch {}", rewards_epoch); + eprintln!("Rewards not available for epoch {rewards_epoch}"); } num_epochs = num_epochs.saturating_sub(1); } @@ -2414,8 +2396,7 @@ pub fn process_show_stake_account( let stake_account = rpc_client.get_account(stake_account_address)?; if stake_account.owner != stake::program::id() { return Err(CliError::RpcRequestError(format!( - "{:?} is not a stake account", - stake_account_address, + "{stake_account_address:?} is not a stake account", )) .into()); } @@ -2443,7 +2424,7 @@ pub fn process_show_stake_account( match fetch_epoch_rewards(rpc_client, stake_account_address, num_epochs) { Ok(rewards) => Some(rewards), Err(error) => { - eprintln!("Failed to fetch epoch rewards: {:?}", error); + eprintln!("Failed to fetch epoch rewards: {error:?}"); None } } @@ -2453,8 +2434,7 @@ pub fn process_show_stake_account( Ok(config.output_format.formatted_string(&state)) } Err(err) => Err(CliError::RpcRequestError(format!( - "Account data could not be deserialized to stake state: {}", - err + "Account data could not be deserialized to stake state: {err}" )) .into()), } @@ -2540,8 +2520,7 @@ pub fn process_delegate_stake( .get_account(vote_account_pubkey) .map_err(|err| { CliError::RpcRequestError(format!( - "Vote account not found: {}. error: {}", - vote_account_pubkey, err, + "Vote account not found: {vote_account_pubkey}. error: {err}", )) })? .data; @@ -2563,8 +2542,7 @@ pub fn process_delegate_stake( if root_slot < min_root_slot { Err(CliError::DynamicProgramError(format!( "Unable to delegate. Vote account appears delinquent \ - because its current root slot, {}, is less than {}", - root_slot, min_root_slot + because its current root slot, {root_slot}, is less than {min_root_slot}" ))) } else { Ok(()) @@ -2576,7 +2554,7 @@ pub fn process_delegate_stake( if !force { sanity_check_result?; } else { - println!("--force supplied, ignoring: {}", err); + println!("--force supplied, ignoring: {err}"); } } } @@ -3469,7 +3447,7 @@ mod tests { // Test Authorize Subcommand w/ sign-only let blockhash = Hash::default(); - let blockhash_string = format!("{}", blockhash); + let blockhash_string = format!("{blockhash}"); let test_authorize = test_commands.clone().get_matches_from(vec![ "test", "stake-authorize", @@ -3744,7 +3722,7 @@ mod tests { ); // Test Authorize Subcommand w/ absentee fee-payer let sig = fee_payer_keypair.sign_message(&[0u8]); - let signer = format!("{}={}", fee_payer_string, sig); + let signer = format!("{fee_payer_string}={sig}"); let test_authorize = test_commands.clone().get_matches_from(vec![ "test", "stake-authorize", @@ -3792,9 +3770,9 @@ mod tests { // Test CreateStakeAccount SubCommand let custodian = solana_sdk::pubkey::new_rand(); - let custodian_string = format!("{}", custodian); + let custodian_string = format!("{custodian}"); let authorized = solana_sdk::pubkey::new_rand(); - let authorized_string = format!("{}", authorized); + let authorized_string = format!("{authorized}"); let test_create_stake_account = test_commands.clone().get_matches_from(vec![ "test", "create-stake-account", @@ -3942,7 +3920,7 @@ mod tests { let offline_pubkey = offline.pubkey(); let offline_string = offline_pubkey.to_string(); let offline_sig = offline.sign_message(&[3u8]); - let offline_signer = format!("{}={}", offline_pubkey, offline_sig); + let offline_signer = format!("{offline_pubkey}={offline_sig}"); let nonce_hash = Hash::new(&[4u8; 32]); let nonce_hash_string = nonce_hash.to_string(); let test_create_stake_account2 = test_commands.clone().get_matches_from(vec![ @@ -4096,7 +4074,7 @@ mod tests { // Test Delegate Subcommand w/ Blockhash let blockhash = Hash::default(); - let blockhash_string = format!("{}", blockhash); + let blockhash_string = format!("{blockhash}"); let test_delegate_stake = test_commands.clone().get_matches_from(vec![ "test", "delegate-stake", @@ -4164,7 +4142,7 @@ mod tests { // Test Delegate Subcommand w/ absent fee payer let key1 = solana_sdk::pubkey::new_rand(); let sig1 = Keypair::new().sign_message(&[0u8]); - let signer1 = format!("{}={}", key1, sig1); + let signer1 = format!("{key1}={sig1}"); let test_delegate_stake = test_commands.clone().get_matches_from(vec![ "test", "delegate-stake", @@ -4208,7 +4186,7 @@ mod tests { // Test Delegate Subcommand w/ absent fee payer and absent nonce authority let key2 = solana_sdk::pubkey::new_rand(); let sig2 = Keypair::new().sign_message(&[0u8]); - let signer2 = format!("{}={}", key2, sig2); + let signer2 = format!("{key2}={sig2}"); let test_delegate_stake = test_commands.clone().get_matches_from(vec![ "test", "delegate-stake", @@ -4624,7 +4602,7 @@ mod tests { // Test Deactivate Subcommand w/ Blockhash let blockhash = Hash::default(); - let blockhash_string = format!("{}", blockhash); + let blockhash_string = format!("{blockhash}"); let test_deactivate_stake = test_commands.clone().get_matches_from(vec![ "test", "deactivate-stake", @@ -4688,7 +4666,7 @@ mod tests { // Test Deactivate Subcommand w/ absent fee payer let key1 = solana_sdk::pubkey::new_rand(); let sig1 = Keypair::new().sign_message(&[0u8]); - let signer1 = format!("{}={}", key1, sig1); + let signer1 = format!("{key1}={sig1}"); let test_deactivate_stake = test_commands.clone().get_matches_from(vec![ "test", "deactivate-stake", @@ -4730,7 +4708,7 @@ mod tests { // Test Deactivate Subcommand w/ absent fee payer and nonce authority let key2 = solana_sdk::pubkey::new_rand(); let sig2 = Keypair::new().sign_message(&[0u8]); - let signer2 = format!("{}={}", key2, sig2); + let signer2 = format!("{key2}={sig2}"); let test_deactivate_stake = test_commands.clone().get_matches_from(vec![ "test", "deactivate-stake", @@ -4857,12 +4835,12 @@ mod tests { let nonce_auth_pubkey = nonce_auth.pubkey(); let nonce_auth_string = nonce_auth_pubkey.to_string(); let nonce_sig = nonce_auth.sign_message(&[0u8]); - let nonce_signer = format!("{}={}", nonce_auth_pubkey, nonce_sig); + let nonce_signer = format!("{nonce_auth_pubkey}={nonce_sig}"); let stake_auth = keypair_from_seed(&[3u8; 32]).unwrap(); let stake_auth_pubkey = stake_auth.pubkey(); let stake_auth_string = stake_auth_pubkey.to_string(); let stake_sig = stake_auth.sign_message(&[0u8]); - let stake_signer = format!("{}={}", stake_auth_pubkey, stake_sig); + let stake_signer = format!("{stake_auth_pubkey}={stake_sig}"); let nonce_hash = Hash::new(&[4u8; 32]); let nonce_hash_string = nonce_hash.to_string(); diff --git a/cli/src/validator_info.rs b/cli/src/validator_info.rs index 135942aa8..b27419128 100644 --- a/cli/src/validator_info.rs +++ b/cli/src/validator_info.rs @@ -33,8 +33,7 @@ use { pub fn check_details_length(string: String) -> Result<(), String> { if string.len() > MAX_LONG_FIELD_LENGTH { Err(format!( - "validator details longer than {:?}-byte limit", - MAX_LONG_FIELD_LENGTH + "validator details longer than {MAX_LONG_FIELD_LENGTH:?}-byte limit" )) } else { Ok(()) @@ -46,8 +45,7 @@ pub fn check_url(string: String) -> Result<(), String> { is_url(string.clone())?; if string.len() > MAX_SHORT_FIELD_LENGTH { Err(format!( - "url longer than {:?}-byte limit", - MAX_SHORT_FIELD_LENGTH + "url longer than {MAX_SHORT_FIELD_LENGTH:?}-byte limit" )) } else { Ok(()) @@ -58,8 +56,7 @@ pub fn check_url(string: String) -> Result<(), String> { pub fn is_short_field(string: String) -> Result<(), String> { if string.len() > MAX_SHORT_FIELD_LENGTH { Err(format!( - "validator field longer than {:?}-byte limit", - MAX_SHORT_FIELD_LENGTH + "validator field longer than {MAX_SHORT_FIELD_LENGTH:?}-byte limit" )) } else { Ok(()) @@ -71,22 +68,16 @@ fn verify_keybase( keybase_username: &Value, ) -> Result<(), Box> { if let Some(keybase_username) = keybase_username.as_str() { - let url = format!( - "https://keybase.pub/{}/solana/validator-{:?}", - keybase_username, validator_pubkey - ); + let url = + format!("https://keybase.pub/{keybase_username}/solana/validator-{validator_pubkey:?}"); let client = Client::new(); if client.head(&url).send()?.status().is_success() { Ok(()) } else { - Err(format!("keybase_username could not be confirmed at: {}. Please add this pubkey file to your keybase profile to connect", url).into()) + Err(format!("keybase_username could not be confirmed at: {url}. Please add this pubkey file to your keybase profile to connect").into()) } } else { - Err(format!( - "keybase_username could not be parsed as String: {}", - keybase_username - ) - .into()) + Err(format!("keybase_username could not be parsed as String: {keybase_username}").into()) } } @@ -116,7 +107,7 @@ fn parse_validator_info( account: &Account, ) -> Result<(Pubkey, Map), Box> { if account.owner != solana_config_program::id() { - return Err(format!("{} is not a validator info account", pubkey).into()); + return Err(format!("{pubkey} is not a validator info account").into()); } let key_list: ConfigKeys = deserialize(&account.data)?; if !key_list.keys.is_empty() { @@ -125,7 +116,7 @@ fn parse_validator_info( let validator_info: Map<_, _> = serde_json::from_str(&validator_info_string)?; Ok((validator_pubkey, validator_info)) } else { - Err(format!("{} could not be parsed as a validator info account", pubkey).into()) + Err(format!("{pubkey} could not be parsed as a validator info account").into()) } } @@ -251,10 +242,10 @@ pub fn process_set_validator_info( let result = verify_keybase(&config.signers[0].pubkey(), string); if result.is_err() { if force_keybase { - println!("--force supplied, ignoring: {:?}", result); + println!("--force supplied, ignoring: {result:?}"); } else { result.map_err(|err| { - CliError::BadParameter(format!("Invalid validator keybase username: {}", err)) + CliError::BadParameter(format!("Invalid validator keybase username: {err}")) })?; } } @@ -300,10 +291,7 @@ pub fn process_set_validator_info( let signers = if balance == 0 { if info_pubkey != info_keypair.pubkey() { - println!( - "Account {:?} does not exist. Generating new keypair...", - info_pubkey - ); + println!("Account {info_pubkey:?} does not exist. Generating new keypair..."); info_pubkey = info_keypair.pubkey(); } vec![config.signers[0], &info_keypair] @@ -362,8 +350,8 @@ pub fn process_set_validator_info( tx.try_sign(&signers, latest_blockhash)?; let signature_str = rpc_client.send_and_confirm_transaction_with_spinner(&tx)?; - println!("Success! Validator info published at: {:?}", info_pubkey); - println!("{}", signature_str); + println!("Success! Validator info published at: {info_pubkey:?}"); + println!("{signature_str}"); Ok("".to_string()) } @@ -428,8 +416,7 @@ mod tests { assert_eq!( check_details_length(long_details), Err(format!( - "validator details longer than {:?}-byte limit", - MAX_LONG_FIELD_LENGTH + "validator details longer than {MAX_LONG_FIELD_LENGTH:?}-byte limit" )) ); } diff --git a/cli/src/vote.rs b/cli/src/vote.rs index 269948473..0104e6764 100644 --- a/cli/src/vote.rs +++ b/cli/src/vote.rs @@ -860,11 +860,10 @@ pub fn process_create_vote_account( { if let Some(vote_account) = response.value { let err_msg = if vote_account.owner == solana_vote_program::id() { - format!("Vote account {} already exists", vote_account_address) + format!("Vote account {vote_account_address} already exists") } else { format!( - "Account {} already exists and is not a vote account", - vote_account_address + "Account {vote_account_address} already exists and is not a vote account" ) }; return Err(CliError::BadParameter(err_msg).into()); @@ -943,8 +942,7 @@ pub fn process_vote_authorize( if let Some(signer) = new_authorized_signer { if signer.is_interactive() { return Err(CliError::BadParameter(format!( - "invalid new authorized vote signer {:?}. Interactive vote signers not supported", - new_authorized_pubkey + "invalid new authorized vote signer {new_authorized_pubkey:?}. Interactive vote signers not supported" )).into()); } } @@ -1181,13 +1179,12 @@ pub(crate) fn get_vote_account( .get_account_with_commitment(vote_account_pubkey, commitment_config)? .value .ok_or_else(|| { - CliError::RpcRequestError(format!("{:?} account does not exist", vote_account_pubkey)) + CliError::RpcRequestError(format!("{vote_account_pubkey:?} account does not exist")) })?; if vote_account.owner != solana_vote_program::id() { return Err(CliError::RpcRequestError(format!( - "{:?} is not a vote account", - vote_account_pubkey + "{vote_account_pubkey:?} is not a vote account" )) .into()); } @@ -1236,7 +1233,7 @@ pub fn process_show_vote_account( match crate::stake::fetch_epoch_rewards(rpc_client, vote_account_address, num_epochs) { Ok(rewards) => Some(rewards), Err(error) => { - eprintln!("Failed to fetch epoch rewards: {:?}", error); + eprintln!("Failed to fetch epoch rewards: {error:?}"); None } } @@ -1387,8 +1384,7 @@ pub fn process_close_vote_account( { if vote_account.activated_stake != 0 { return Err(format!( - "Cannot close a vote account with active stake: {}", - vote_account_pubkey + "Cannot close a vote account with active stake: {vote_account_pubkey}" ) .into()); } @@ -1459,7 +1455,7 @@ mod tests { let default_signer = DefaultSigner::new("", &default_keypair_file); let blockhash = Hash::default(); - let blockhash_string = format!("{}", blockhash); + let blockhash_string = format!("{blockhash}"); let nonce_account = Pubkey::new_unique(); // Test VoteAuthorize SubCommand diff --git a/cli/src/wallet.rs b/cli/src/wallet.rs index 2278c1bde..9ed8a48c7 100644 --- a/cli/src/wallet.rs +++ b/cli/src/wallet.rs @@ -579,7 +579,7 @@ pub fn process_show_account( let mut f = File::create(output_file)?; f.write_all(account_string.as_bytes())?; writeln!(&mut account_string)?; - writeln!(&mut account_string, "Wrote account to {}", output_file)?; + writeln!(&mut account_string, "Wrote account to {output_file}")?; } } OutputFormat::Display | OutputFormat::DisplayVerbose => { @@ -587,7 +587,7 @@ pub fn process_show_account( let mut f = File::create(output_file)?; f.write_all(&data)?; writeln!(&mut account_string)?; - writeln!(&mut account_string, "Wrote account data to {}", output_file)?; + writeln!(&mut account_string, "Wrote account data to {output_file}")?; } else if !data.is_empty() { use pretty_hex::*; writeln!(&mut account_string, "{:?}", data.hex_dump())?; @@ -620,13 +620,13 @@ pub fn process_airdrop( let result = request_and_confirm_airdrop(rpc_client, config, &pubkey, lamports); if let Ok(signature) = result { let signature_cli_message = log_instruction_custom_error::(result, config)?; - println!("{}", signature_cli_message); + println!("{signature_cli_message}"); let current_balance = rpc_client.get_balance(&pubkey)?; if current_balance < pre_balance.saturating_add(lamports) { println!("Balance unchanged"); - println!("Run `solana confirm -v {:?}` for more info", signature); + println!("Run `solana confirm -v {signature:?}` for more info"); Ok("".to_string()) } else { Ok(build_balance_message(current_balance, false, true)) @@ -701,7 +701,7 @@ pub fn process_confirm( }); } Err(err) => { - get_transaction_error = Some(format!("{:?}", err)); + get_transaction_error = Some(format!("{err:?}")); } } } @@ -721,7 +721,7 @@ pub fn process_confirm( }; Ok(config.output_format.formatted_string(&cli_transaction)) } - Err(err) => Err(CliError::RpcRequestError(format!("Unable to confirm: {}", err)).into()), + Err(err) => Err(CliError::RpcRequestError(format!("Unable to confirm: {err}")).into()), } } @@ -789,10 +789,9 @@ pub fn process_transfer( .value; if recipient_balance == 0 { return Err(format!( - "The recipient address ({}) is not funded. \ + "The recipient address ({to}) is not funded. \ Add `--allow-unfunded-recipient` to complete the transfer \ - ", - to + " ) .into()); } diff --git a/cli/tests/program.rs b/cli/tests/program.rs index 1caf01625..36d81c6a4 100644 --- a/cli/tests/program.rs +++ b/cli/tests/program.rs @@ -148,7 +148,7 @@ fn test_cli_program_deploy_non_upgradeable() { "Program {} is no longer upgradeable", custom_address_keypair.pubkey() ), - format!("{}", err) + format!("{err}") ); // Attempt to deploy to account with excess balance @@ -178,7 +178,7 @@ fn test_cli_program_deploy_non_upgradeable() { "Account {} is not an upgradeable program or already in use", custom_address_keypair.pubkey() ), - format!("{}", err) + format!("{err}") ); // Use forcing parameter to deploy to account with excess balance diff --git a/client/src/connection_cache.rs b/client/src/connection_cache.rs index 4ea614858..cfc8c2b59 100644 --- a/client/src/connection_cache.rs +++ b/client/src/connection_cache.rs @@ -466,7 +466,7 @@ mod tests { let c = rng.gen_range(1, 255); let d = rng.gen_range(1, 255); - let addr_str = format!("{}.{}.{}.{}:80", a, b, c, d); + let addr_str = format!("{a}.{b}.{c}.{d}:80"); addr_str.parse().expect("Invalid address") } diff --git a/client/src/nonblocking/tpu_client.rs b/client/src/nonblocking/tpu_client.rs index 78cf83fcc..e914a8818 100644 --- a/client/src/nonblocking/tpu_client.rs +++ b/client/src/nonblocking/tpu_client.rs @@ -259,10 +259,7 @@ impl TpuClient { total_transactions, Some(block_height), last_valid_block_height, - &format!( - "Waiting for next block, {} transactions pending...", - num_transactions - ), + &format!("Waiting for next block, {num_transactions} transactions pending..."), ); let mut new_block_height = block_height; while block_height == new_block_height && block_height_refreshes > 0 { @@ -291,10 +288,8 @@ impl TpuClient { if let Some((i, _)) = pending_transactions.remove(signature) { confirmed_transactions += 1; if status.err.is_some() { - progress_bar.println(format!( - "Failed transaction: {:?}", - status - )); + progress_bar + .println(format!("Failed transaction: {status:?}")); } transaction_errors[i] = status.err; } @@ -319,8 +314,7 @@ impl TpuClient { transactions = pending_transactions.into_values().collect(); progress_bar.println(format!( - "Blockhash expired. {} retries remaining", - expired_blockhash_retries + "Blockhash expired. {expired_blockhash_retries} retries remaining" )); expired_blockhash_retries -= 1; } diff --git a/client/src/thin_client.rs b/client/src/thin_client.rs index 3e98ef469..1c38f5f7a 100644 --- a/client/src/thin_client.rs +++ b/client/src/thin_client.rs @@ -169,7 +169,7 @@ impl ThinClient { } Err(io::Error::new( io::ErrorKind::Other, - format!("retry_transfer failed in {} retries", tries), + format!("retry_transfer failed in {tries} retries"), ) .into()) } @@ -377,7 +377,7 @@ impl SyncClient for ThinClient { .map_err(|err| { io::Error::new( io::ErrorKind::Other, - format!("send_transaction failed with error {:?}", err), + format!("send_transaction failed with error {err:?}"), ) })?; Ok(status) @@ -394,7 +394,7 @@ impl SyncClient for ThinClient { .map_err(|err| { io::Error::new( io::ErrorKind::Other, - format!("send_transaction failed with error {:?}", err), + format!("send_transaction failed with error {err:?}"), ) })?; Ok(status) @@ -414,7 +414,7 @@ impl SyncClient for ThinClient { .map_err(|err| { io::Error::new( io::ErrorKind::Other, - format!("send_transaction failed with error {:?}", err), + format!("send_transaction failed with error {err:?}"), ) })?; Ok(slot) diff --git a/core/src/banking_stage.rs b/core/src/banking_stage.rs index 2e1831a34..dd54e279d 100644 --- a/core/src/banking_stage.rs +++ b/core/src/banking_stage.rs @@ -490,7 +490,7 @@ impl BankingStage { let connection_cache = connection_cache.clone(); let bank_forks = bank_forks.clone(); Builder::new() - .name(format!("solBanknStgTx{:02}", i)) + .name(format!("solBanknStgTx{i:02}")) .spawn(move || { Self::process_loop( &mut packet_deserializer, @@ -1151,7 +1151,7 @@ impl BankingStage { starting_transaction_index: None, }; } - Err(e) => panic!("Poh recorder returned unexpected error: {:?}", e), + Err(e) => panic!("Poh recorder returned unexpected error: {e:?}"), } } @@ -3903,7 +3903,7 @@ mod tests { let mut packets = vec![Packet::default(); 2]; let num_received = recv_mmsg(recv_socket, &mut packets[..]).unwrap_or_default(); - assert_eq!(num_received, expected_num_forwarded, "{}", name); + assert_eq!(num_received, expected_num_forwarded, "{name}"); } exit.store(true, Ordering::Relaxed); @@ -4003,7 +4003,7 @@ mod tests { let mut packets = vec![Packet::default(); 2]; let num_received = recv_mmsg(recv_socket, &mut packets[..]).unwrap_or_default(); - assert_eq!(num_received, expected_ids.len(), "{}", name); + assert_eq!(num_received, expected_ids.len(), "{name}"); for (i, expected_id) in expected_ids.iter().enumerate() { assert_eq!(packets[i].meta().size, 215); let recv_transaction: VersionedTransaction = @@ -4011,17 +4011,12 @@ mod tests { assert_eq!( recv_transaction.message.recent_blockhash(), expected_id, - "{}", - name + "{name}" ); } let num_unprocessed_packets: usize = unprocessed_packet_batches.len(); - assert_eq!( - num_unprocessed_packets, expected_num_unprocessed, - "{}", - name - ); + assert_eq!(num_unprocessed_packets, expected_num_unprocessed, "{name}"); } exit.store(true, Ordering::Relaxed); diff --git a/core/src/consensus.rs b/core/src/consensus.rs index 245c9dc07..9fab5402a 100644 --- a/core/src/consensus.rs +++ b/core/src/consensus.rs @@ -292,7 +292,7 @@ impl Tower { "tower_warn", ( "warn", - format!("Unable to get vote_state from account {}", key), + format!("Unable to get vote_state from account {key}"), String ), ); @@ -621,10 +621,7 @@ impl Tower { // non-descendants of the root every time root is set assert!( ancestors.contains(&root_slot), - "ancestors: {:?}, slot: {} root: {}", - ancestors, - slot, - root_slot + "ancestors: {ancestors:?}, slot: {slot} root: {root_slot}" ); } } @@ -681,8 +678,7 @@ impl Tower { // newer snapshots on validator restart let message = format!( "bank_forks doesn't have corresponding data for the stray restored \ - last vote({}), meaning some inconsistency between saved tower and ledger.", - last_voted_slot + last vote({last_voted_slot}), meaning some inconsistency between saved tower and ledger." ); warn!("{}", message); datapoint_warn!("tower_warn", ("warn", message, String)); @@ -771,7 +767,7 @@ impl Tower { // all of them. empty_ancestors_due_to_minor_unsynced_ledger() } else { - panic!("no ancestors found with slot: {}", last_voted_slot); + panic!("no ancestors found with slot: {last_voted_slot}"); } }); @@ -788,10 +784,7 @@ impl Tower { return suspended_decision_due_to_major_unsynced_ledger(); } else { panic!( - "Should never consider switching to ancestor ({}) of last vote: {}, ancestors({:?})", - switch_slot, - last_voted_slot, - last_vote_ancestors, + "Should never consider switching to ancestor ({switch_slot}) of last vote: {last_voted_slot}, ancestors({last_vote_ancestors:?})", ); } } @@ -1106,8 +1099,7 @@ impl Tower { let message = format!( "For some reason, we're REPROCESSING slots which has already been \ voted and ROOTED by us; \ - VOTING will be SUSPENDED UNTIL {}!", - last_voted_slot, + VOTING will be SUSPENDED UNTIL {last_voted_slot}!", ); error!("{}", message); datapoint_error!("tower_error", ("error", message, String)); @@ -1371,9 +1363,8 @@ pub fn reconcile_blockstore_roots_with_external_source( Ordering::Greater => true, Ordering::Equal => false, Ordering::Less => panic!( - "last_blockstore_root({}) is skipped while traversing \ - blockstore (currently at {}) from external root ({:?})!?", - last_blockstore_root, current, external_source, + "last_blockstore_root({last_blockstore_root}) is skipped while traversing \ + blockstore (currently at {current}) from external root ({external_source:?})!?", ), }) .collect(); @@ -2824,7 +2815,7 @@ pub mod test { .write(true) .truncate(true) .open(path) - .unwrap_or_else(|_| panic!("Failed to truncate file: {:?}", path)); + .unwrap_or_else(|_| panic!("Failed to truncate file: {path:?}")); }, ); assert_matches!(loaded, Err(TowerError::SerializeError(_))) diff --git a/core/src/duplicate_repair_status.rs b/core/src/duplicate_repair_status.rs index 8fc0eb6ba..88213107e 100644 --- a/core/src/duplicate_repair_status.rs +++ b/core/src/duplicate_repair_status.rs @@ -695,7 +695,7 @@ pub mod tests { test_setup.correct_ancestors_response ); } - x => panic!("Incorrect decision {:?}", x), + x => panic!("Incorrect decision {x:?}"), }; } @@ -748,7 +748,7 @@ pub mod tests { { repair_status } - x => panic!("Incorrect decision {:?}", x), + x => panic!("Incorrect decision {x:?}"), }; // Expect to find everything after 92 in the `correct_ancestors_to_repair`. @@ -783,7 +783,7 @@ pub mod tests { test_setup.correct_ancestors_response ); } - x => panic!("Incorrect decision {:?}", x), + x => panic!("Incorrect decision {x:?}"), }; } @@ -829,7 +829,7 @@ pub mod tests { expected_mismatched_slots ); } - x => panic!("Incorrect decision {:?}", x), + x => panic!("Incorrect decision {x:?}"), }; } diff --git a/core/src/heaviest_subtree_fork_choice.rs b/core/src/heaviest_subtree_fork_choice.rs index 58e75896f..2b6d61308 100644 --- a/core/src/heaviest_subtree_fork_choice.rs +++ b/core/src/heaviest_subtree_fork_choice.rs @@ -302,7 +302,7 @@ impl HeaviestSubtreeForkChoice { let root_fork_info = self.fork_infos.get_mut(&new_root); root_fork_info - .unwrap_or_else(|| panic!("New root: {:?}, didn't exist in fork choice", new_root)) + .unwrap_or_else(|| panic!("New root: {new_root:?}, didn't exist in fork choice")) .parent = None; self.tree_root = new_root; self.last_root_time = Instant::now(); @@ -929,9 +929,8 @@ impl HeaviestSubtreeForkChoice { // validator has been running, so we must be able to fetch best_slots for all of // them. panic!( - "a bank at last_voted_slot({:?}) is a frozen bank so must have been \ + "a bank at last_voted_slot({last_voted_slot_hash:?}) is a frozen bank so must have been \ added to heaviest_subtree_fork_choice at time of freezing", - last_voted_slot_hash, ) } else { // fork_infos doesn't have corresponding data for the stale stray last vote, diff --git a/core/src/optimistic_confirmation_verifier.rs b/core/src/optimistic_confirmation_verifier.rs index 0b5e6e565..bf63c68b1 100644 --- a/core/src/optimistic_confirmation_verifier.rs +++ b/core/src/optimistic_confirmation_verifier.rs @@ -93,7 +93,7 @@ impl OptimisticConfirmationVerifier { } pub fn format_optimistic_confirmed_slot_violation_log(slot: Slot) -> String { - format!("Optimistically confirmed slot {} was not rooted", slot) + format!("Optimistically confirmed slot {slot} was not rooted") } pub fn log_unrooted_optimistic_slots( diff --git a/core/src/poh_timing_reporter.rs b/core/src/poh_timing_reporter.rs index 76f977386..78b4748a0 100644 --- a/core/src/poh_timing_reporter.rs +++ b/core/src/poh_timing_reporter.rs @@ -234,6 +234,6 @@ mod test { #[test] fn test_slot_poh_timestamp_fmt() { let t = SlotPohTimestamp::default(); - assert_eq!(format!("{}", t), "SlotPohTimestamp: start=0 end=0 full=0"); + assert_eq!(format!("{t}"), "SlotPohTimestamp: start=0 end=0 full=0"); } } diff --git a/core/src/progress_map.rs b/core/src/progress_map.rs index 3077d5e25..bf77a4d53 100644 --- a/core/src/progress_map.rs +++ b/core/src/progress_map.rs @@ -399,7 +399,7 @@ impl ProgressMap { pub fn get_propagated_stats_must_exist(&self, slot: Slot) -> &PropagatedStats { self.get_propagated_stats(slot) - .unwrap_or_else(|| panic!("slot={} must exist in ProgressMap", slot)) + .unwrap_or_else(|| panic!("slot={slot} must exist in ProgressMap")) } pub fn get_fork_stats(&self, slot: Slot) -> Option<&ForkStats> { diff --git a/core/src/repair_generic_traversal.rs b/core/src/repair_generic_traversal.rs index 13691ff06..225a5ea6a 100644 --- a/core/src/repair_generic_traversal.rs +++ b/core/src/repair_generic_traversal.rs @@ -138,8 +138,7 @@ pub fn get_closest_completion( ( "error", format!( - "last_index + 1 < shred_count. last_index={} shred_count={}", - last_index, shred_count, + "last_index + 1 < shred_count. last_index={last_index} shred_count={shred_count}", ), String ), diff --git a/core/src/replay_stage.rs b/core/src/replay_stage.rs index bd1adf9f6..a446837dc 100644 --- a/core/src/replay_stage.rs +++ b/core/src/replay_stage.rs @@ -99,7 +99,7 @@ const MAX_REPAIR_RETRY_LOOP_ATTEMPTS: usize = 10; lazy_static! { static ref PAR_THREAD_POOL: ThreadPool = rayon::ThreadPoolBuilder::new() .num_threads(MAX_CONCURRENT_FORKS_TO_REPLAY) - .thread_name(|ix| format!("solReplay{:02}", ix)) + .thread_name(|ix| format!("solReplay{ix:02}")) .build() .unwrap(); } @@ -1796,13 +1796,13 @@ impl ReplayStage { if is_serious { datapoint_error!( "replay-stage-mark_dead_slot", - ("error", format!("error: {:?}", err), String), + ("error", format!("error: {err:?}"), String), ("slot", slot, i64) ); } else { datapoint_info!( "replay-stage-mark_dead_slot", - ("error", format!("error: {:?}", err), String), + ("error", format!("error: {err:?}"), String), ("slot", slot, i64) ); } @@ -1815,7 +1815,7 @@ impl ReplayStage { rpc_subscriptions.notify_slot_update(SlotUpdate::Dead { slot, - err: format!("error: {:?}", err), + err: format!("error: {err:?}"), timestamp: timestamp(), }); let dead_state = DeadState::new_from_state( @@ -2134,7 +2134,7 @@ impl ReplayStage { tower.refresh_last_vote_tx_blockhash(recent_blockhash); // Send the votes to the TPU and gossip for network propagation - let hash_string = format!("{}", recent_blockhash); + let hash_string = format!("{recent_blockhash}"); datapoint_info!( "refresh_vote", ("last_voted_slot", last_voted_slot, i64), @@ -2894,7 +2894,7 @@ impl ReplayStage { // Otherwise we have to check the votes for confirmation let mut propagated_stats = progress .get_propagated_stats_mut(slot) - .unwrap_or_else(|| panic!("slot={} must exist in ProgressMap", slot)); + .unwrap_or_else(|| panic!("slot={slot} must exist in ProgressMap")); if propagated_stats.slot_vote_tracker.is_none() { propagated_stats.slot_vote_tracker = vote_tracker.get_slot_vote_tracker(slot); diff --git a/core/src/retransmit_stage.rs b/core/src/retransmit_stage.rs index 3a3be3d0c..b8ea2356b 100644 --- a/core/src/retransmit_stage.rs +++ b/core/src/retransmit_stage.rs @@ -364,7 +364,7 @@ pub fn retransmitter( let num_threads = get_thread_count().min(8).max(sockets.len()); let thread_pool = ThreadPoolBuilder::new() .num_threads(num_threads) - .thread_name(|i| format!("solRetransmit{:02}", i)) + .thread_name(|i| format!("solRetransmit{i:02}")) .build() .unwrap(); Builder::new() diff --git a/core/src/snapshot_packager_service.rs b/core/src/snapshot_packager_service.rs index 5fc51b9ff..050b9d73e 100644 --- a/core/src/snapshot_packager_service.rs +++ b/core/src/snapshot_packager_service.rs @@ -243,7 +243,7 @@ mod tests { // Create temporary placeholder directory for all test files fn make_tmp_dir_path() -> PathBuf { let out_dir = std::env::var("FARF_DIR").unwrap_or_else(|_| "farf".to_string()); - let path = PathBuf::from(format!("{}/tmp/test_package_snapshots", out_dir)); + let path = PathBuf::from(format!("{out_dir}/tmp/test_package_snapshots")); // whack any possible collision let _ignored = std::fs::remove_dir_all(&path); @@ -282,7 +282,7 @@ mod tests { // Create some fake snapshot let snapshots_paths: Vec<_> = (0..5) .map(|i| { - let snapshot_file_name = format!("{}", i); + let snapshot_file_name = format!("{i}"); let snapshots_dir = snapshots_dir.join(&snapshot_file_name); fs::create_dir_all(&snapshots_dir).unwrap(); let fake_snapshot_path = snapshots_dir.join(&snapshot_file_name); diff --git a/core/src/tower_storage.rs b/core/src/tower_storage.rs index 42ffc7c72..5841a1a48 100644 --- a/core/src/tower_storage.rs +++ b/core/src/tower_storage.rs @@ -138,13 +138,13 @@ impl FileTowerStorage { // Old filename for towers pre 1.9 (VoteStateUpdate) pub fn old_filename(&self, node_pubkey: &Pubkey) -> PathBuf { self.tower_path - .join(format!("tower-{}", node_pubkey)) + .join(format!("tower-{node_pubkey}")) .with_extension("bin") } pub fn filename(&self, node_pubkey: &Pubkey) -> PathBuf { self.tower_path - .join(format!("tower-1_9-{}", node_pubkey)) + .join(format!("tower-1_9-{node_pubkey}")) .with_extension("bin") } @@ -266,8 +266,8 @@ impl EtcdTowerStorage { } fn get_keys(node_pubkey: &Pubkey) -> (String, String) { - let instance_key = format!("{}/instance", node_pubkey); - let tower_key = format!("{}/tower", node_pubkey); + let instance_key = format!("{node_pubkey}/instance"); + let tower_key = format!("{node_pubkey}/tower"); (instance_key, tower_key) } @@ -311,7 +311,7 @@ impl TowerStorage for EtcdTowerStorage { if !response.succeeded() { return Err(TowerError::IoError(io::Error::new( io::ErrorKind::Other, - format!("Lost etcd instance lock for {}", node_pubkey), + format!("Lost etcd instance lock for {node_pubkey}"), ))); } diff --git a/core/src/validator.rs b/core/src/validator.rs index 5bbd61a7f..6a025846a 100644 --- a/core/src/validator.rs +++ b/core/src/validator.rs @@ -392,8 +392,7 @@ impl Validator { if !config.no_os_network_stats_reporting { if let Err(e) = verify_net_stats_access() { return Err(format!( - "Failed to access Network stats: {}. Bypass check with --no-os-network-stats-reporting.", - e, + "Failed to access Network stats: {e}. Bypass check with --no-os-network-stats-reporting.", )); } } @@ -409,7 +408,7 @@ impl Validator { match result { Ok(geyser_plugin_service) => Some(geyser_plugin_service), Err(err) => { - return Err(format!("Failed to load the Geyser plugin: {:?}", err)); + return Err(format!("Failed to load the Geyser plugin: {err:?}")); } } } else { @@ -430,7 +429,7 @@ impl Validator { } if rayon::ThreadPoolBuilder::new() - .thread_name(|ix| format!("solRayonGlob{:02}", ix)) + .thread_name(|ix| format!("solRayonGlob{ix:02}")) .build_global() .is_err() { @@ -447,8 +446,7 @@ impl Validator { if !ledger_path.is_dir() { return Err(format!( - "ledger directory does not exist or is not accessible: {:?}", - ledger_path + "ledger directory does not exist or is not accessible: {ledger_path:?}" )); } @@ -903,7 +901,7 @@ impl Validator { &start_progress, ) { Ok(waited) => waited, - Err(e) => return Err(format!("wait_for_supermajority failed: {:?}", e)), + Err(e) => return Err(format!("wait_for_supermajority failed: {e:?}")), }; let ledger_metric_report_service = @@ -1232,9 +1230,8 @@ fn check_poh_speed( info!("PoH speed check: Will sleep {}ns per slot.", extra_ns); } else { return Err(format!( - "PoH is slower than cluster target tick rate! mine: {} cluster: {}. \ + "PoH is slower than cluster target tick rate! mine: {my_ns_per_slot} cluster: {target_ns_per_slot}. \ If you wish to continue, try --no-poh-speed-test", - my_ns_per_slot, target_ns_per_slot, )); } } @@ -1273,10 +1270,8 @@ fn post_process_restored_tower( // intentionally fail to restore tower; we're supposedly in a new hard fork; past // out-of-chain vote state doesn't make sense at all // what if --wait-for-supermajority again if the validator restarted? - let message = format!( - "Hard fork is detected; discarding tower restoration result: {:?}", - tower - ); + let message = + format!("Hard fork is detected; discarding tower restoration result: {tower:?}"); datapoint_error!("tower_error", ("error", message, String),); error!("{}", message); @@ -1306,15 +1301,14 @@ fn post_process_restored_tower( if !err.is_file_missing() { datapoint_error!( "tower_error", - ("error", format!("Unable to restore tower: {}", err), String), + ("error", format!("Unable to restore tower: {err}"), String), ); } if should_require_tower && voting_has_been_active { return Err(format!( - "Requested mandatory tower restore failed: {}. \ + "Requested mandatory tower restore failed: {err}. \ And there is an existing vote_account containing actual votes. \ - Aborting due to possible conflicting duplicate votes", - err + Aborting due to possible conflicting duplicate votes" )); } if err.is_file_missing() && !voting_has_been_active { @@ -1380,10 +1374,7 @@ fn load_blockstore( if let Some(expected_genesis_hash) = config.expected_genesis_hash { if genesis_hash != expected_genesis_hash { return Err(format!( - "genesis hash mismatch: hash={} expected={}. Delete the ledger directory to continue: {:?}", - genesis_hash, - expected_genesis_hash, - ledger_path, + "genesis hash mismatch: hash={genesis_hash} expected={expected_genesis_hash}. Delete the ledger directory to continue: {ledger_path:?}", )); } } @@ -1599,7 +1590,7 @@ impl<'a> ProcessBlockStore<'a> { self.cache_block_meta_sender.as_ref(), &self.accounts_background_request_sender, ) { - return Err(format!("Failed to load ledger: {:?}", e)); + return Err(format!("Failed to load ledger: {e:?}")); } exit.store(true, Ordering::Relaxed); @@ -1617,10 +1608,7 @@ impl<'a> ProcessBlockStore<'a> { self.blockstore, &mut self.original_blockstore_root, ) { - return Err(format!( - "Failed to reconcile blockstore with tower: {:?}", - e - )); + return Err(format!("Failed to reconcile blockstore with tower: {e:?}")); } } @@ -1645,8 +1633,7 @@ impl<'a> ProcessBlockStore<'a> { &mut self.original_blockstore_root, ) { return Err(format!( - "Failed to reconcile blockstore with hard fork: {:?}", - e + "Failed to reconcile blockstore with hard fork: {e:?}" )); } } @@ -1715,7 +1702,7 @@ fn maybe_warp_slot( snapshot_config.maximum_incremental_snapshot_archives_to_retain, ) { Ok(archive_info) => archive_info, - Err(e) => return Err(format!("Unable to create snapshot: {}", e)), + Err(e) => return Err(format!("Unable to create snapshot: {e}")), }; info!( "created snapshot: {}", diff --git a/core/src/window_service.rs b/core/src/window_service.rs index 8ca1861cb..328552997 100644 --- a/core/src/window_service.rs +++ b/core/src/window_service.rs @@ -405,7 +405,7 @@ impl WindowService { }; let thread_pool = rayon::ThreadPoolBuilder::new() .num_threads(get_thread_count().min(8)) - .thread_name(|i| format!("solWinInsert{:02}", i)) + .thread_name(|i| format!("solWinInsert{i:02}")) .build() .unwrap(); let reed_solomon_cache = ReedSolomonCache::default(); diff --git a/core/tests/ledger_cleanup.rs b/core/tests/ledger_cleanup.rs index 20e6a1a61..bad78c6ad 100644 --- a/core/tests/ledger_cleanup.rs +++ b/core/tests/ledger_cleanup.rs @@ -439,7 +439,7 @@ mod tests { let shared_batch_id = current_batch_id.clone(); let shared_finished_count = finished_batch_count.clone(); let insert_thread = Builder::new() - .name(format!("insert_shreds-{}", i)) + .name(format!("insert_shreds-{i}")) .spawn(move || { let start = Instant::now(); let mut now = Instant::now(); diff --git a/core/tests/snapshots.rs b/core/tests/snapshots.rs index cfc820f7f..6151748d6 100644 --- a/core/tests/snapshots.rs +++ b/core/tests/snapshots.rs @@ -1094,9 +1094,7 @@ fn test_snapshots_with_background_services( { assert!( timer.elapsed() < MAX_WAIT_DURATION, - "Waiting for full snapshot {} exceeded the {:?} maximum wait duration!", - slot, - MAX_WAIT_DURATION, + "Waiting for full snapshot {slot} exceeded the {MAX_WAIT_DURATION:?} maximum wait duration!", ); std::thread::sleep(Duration::from_secs(1)); } @@ -1114,9 +1112,7 @@ fn test_snapshots_with_background_services( { assert!( timer.elapsed() < MAX_WAIT_DURATION, - "Waiting for incremental snapshot {} exceeded the {:?} maximum wait duration!", - slot, - MAX_WAIT_DURATION, + "Waiting for incremental snapshot {slot} exceeded the {MAX_WAIT_DURATION:?} maximum wait duration!", ); std::thread::sleep(Duration::from_secs(1)); } diff --git a/dos/src/main.rs b/dos/src/main.rs index 1409e90e3..72fd88a7f 100644 --- a/dos/src/main.rs +++ b/dos/src/main.rs @@ -538,7 +538,7 @@ fn create_payers( let res = generate_and_fund_keypairs(client.unwrap().clone(), &funding_key, size, 1_000_000) .unwrap_or_else(|e| { - eprintln!("Error could not fund keys: {:?}", e); + eprintln!("Error could not fund keys: {e:?}"); exit(1); }); res.into_iter().map(Some).collect() @@ -591,11 +591,11 @@ fn run_dos_transactions( }) .collect(); if let Err(err) = sender_thread.join() { - println!("join() failed with: {:?}", err); + println!("join() failed with: {err:?}"); } for t_generator in tx_generator_threads { if let Err(err) = t_generator.join() { - println!("join() failed with: {:?}", err); + println!("join() failed with: {err:?}"); } } } diff --git a/download-utils/src/lib.rs b/download-utils/src/lib.rs index 411b21e43..7f0e1fe14 100644 --- a/download-utils/src/lib.rs +++ b/download-utils/src/lib.rs @@ -69,7 +69,7 @@ pub fn download_file<'a, 'b>( progress_notify_callback: &'a mut DownloadProgressCallbackOption<'b>, ) -> Result<(), String> { if destination_file.is_file() { - return Err(format!("{:?} already exists", destination_file)); + return Err(format!("{destination_file:?} already exists")); } let download_start = Instant::now(); @@ -88,7 +88,7 @@ pub fn download_file<'a, 'b>( let progress_bar = new_spinner_progress_bar(); if use_progress_bar { - progress_bar.set_message(format!("{}Downloading {}...", TRUCK, url)); + progress_bar.set_message(format!("{TRUCK}Downloading {url}...")); } let response = reqwest::blocking::Client::new() @@ -119,7 +119,7 @@ pub fn download_file<'a, 'b>( .expect("ProgresStyle::template direct input to be correct") .progress_chars("=> "), ); - progress_bar.set_message(format!("{}Downloading~ {}", TRUCK, url)); + progress_bar.set_message(format!("{TRUCK}Downloading~ {url}")); } else { info!("Downloading {} bytes from {}", download_size, url); } @@ -212,7 +212,7 @@ pub fn download_file<'a, 'b>( File::create(&temp_destination_file) .and_then(|mut file| std::io::copy(&mut source, &mut file)) - .map_err(|err| format!("Unable to write {:?}: {:?}", temp_destination_file, err))?; + .map_err(|err| format!("Unable to write {temp_destination_file:?}: {err:?}"))?; source.progress_bar.finish_and_clear(); info!( @@ -227,7 +227,7 @@ pub fn download_file<'a, 'b>( ); std::fs::rename(temp_destination_file, destination_file) - .map_err(|err| format!("Unable to rename: {:?}", err))?; + .map_err(|err| format!("Unable to rename: {err:?}"))?; Ok(()) } @@ -243,7 +243,7 @@ pub fn download_genesis_if_missing( let _ignored = fs::remove_dir_all(&tmp_genesis_path); download_file( - &format!("http://{}/{}", rpc_addr, DEFAULT_GENESIS_ARCHIVE), + &format!("http://{rpc_addr}/{DEFAULT_GENESIS_ARCHIVE}"), &tmp_genesis_package, use_progress_bar, &mut None, diff --git a/entry/src/entry.rs b/entry/src/entry.rs index 9f8bb2e81..e7ba1d9d4 100644 --- a/entry/src/entry.rs +++ b/entry/src/entry.rs @@ -46,7 +46,7 @@ use { lazy_static! { static ref PAR_THREAD_POOL: ThreadPool = rayon::ThreadPoolBuilder::new() .num_threads(get_max_thread_count()) - .thread_name(|ix| format!("solEntry{:02}", ix)) + .thread_name(|ix| format!("solEntry{ix:02}")) .build() .unwrap(); } @@ -678,7 +678,7 @@ impl EntrySlice for [Entry] { ); }, _ => { - panic!("unsupported simd len: {}", simd_len); + panic!("unsupported simd len: {simd_len}"); } } let entry_start = i * simd_len; diff --git a/faucet/src/faucet.rs b/faucet/src/faucet.rs index d440d34ff..e23f1142c 100644 --- a/faucet/src/faucet.rs +++ b/faucet/src/faucet.rs @@ -367,8 +367,7 @@ pub async fn run_faucet( listener.as_ref().map(|listener| listener.local_addr().unwrap()) .map_err(|err| { format!( - "Unable to bind faucet to {:?}, check the address is not already in use: {}", - faucet_addr, err + "Unable to bind faucet to {faucet_addr:?}, check the address is not already in use: {err}" ) }) ) diff --git a/frozen-abi/macro/src/lib.rs b/frozen-abi/macro/src/lib.rs index b2040b781..8132a06dd 100644 --- a/frozen-abi/macro/src/lib.rs +++ b/frozen-abi/macro/src/lib.rs @@ -236,7 +236,7 @@ fn do_derive_abi_enum_visitor(input: ItemEnum) -> TokenStream { }); } - let type_str = format!("{}", type_name); + let type_str = format!("{type_name}"); (quote! { impl #impl_generics ::solana_frozen_abi::abi_example::AbiEnumVisitor for #type_name #ty_generics #where_clause { fn visit_for_abi(&self, digester: &mut ::solana_frozen_abi::abi_digester::AbiDigester) -> ::solana_frozen_abi::abi_digester::DigestResult { @@ -310,7 +310,7 @@ fn quote_for_test( #[cfg(RUSTC_WITH_SPECIALIZATION)] fn test_mod_name(type_name: &Ident) -> Ident { - Ident::new(&format!("{}_frozen_abi", type_name), Span::call_site()) + Ident::new(&format!("{type_name}_frozen_abi"), Span::call_site()) } #[cfg(RUSTC_WITH_SPECIALIZATION)] diff --git a/frozen-abi/src/abi_digester.rs b/frozen-abi/src/abi_digester.rs index 66047f2fe..263bf60ee 100644 --- a/frozen-abi/src/abi_digester.rs +++ b/frozen-abi/src/abi_digester.rs @@ -180,7 +180,7 @@ impl AbiDigester { v: &T, ) -> Result<(), DigestError> { let field_type_name = shorten_serialize_with(type_name::()); - self.update_with_string(format!("field {}: {}", key, field_type_name)); + self.update_with_string(format!("field {key}: {field_type_name}")); self.create_child()? .digest_data(v) .map(|_| ()) @@ -198,7 +198,7 @@ impl AbiDigester { label: &'static str, variant: &'static str, ) -> Result<(), DigestError> { - assert!(self.for_enum, "derive AbiEnumVisitor or implement it for the enum, which contains a variant ({}) named {}", label, variant); + assert!(self.for_enum, "derive AbiEnumVisitor or implement it for the enum, which contains a variant ({label}) named {variant}"); Ok(()) } @@ -220,7 +220,7 @@ impl AbiDigester { error!("Bad thread name detected for dumping; Maybe, --test-threads=1? Sorry, SOLANA_ABI_DUMP_DIR doesn't work under 1; increase it"); } - let path = format!("{}/{}_{}", dir, thread_name, hash,); + let path = format!("{dir}/{thread_name}_{hash}",); let mut file = std::fs::File::create(path).unwrap(); for buf in (*self.data_types.borrow()).iter() { file.write_all(buf.as_bytes()).unwrap(); @@ -337,7 +337,7 @@ impl Serializer for AbiDigester { fn serialize_unit_variant(mut self, _name: Sstr, index: u32, variant: Sstr) -> DigestResult { self.check_for_enum("unit_variant", variant)?; - self.update_with_string(format!("variant({}) {} (unit)", index, variant)); + self.update_with_string(format!("variant({index}) {variant} (unit)")); Ok(self) } @@ -379,17 +379,17 @@ impl Serializer for AbiDigester { len, 1, "Exactly 1 seq element is needed to generate the ABI digest precisely" ); - self.update_with_string(format!("seq (elements = {})", len)); + self.update_with_string(format!("seq (elements = {len})")); self.create_child() } fn serialize_tuple(mut self, len: usize) -> DigestResult { - self.update_with_string(format!("tuple (elements = {})", len)); + self.update_with_string(format!("tuple (elements = {len})")); self.create_child() } fn serialize_tuple_struct(mut self, name: Sstr, len: usize) -> DigestResult { - self.update_with_string(format!("struct {} (fields = {}) (tuple)", name, len)); + self.update_with_string(format!("struct {name} (fields = {len}) (tuple)")); self.create_child() } @@ -401,7 +401,7 @@ impl Serializer for AbiDigester { len: usize, ) -> DigestResult { self.check_for_enum("tuple_variant", variant)?; - self.update_with_string(format!("variant({}) {} (fields = {})", i, variant, len)); + self.update_with_string(format!("variant({i}) {variant} (fields = {len})")); self.create_child() } @@ -411,12 +411,12 @@ impl Serializer for AbiDigester { len, 1, "Exactly 1 map entry is needed to generate the ABI digest precisely" ); - self.update_with_string(format!("map (entries = {})", len)); + self.update_with_string(format!("map (entries = {len})")); self.create_child() } fn serialize_struct(mut self, name: Sstr, len: usize) -> DigestResult { - self.update_with_string(format!("struct {} (fields = {})", name, len)); + self.update_with_string(format!("struct {name} (fields = {len})")); self.create_child() } @@ -428,10 +428,7 @@ impl Serializer for AbiDigester { len: usize, ) -> DigestResult { self.check_for_enum("struct_variant", variant)?; - self.update_with_string(format!( - "variant({}) struct {} (fields = {})", - i, variant, len - )); + self.update_with_string(format!("variant({i}) struct {variant} (fields = {len})")); self.create_child() } } diff --git a/frozen-abi/src/abi_example.rs b/frozen-abi/src/abi_example.rs index 2e1bdbcac..b9d41a6b7 100644 --- a/frozen-abi/src/abi_example.rs +++ b/frozen-abi/src/abi_example.rs @@ -266,15 +266,9 @@ impl TypeErasedExample for Placeholder { let normalized_type_name = normalize_type_name(original_type_name); if normalized_type_name.starts_with("solana") { - panic!( - "derive or implement AbiExample/AbiEnumVisitor for {}", - original_type_name - ); + panic!("derive or implement AbiExample/AbiEnumVisitor for {original_type_name}"); } else { - panic!( - "new unrecognized type for ABI digest!: {}", - original_type_name - ) + panic!("new unrecognized type for ABI digest!: {original_type_name}") } } } diff --git a/genesis-utils/src/lib.rs b/genesis-utils/src/lib.rs index 6af1981aa..7aa151201 100644 --- a/genesis-utils/src/lib.rs +++ b/genesis-utils/src/lib.rs @@ -17,8 +17,7 @@ fn check_genesis_hash( if let Some(expected_genesis_hash) = expected_genesis_hash { if expected_genesis_hash != genesis_hash { return Err(format!( - "Genesis hash mismatch: expected {} but downloaded genesis hash is {}", - expected_genesis_hash, genesis_hash, + "Genesis hash mismatch: expected {expected_genesis_hash} but downloaded genesis hash is {genesis_hash}", )); } } @@ -31,7 +30,7 @@ fn load_local_genesis( expected_genesis_hash: Option, ) -> Result { let existing_genesis = GenesisConfig::load(ledger_path) - .map_err(|err| format!("Failed to load genesis config: {}", err))?; + .map_err(|err| format!("Failed to load genesis config: {err}"))?; check_genesis_hash(&existing_genesis, expected_genesis_hash)?; Ok(existing_genesis) @@ -59,14 +58,14 @@ pub fn download_then_check_genesis_hash( ledger_path, max_genesis_archive_unpacked_size, ) - .map_err(|err| format!("Failed to unpack downloaded genesis config: {}", err))?; + .map_err(|err| format!("Failed to unpack downloaded genesis config: {err}"))?; let downloaded_genesis = GenesisConfig::load(ledger_path) - .map_err(|err| format!("Failed to load downloaded genesis config: {}", err))?; + .map_err(|err| format!("Failed to load downloaded genesis config: {err}"))?; check_genesis_hash(&downloaded_genesis, expected_genesis_hash)?; std::fs::rename(tmp_genesis_package, genesis_package) - .map_err(|err| format!("Unable to rename: {:?}", err))?; + .map_err(|err| format!("Unable to rename: {err:?}"))?; downloaded_genesis } else { diff --git a/genesis/src/address_generator.rs b/genesis/src/address_generator.rs index afea1f616..ad12d3d85 100644 --- a/genesis/src/address_generator.rs +++ b/genesis/src/address_generator.rs @@ -17,7 +17,7 @@ impl AddressGenerator { } pub fn nth(&self, nth: usize) -> Pubkey { - Pubkey::create_with_seed(&self.base_pubkey, &format!("{}", nth), &self.program_id).unwrap() + Pubkey::create_with_seed(&self.base_pubkey, &format!("{nth}"), &self.program_id).unwrap() } #[allow(clippy::should_implement_trait)] diff --git a/genesis/src/main.rs b/genesis/src/main.rs index d1f8e2a35..6338a35e2 100644 --- a/genesis/src/main.rs +++ b/genesis/src/main.rs @@ -64,13 +64,13 @@ pub fn load_genesis_accounts(file: &str, genesis_config: &mut GenesisConfig) -> let genesis_accounts: HashMap = serde_yaml::from_reader(accounts_file) - .map_err(|err| io::Error::new(io::ErrorKind::Other, format!("{:?}", err)))?; + .map_err(|err| io::Error::new(io::ErrorKind::Other, format!("{err:?}")))?; for (key, account_details) in genesis_accounts { let pubkey = pubkey_from_str(key.as_str()).map_err(|err| { io::Error::new( io::ErrorKind::Other, - format!("Invalid pubkey/keypair {}: {:?}", key, err), + format!("Invalid pubkey/keypair {key}: {err:?}"), ) })?; @@ -401,8 +401,7 @@ fn main() -> Result<(), Box> { Err(io::Error::new( io::ErrorKind::Other, format!( - "error: insufficient {}: {} for rent exemption, requires {}", - name, lamports, exempt + "error: insufficient {name}: {lamports} for rent exemption, requires {exempt}" ), )) } else { @@ -592,12 +591,12 @@ fn main() -> Result<(), Box> { match address_loader_program { [address, loader, program] => { let address = address.parse::().unwrap_or_else(|err| { - eprintln!("Error: invalid address {}: {}", address, err); + eprintln!("Error: invalid address {address}: {err}"); process::exit(1); }); let loader = loader.parse::().unwrap_or_else(|err| { - eprintln!("Error: invalid loader {}: {}", loader, err); + eprintln!("Error: invalid loader {loader}: {err}"); process::exit(1); }); @@ -605,7 +604,7 @@ fn main() -> Result<(), Box> { File::open(program) .and_then(|mut file| file.read_to_end(&mut program_data)) .unwrap_or_else(|err| { - eprintln!("Error: failed to read {}: {}", program, err); + eprintln!("Error: failed to read {program}: {err}"); process::exit(1); }); genesis_config.add_account( @@ -632,7 +631,7 @@ fn main() -> Result<(), Box> { LedgerColumnOptions::default(), )?; - println!("{}", genesis_config); + println!("{genesis_config}"); Ok(()) } diff --git a/geyser-plugin-manager/src/geyser_plugin_service.rs b/geyser-plugin-manager/src/geyser_plugin_service.rs index e203bd1de..5112b9a10 100644 --- a/geyser-plugin-manager/src/geyser_plugin_service.rs +++ b/geyser-plugin-manager/src/geyser_plugin_service.rs @@ -140,8 +140,7 @@ impl GeyserPluginService { Ok(file) => file, Err(err) => { return Err(GeyserPluginServiceError::CannotOpenConfigFile(format!( - "Failed to open the plugin config file {:?}, error: {:?}", - geyser_plugin_config_file, err + "Failed to open the plugin config file {geyser_plugin_config_file:?}, error: {err:?}" ))); } }; @@ -149,8 +148,7 @@ impl GeyserPluginService { let mut contents = String::new(); if let Err(err) = file.read_to_string(&mut contents) { return Err(GeyserPluginServiceError::CannotReadConfigFile(format!( - "Failed to read the plugin config file {:?}, error: {:?}", - geyser_plugin_config_file, err + "Failed to read the plugin config file {geyser_plugin_config_file:?}, error: {err:?}" ))); } @@ -158,8 +156,7 @@ impl GeyserPluginService { Ok(value) => value, Err(err) => { return Err(GeyserPluginServiceError::InvalidConfigFileFormat(format!( - "The config file {:?} is not in a valid Json5 format, error: {:?}", - geyser_plugin_config_file, err + "The config file {geyser_plugin_config_file:?} is not in a valid Json5 format, error: {err:?}" ))); } }; @@ -171,8 +168,7 @@ impl GeyserPluginService { if libpath.is_relative() { let config_dir = geyser_plugin_config_file.parent().ok_or_else(|| { GeyserPluginServiceError::CannotOpenConfigFile(format!( - "Failed to resolve parent of {:?}", - geyser_plugin_config_file, + "Failed to resolve parent of {geyser_plugin_config_file:?}", )) })?; libpath = config_dir.join(libpath); @@ -186,10 +182,7 @@ impl GeyserPluginService { unsafe { let result = plugin_manager.load_plugin(libpath.to_str().unwrap(), config_file); if let Err(err) = result { - let msg = format!( - "Failed to load the plugin library: {:?}, error: {:?}", - libpath, err - ); + let msg = format!("Failed to load the plugin library: {libpath:?}, error: {err:?}"); return Err(GeyserPluginServiceError::PluginLoadError(msg)); } } diff --git a/gossip/src/cluster_info.rs b/gossip/src/cluster_info.rs index d0aaf2e80..d0c6d64ef 100644 --- a/gossip/src/cluster_info.rs +++ b/gossip/src/cluster_info.rs @@ -844,15 +844,12 @@ impl ClusterInfo { nodes.join(""), nodes.len().saturating_sub(shred_spy_nodes), if total_spy_nodes > 0 { - format!("\nSpies: {}", total_spy_nodes) + format!("\nSpies: {total_spy_nodes}") } else { "".to_string() }, if different_shred_nodes > 0 { - format!( - "\nNodes with different shred version: {}", - different_shred_nodes - ) + format!("\nNodes with different shred version: {different_shred_nodes}") } else { "".to_string() } @@ -1714,7 +1711,7 @@ impl ClusterInfo { ) -> JoinHandle<()> { let thread_pool = ThreadPoolBuilder::new() .num_threads(std::cmp::min(get_thread_count(), 8)) - .thread_name(|i| format!("solRunGossip{:02}", i)) + .thread_name(|i| format!("solRunGossip{i:02}")) .build() .unwrap(); Builder::new() @@ -2620,7 +2617,7 @@ impl ClusterInfo { ) -> JoinHandle<()> { let thread_pool = ThreadPoolBuilder::new() .num_threads(get_thread_count().min(8)) - .thread_name(|i| format!("solGossipCons{:02}", i)) + .thread_name(|i| format!("solGossipCons{i:02}")) .build() .unwrap(); let run_consume = move || { @@ -2652,7 +2649,7 @@ impl ClusterInfo { let recycler = PacketBatchRecycler::default(); let thread_pool = ThreadPoolBuilder::new() .num_threads(get_thread_count().min(8)) - .thread_name(|i| format!("solGossipWork{:02}", i)) + .thread_name(|i| format!("solGossipWork{i:02}")) .build() .unwrap(); Builder::new() @@ -3568,8 +3565,7 @@ RPC Enabled Nodes: 1"#; let size = serialized_size(&pull_response).unwrap(); assert!( PULL_RESPONSE_MIN_SERIALIZED_SIZE as u64 <= size, - "pull-response serialized size: {}", - size + "pull-response serialized size: {size}" ); } } diff --git a/gossip/src/crds.rs b/gossip/src/crds.rs index 2c215c928..14d7d57aa 100644 --- a/gossip/src/crds.rs +++ b/gossip/src/crds.rs @@ -1129,13 +1129,9 @@ mod tests { assert!(num_inserts > crds.table.len()); let (num_nodes, num_votes, num_epoch_slots) = check_crds_value_indices(&mut rng, &crds); assert!(num_nodes * 3 < crds.table.len()); - assert!(num_nodes > 100, "num nodes: {}", num_nodes); - assert!(num_votes > 100, "num votes: {}", num_votes); - assert!( - num_epoch_slots > 100, - "num epoch slots: {}", - num_epoch_slots - ); + assert!(num_nodes > 100, "num nodes: {num_nodes}"); + assert!(num_votes > 100, "num votes: {num_votes}"); + assert!(num_epoch_slots > 100, "num epoch slots: {num_epoch_slots}"); // Remove values one by one and assert that nodes indices stay valid. while !crds.table.is_empty() { let index = rng.gen_range(0, crds.table.len()); diff --git a/gossip/src/crds_gossip_pull.rs b/gossip/src/crds_gossip_pull.rs index 6fd0b8eee..b6cf917f5 100644 --- a/gossip/src/crds_gossip_pull.rs +++ b/gossip/src/crds_gossip_pull.rs @@ -968,7 +968,7 @@ pub(crate) mod tests { } } let crds = RwLock::new(crds); - assert!(num_inserts > 30_000, "num inserts: {}", num_inserts); + assert!(num_inserts > 30_000, "num inserts: {num_inserts}"); let filters = crds_gossip_pull.build_crds_filters(&thread_pool, &crds, MAX_BLOOM_SIZE); assert_eq!(filters.len(), MIN_NUM_BLOOM_FILTERS.max(32)); let crds = crds.read().unwrap(); @@ -995,7 +995,7 @@ pub(crate) mod tests { } assert_eq!(num_hits, 1); } - assert!(false_positives < 150_000, "fp: {}", false_positives); + assert!(false_positives < 150_000, "fp: {false_positives}"); } #[test] @@ -1164,7 +1164,7 @@ pub(crate) mod tests { .take(100) .filter(|peer| peer != old) .count(); - assert!(count < 2, "count of peer != old: {}", count); + assert!(count < 2, "count of peer != old: {count}"); } #[test] diff --git a/gossip/src/crds_value.rs b/gossip/src/crds_value.rs index cbee1542f..9d1fe6e14 100644 --- a/gossip/src/crds_value.rs +++ b/gossip/src/crds_value.rs @@ -504,8 +504,8 @@ impl fmt::Display for CrdsValueLabel { CrdsValueLabel::AccountsHashes(_) => write!(f, "AccountsHashes({})", self.pubkey()), CrdsValueLabel::LegacyVersion(_) => write!(f, "LegacyVersion({})", self.pubkey()), CrdsValueLabel::Version(_) => write!(f, "Version({})", self.pubkey()), - CrdsValueLabel::NodeInstance(pk) => write!(f, "NodeInstance({})", pk), - CrdsValueLabel::DuplicateShred(ix, pk) => write!(f, "DuplicateShred({}, {})", ix, pk), + CrdsValueLabel::NodeInstance(pk) => write!(f, "NodeInstance({pk})"), + CrdsValueLabel::DuplicateShred(ix, pk) => write!(f, "DuplicateShred({ix}, {pk})"), CrdsValueLabel::IncrementalSnapshotHashes(_) => { write!(f, "IncrementalSnapshotHashes({})", self.pubkey()) } diff --git a/gossip/src/main.rs b/gossip/src/main.rs index f2bb071b2..0be8acfa4 100644 --- a/gossip/src/main.rs +++ b/gossip/src/main.rs @@ -158,17 +158,14 @@ fn parse_gossip_host(matches: &ArgMatches, entrypoint_addr: Option) .value_of("gossip_host") .map(|gossip_host| { solana_net_utils::parse_host(gossip_host).unwrap_or_else(|e| { - eprintln!("failed to parse gossip-host: {}", e); + eprintln!("failed to parse gossip-host: {e}"); exit(1); }) }) .unwrap_or_else(|| { if let Some(entrypoint_addr) = entrypoint_addr { solana_net_utils::get_public_ip_addr(&entrypoint_addr).unwrap_or_else(|err| { - eprintln!( - "Failed to contact cluster entrypoint {}: {}", - entrypoint_addr, err - ); + eprintln!("Failed to contact cluster entrypoint {entrypoint_addr}: {err}"); exit(1); }) } else { @@ -192,26 +189,20 @@ fn process_spy_results( } else { " or more" }; - eprintln!( - "Error: Insufficient validators discovered. Expecting {}{}", - num, add, - ); + eprintln!("Error: Insufficient validators discovered. Expecting {num}{add}",); exit(1); } } if let Some(node) = pubkey { if !validators.iter().any(|x| x.id == node) { - eprintln!("Error: Could not find node {:?}", node); + eprintln!("Error: Could not find node {node:?}"); exit(1); } } } if let Some(num_nodes_exactly) = num_nodes_exactly { if validators.len() > num_nodes_exactly { - eprintln!( - "Error: Extra nodes discovered. Expecting exactly {}", - num_nodes_exactly - ); + eprintln!("Error: Extra nodes discovered. Expecting exactly {num_nodes_exactly}"); exit(1); } } @@ -269,7 +260,7 @@ fn process_spy(matches: &ArgMatches, socket_addr_space: SocketAddrSpace) -> std: fn parse_entrypoint(matches: &ArgMatches) -> Option { matches.value_of("entrypoint").map(|entrypoint| { solana_net_utils::parse_host_port(entrypoint).unwrap_or_else(|e| { - eprintln!("failed to parse entrypoint address: {}", e); + eprintln!("failed to parse entrypoint address: {e}"); exit(1); }) }) @@ -314,7 +305,7 @@ fn process_rpc_url( } for rpc_addr in rpc_addrs { - println!("http://{}", rpc_addr); + println!("http://{rpc_addr}"); if any { break; } diff --git a/gossip/tests/cluster_info.rs b/gossip/tests/cluster_info.rs index 85f8f0c75..6b33939a3 100644 --- a/gossip/tests/cluster_info.rs +++ b/gossip/tests/cluster_info.rs @@ -227,8 +227,7 @@ fn run_simulation(stakes: &[u64], fanout: usize) { for (id, (layer1_done, recv, r)) in batch.iter_mut() { assert!( now.elapsed().as_secs() < timeout, - "Timed out with {:?} remaining nodes", - remaining + "Timed out with {remaining:?} remaining nodes" ); let cluster = c_info.clone_with_id(id); if !*layer1_done { diff --git a/gossip/tests/crds_gossip.rs b/gossip/tests/crds_gossip.rs index 0c0d4e8b4..1c79a8f65 100644 --- a/gossip/tests/crds_gossip.rs +++ b/gossip/tests/crds_gossip.rs @@ -607,7 +607,7 @@ fn network_run_pull( fn build_gossip_thread_pool() -> ThreadPool { ThreadPoolBuilder::new() .num_threads(get_thread_count().min(2)) - .thread_name(|i| format!("gossipTest{:02}", i)) + .thread_name(|i| format!("gossipTest{i:02}")) .build() .unwrap() } diff --git a/install/src/bin/solana-install-init.rs b/install/src/bin/solana-install-init.rs index 42f68b1cd..ec888d8f4 100644 --- a/install/src/bin/solana-install-init.rs +++ b/install/src/bin/solana-install-init.rs @@ -17,7 +17,7 @@ fn press_enter() { fn main() { solana_install::main_init().unwrap_or_else(|err| { - println!("Error: {}", err); + println!("Error: {err}"); press_enter(); exit(1); }); diff --git a/install/src/command.rs b/install/src/command.rs index 1278c32e4..e4c77532f 100644 --- a/install/src/command.rs +++ b/install/src/command.rs @@ -89,7 +89,7 @@ fn download_to_temp( Ok(hasher.result()) } - let url = Url::parse(url).map_err(|err| format!("Unable to parse {}: {}", url, err))?; + let url = Url::parse(url).map_err(|err| format!("Unable to parse {url}: {err}"))?; let temp_dir = TempDir::new()?; let temp_file = temp_dir.path().join("download"); @@ -100,7 +100,7 @@ fn download_to_temp( .build()?; let progress_bar = new_spinner_progress_bar(); - progress_bar.set_message(format!("{}Downloading...", TRUCK)); + progress_bar.set_message(format!("{TRUCK}Downloading...")); let response = client.get(url.as_str()).send()?; let download_size = { @@ -121,7 +121,7 @@ fn download_to_temp( .expect("ProgresStyle::template direct input to be correct") .progress_chars("=> "), ); - progress_bar.set_message(format!("{}Downloading", TRUCK)); + progress_bar.set_message(format!("{TRUCK}Downloading")); struct DownloadProgress { progress_bar: ProgressBar, @@ -146,7 +146,7 @@ fn download_to_temp( std::io::copy(&mut source, &mut file)?; let temp_file_sha256 = sha256_file_digest(&temp_file) - .map_err(|err| format!("Unable to hash {:?}: {}", temp_file, err))?; + .map_err(|err| format!("Unable to hash {temp_file:?}: {err}"))?; if expected_sha256.is_some() && expected_sha256 != Some(&temp_file_sha256) { return Err(io::Error::new(io::ErrorKind::Other, "Incorrect hash").into()); @@ -164,7 +164,7 @@ fn extract_release_archive( use {bzip2::bufread::BzDecoder, tar::Archive}; let progress_bar = new_spinner_progress_bar(); - progress_bar.set_message(format!("{}Extracting...", PACKAGE)); + progress_bar.set_message(format!("{PACKAGE}Extracting...")); if extract_dir.exists() { let _ = fs::remove_dir_all(extract_dir); @@ -189,9 +189,9 @@ fn extract_release_archive( fn load_release_version(version_yml: &Path) -> Result { let file = File::open(version_yml) - .map_err(|err| format!("Unable to open {:?}: {:?}", version_yml, err))?; + .map_err(|err| format!("Unable to open {version_yml:?}: {err:?}"))?; let version: ReleaseVersion = serde_yaml::from_reader(file) - .map_err(|err| format!("Unable to parse {:?}: {:?}", version_yml, err))?; + .map_err(|err| format!("Unable to parse {version_yml:?}: {err:?}"))?; Ok(version) } @@ -273,13 +273,13 @@ fn get_update_manifest( ) -> Result { let data = rpc_client .get_account_data(update_manifest_pubkey) - .map_err(|err| format!("Unable to fetch update manifest: {}", err))?; + .map_err(|err| format!("Unable to fetch update manifest: {err}"))?; let config_data = get_config_data(&data) - .map_err(|err| format!("Unable to get at config_data to update manifest: {}", err))?; + .map_err(|err| format!("Unable to get at config_data to update manifest: {err}"))?; let signed_update_manifest = SignedUpdateManifest::deserialize(update_manifest_pubkey, config_data) - .map_err(|err| format!("Unable to deserialize update manifest: {}", err))?; + .map_err(|err| format!("Unable to deserialize update manifest: {err}"))?; Ok(signed_update_manifest.manifest) } @@ -448,7 +448,7 @@ fn add_to_path(new_path: &str) -> bool { #[cfg(unix)] fn add_to_path(new_path: &str) -> bool { - let shell_export_string = format!("\nexport PATH=\"{}:$PATH\"", new_path); + let shell_export_string = format!("\nexport PATH=\"{new_path}:$PATH\""); let mut modified_rcfiles = false; // Look for sh, bash, and zsh rc files @@ -488,7 +488,7 @@ fn add_to_path(new_path: &str) -> bool { match read_file(&rcfile) { Err(err) => { - println!("Unable to read {:?}: {}", rcfile, err); + println!("Unable to read {rcfile:?}: {err}"); } Ok(contents) => { if !contents.contains(&shell_export_string) { @@ -506,14 +506,14 @@ fn add_to_path(new_path: &str) -> bool { .create(true) .open(dest)?; - writeln!(&mut dest_file, "{}", line)?; + writeln!(&mut dest_file, "{line}")?; dest_file.sync_data()?; Ok(()) } append_file(&rcfile, &shell_export_string).unwrap_or_else(|err| { - format!("Unable to append to {:?}: {}", rcfile, err); + format!("Unable to append to {rcfile:?}: {err}"); }); modified_rcfiles = true; } @@ -597,9 +597,9 @@ fn release_channel_version_url(release_channel: &str) -> String { fn print_update_manifest(update_manifest: &UpdateManifest) { let when = Local.timestamp(update_manifest.timestamp_secs as i64, 0); - println_name_value(&format!("{}release date:", BULLET), &when.to_string()); + println_name_value(&format!("{BULLET}release date:"), &when.to_string()); println_name_value( - &format!("{}download URL:", BULLET), + &format!("{BULLET}download URL:"), &update_manifest.download_url, ); } @@ -619,7 +619,7 @@ pub fn info(config_file: &str, local_info_only: bool, eval: bool) -> Result<(), ExplicitRelease::Channel(channel) => channel, }) .and_then(|channel| { - println!("SOLANA_INSTALL_ACTIVE_CHANNEL={}", channel,); + println!("SOLANA_INSTALL_ACTIVE_CHANNEL={channel}",); Option::::None }); return Ok(()); @@ -636,7 +636,7 @@ pub fn info(config_file: &str, local_info_only: bool, eval: bool) -> Result<(), load_release_version(&config.active_release_dir().join("version.yml")) { println_name_value( - &format!("{}Release commit:", BULLET), + &format!("{BULLET}Release commit:"), &release_version.commit[0..7], ); } @@ -645,16 +645,16 @@ pub fn info(config_file: &str, local_info_only: bool, eval: bool) -> Result<(), if let Some(explicit_release) = &config.explicit_release { match explicit_release { ExplicitRelease::Semver(release_semver) => { - println_name_value(&format!("{}Release version:", BULLET), release_semver); + println_name_value(&format!("{BULLET}Release version:"), release_semver); println_name_value( - &format!("{}Release URL:", BULLET), + &format!("{BULLET}Release URL:"), &github_release_download_url(release_semver), ); } ExplicitRelease::Channel(release_channel) => { - println_name_value(&format!("{}Release channel:", BULLET), release_channel); + println_name_value(&format!("{BULLET}Release channel:"), release_channel); println_name_value( - &format!("{}Release URL:", BULLET), + &format!("{BULLET}Release URL:"), &release_channel_download_url(release_channel), ); } @@ -693,9 +693,9 @@ pub fn deploy( update_manifest_keypair_file: &str, ) -> Result<(), String> { let from_keypair = read_keypair_file(from_keypair_file) - .map_err(|err| format!("Unable to read {}: {}", from_keypair_file, err))?; + .map_err(|err| format!("Unable to read {from_keypair_file}: {err}"))?; let update_manifest_keypair = read_keypair_file(update_manifest_keypair_file) - .map_err(|err| format!("Unable to read {}: {}", update_manifest_keypair_file, err))?; + .map_err(|err| format!("Unable to read {update_manifest_keypair_file}: {err}"))?; println_name_value("JSON RPC URL:", json_rpc_url); println_name_value( @@ -706,23 +706,20 @@ pub fn deploy( // Confirm the `json_rpc_url` is good and that `from_keypair` is a valid account let rpc_client = RpcClient::new(json_rpc_url.to_string()); let progress_bar = new_spinner_progress_bar(); - progress_bar.set_message(format!("{}Checking cluster...", LOOKING_GLASS)); + progress_bar.set_message(format!("{LOOKING_GLASS}Checking cluster...")); let balance = rpc_client .get_balance(&from_keypair.pubkey()) .map_err(|err| { - format!( - "Unable to get the account balance of {}: {}", - from_keypair_file, err - ) + format!("Unable to get the account balance of {from_keypair_file}: {err}") })?; progress_bar.finish_and_clear(); if balance == 0 { - return Err(format!("{} account balance is empty", from_keypair_file)); + return Err(format!("{from_keypair_file} account balance is empty")); } // Download the release let (temp_dir, temp_archive, temp_archive_sha256) = download_to_temp(download_url, None) - .map_err(|err| format!("Unable to download {}: {}", download_url, err))?; + .map_err(|err| format!("Unable to download {download_url}: {err}"))?; if let Ok(update_manifest) = get_update_manifest(&rpc_client, &update_manifest_keypair.pubkey()) { @@ -739,23 +736,16 @@ pub fn deploy( // Extract it and load the release version metadata let temp_release_dir = temp_dir.path().join("archive"); extract_release_archive(&temp_archive, &temp_release_dir).map_err(|err| { - format!( - "Unable to extract {:?} into {:?}: {}", - temp_archive, temp_release_dir, err - ) + format!("Unable to extract {temp_archive:?} into {temp_release_dir:?}: {err}") })?; - let release_target = load_release_target(&temp_release_dir).map_err(|err| { - format!( - "Unable to load release target from {:?}: {}", - temp_release_dir, err - ) - })?; + let release_target = load_release_target(&temp_release_dir) + .map_err(|err| format!("Unable to load release target from {temp_release_dir:?}: {err}"))?; println_name_value("Update target:", &release_target); let progress_bar = new_spinner_progress_bar(); - progress_bar.set_message(format!("{}Deploying update...", PACKAGE)); + progress_bar.set_message(format!("{PACKAGE}Deploying update...")); // Construct an update manifest for the release let mut update_manifest = SignedUpdateManifest { @@ -772,14 +762,14 @@ pub fn deploy( // Store the new update manifest on the cluster new_update_manifest(&rpc_client, &from_keypair, &update_manifest_keypair) - .map_err(|err| format!("Unable to create update manifest: {}", err))?; + .map_err(|err| format!("Unable to create update manifest: {err}"))?; store_update_manifest( &rpc_client, &from_keypair, &update_manifest_keypair, &update_manifest, ) - .map_err(|err| format!("Unable to store update manifest: {:?}", err))?; + .map_err(|err| format!("Unable to store update manifest: {err:?}"))?; progress_bar.finish_and_clear(); println!(" {}{}", SPARKLE, style("Deployment successful").bold()); @@ -838,7 +828,7 @@ pub fn gc(config_file: &str) -> Result<(), String> { .expect("ProgresStyle::template direct input to be correct") .progress_chars("=> "), ); - progress_bar.set_message(format!("{}Removing old releases", RECYCLING)); + progress_bar.set_message(format!("{RECYCLING}Removing old releases")); for (release, _modified_type) in old_releases { progress_bar.inc(1); let _ = fs::remove_dir_all(release); @@ -884,8 +874,8 @@ fn check_for_newer_github_release( let url = reqwest::Url::parse_with_params( "https://api.github.com/repos/solana-labs/solana/releases", &[ - ("per_page", &format!("{}", PER_PAGE)), - ("page", &format!("{}", page)), + ("per_page", &format!("{PER_PAGE}")), + ("page", &format!("{page}")), ], ) .unwrap(); @@ -947,7 +937,7 @@ pub fn init_or_update(config_file: &str, is_init: bool, check_only: bool) -> Res match explicit_release { ExplicitRelease::Semver(current_release_semver) => { let progress_bar = new_spinner_progress_bar(); - progress_bar.set_message(format!("{}Checking for updates...", LOOKING_GLASS)); + progress_bar.set_message(format!("{LOOKING_GLASS}Checking for updates...")); let github_release = check_for_newer_github_release( semver::VersionReq::parse(&format!( @@ -967,19 +957,18 @@ pub fn init_or_update(config_file: &str, is_init: bool, check_only: bool) -> Res match github_release { None => { - return Err(format!("Unknown release: {}", current_release_semver)); + return Err(format!("Unknown release: {current_release_semver}")); } Some(release_semver) => { if release_semver == *current_release_semver { if let Ok(active_release_version) = load_release_version( &config.active_release_dir().join("version.yml"), ) { - if format!("v{}", current_release_semver) + if format!("v{current_release_semver}") == active_release_version.channel { println!( - "Install is up to date. {} is the latest compatible release", - release_semver + "Install is up to date. {release_semver} is the latest compatible release" ); return Ok(false); } @@ -1004,7 +993,7 @@ pub fn init_or_update(config_file: &str, is_init: bool, check_only: bool) -> Res let (_temp_dir, temp_file, _temp_archive_sha256) = download_to_temp(&version_url, None) - .map_err(|err| format!("Unable to download {}: {}", version_url, err))?; + .map_err(|err| format!("Unable to download {version_url}: {err}"))?; let update_release_version = load_release_version(&temp_file)?; @@ -1069,7 +1058,7 @@ pub fn init_or_update(config_file: &str, is_init: bool, check_only: bool) -> Res } } else { let progress_bar = new_spinner_progress_bar(); - progress_bar.set_message(format!("{}Checking for updates...", LOOKING_GLASS)); + progress_bar.set_message(format!("{LOOKING_GLASS}Checking for updates...")); let rpc_client = RpcClient::new(config.json_rpc_url.clone()); let update_manifest = get_update_manifest(&rpc_client, &config.update_manifest_pubkey)?; progress_bar.finish_and_clear(); @@ -1111,7 +1100,7 @@ pub fn init_or_update(config_file: &str, is_init: bool, check_only: bool) -> Res println!( " {}{}", WRAPPED_PRESENT, - style(format!("Update available: {}", updated_version)).bold() + style(format!("Update available: {updated_version}")).bold() ); return Ok(true); } @@ -1119,24 +1108,17 @@ pub fn init_or_update(config_file: &str, is_init: bool, check_only: bool) -> Res if let Some((download_url, archive_sha256)) = download_url_and_sha256 { let (_temp_dir, temp_archive, _temp_archive_sha256) = download_to_temp(&download_url, archive_sha256.as_ref()) - .map_err(|err| format!("Unable to download {}: {}", download_url, err))?; + .map_err(|err| format!("Unable to download {download_url}: {err}"))?; extract_release_archive(&temp_archive, &release_dir).map_err(|err| { - format!( - "Unable to extract {:?} to {:?}: {}", - temp_archive, release_dir, err - ) + format!("Unable to extract {temp_archive:?} to {release_dir:?}: {err}") })?; } - let release_target = load_release_target(&release_dir).map_err(|err| { - format!( - "Unable to load release target from {:?}: {}", - release_dir, err - ) - })?; + let release_target = load_release_target(&release_dir) + .map_err(|err| format!("Unable to load release target from {release_dir:?}: {err}"))?; if release_target != crate::build_env::TARGET { - return Err(format!("Incompatible update target: {}", release_target)); + return Err(format!("Incompatible update target: {release_target}")); } // Trigger an update to the modification time for `release_dir` @@ -1167,13 +1149,13 @@ pub fn init_or_update(config_file: &str, is_init: bool, check_only: bool) -> Res println!( " {}{}", SPARKLE, - style(format!("{} initialized", updated_version)).bold() + style(format!("{updated_version} initialized")).bold() ); } else { println!( " {}{}", SPARKLE, - style(format!("Update successful to {}", updated_version)).bold() + style(format!("Update successful to {updated_version}")).bold() ); } Ok(true) @@ -1212,14 +1194,14 @@ pub fn run( Some(mut child) => match child.try_wait() { Ok(Some(status)) => { println_name_value( - &format!("{} exited with:", program_name), + &format!("{program_name} exited with:"), &status.to_string(), ); None } Ok(None) => Some(child), Err(err) => { - eprintln!("Error attempting to wait for program to exit: {}", err); + eprintln!("Error attempting to wait for program to exit: {err}"); None } }, @@ -1230,7 +1212,7 @@ pub fn run( { Ok(child) => Some(child), Err(err) => { - eprintln!("Failed to spawn {}: {:?}", program_name, err); + eprintln!("Failed to spawn {program_name}: {err:?}"); None } } @@ -1243,13 +1225,13 @@ pub fn run( // Update successful, kill current process so it will be restart if let Some(ref mut child) = child_option { stop_process(child).unwrap_or_else(|err| { - eprintln!("Failed to stop child: {:?}", err); + eprintln!("Failed to stop child: {err:?}"); }); } } Ok(false) => {} // No update available Err(err) => { - eprintln!("Failed to apply update: {:?}", err); + eprintln!("Failed to apply update: {err:?}"); } }; now = Instant::now(); @@ -1259,7 +1241,7 @@ pub fn run( // Handle SIGTERM... if let Some(ref mut child) = child_option { stop_process(child).unwrap_or_else(|err| { - eprintln!("Failed to stop child: {:?}", err); + eprintln!("Failed to stop child: {err:?}"); }); } std::process::exit(0); diff --git a/install/src/config.rs b/install/src/config.rs index 62ba76bd6..42f151e0f 100644 --- a/install/src/config.rs +++ b/install/src/config.rs @@ -47,17 +47,17 @@ impl Config { fn _load(config_file: &str) -> Result { let file = File::open(config_file)?; let config = serde_yaml::from_reader(file) - .map_err(|err| io::Error::new(io::ErrorKind::Other, format!("{:?}", err)))?; + .map_err(|err| io::Error::new(io::ErrorKind::Other, format!("{err:?}")))?; Ok(config) } pub fn load(config_file: &str) -> Result { - Self::_load(config_file).map_err(|err| format!("Unable to load {}: {:?}", config_file, err)) + Self::_load(config_file).map_err(|err| format!("Unable to load {config_file}: {err:?}")) } fn _save(&self, config_file: &str) -> Result<(), io::Error> { let serialized = serde_yaml::to_string(self) - .map_err(|err| io::Error::new(io::ErrorKind::Other, format!("{:?}", err)))?; + .map_err(|err| io::Error::new(io::ErrorKind::Other, format!("{err:?}")))?; if let Some(outdir) = Path::new(&config_file).parent() { create_dir_all(outdir)?; @@ -71,7 +71,7 @@ impl Config { pub fn save(&self, config_file: &str) -> Result<(), String> { self._save(config_file) - .map_err(|err| format!("Unable to save {}: {:?}", config_file, err)) + .map_err(|err| format!("Unable to save {config_file}: {err:?}")) } pub fn active_release_dir(&self) -> &PathBuf { @@ -104,7 +104,7 @@ mod test { let json_rpc_url = "https://api.mainnet-beta.solana.com"; let pubkey = Pubkey::default(); let config_name = "config.yaml"; - let config_path = format!("{}/{}", root_dir, config_name); + let config_path = format!("{root_dir}/{config_name}"); let config = Config::new(&root_dir, json_rpc_url, &pubkey, None); @@ -154,10 +154,9 @@ update_manifest_pubkey: current_update_manifest: null update_poll_secs: 3600 explicit_release: null -releases_dir: {}/releases -active_release_dir: {}/active_release -", - root_dir, root_dir +releases_dir: {root_dir}/releases +active_release_dir: {root_dir}/active_release +" ), ); } diff --git a/install/src/lib.rs b/install/src/lib.rs index f79bdfcf1..e6f68587a 100644 --- a/install/src/lib.rs +++ b/install/src/lib.rs @@ -20,14 +20,14 @@ mod update_manifest; pub fn is_semver(semver: &str) -> Result<(), String> { match semver::Version::parse(semver) { Ok(_) => Ok(()), - Err(err) => Err(format!("{:?}", err)), + Err(err) => Err(format!("{err:?}")), } } pub fn is_release_channel(channel: &str) -> Result<(), String> { match channel { "edge" | "beta" | "stable" => Ok(()), - _ => Err(format!("Invalid release channel {}", channel)), + _ => Err(format!("Invalid release channel {channel}")), } } diff --git a/install/src/stop_process.rs b/install/src/stop_process.rs index 1829837cb..f41fbb4df 100644 --- a/install/src/stop_process.rs +++ b/install/src/stop_process.rs @@ -45,25 +45,25 @@ pub fn stop_process(process: &mut Child) -> Result<(), io::Error> { } } Err(EINVAL) => { - println!("Invalid signal. Killing process {}", pid); + println!("Invalid signal. Killing process {pid}"); kill_process(process)?; } Err(EPERM) => { return Err(io::Error::new( ErrorKind::InvalidInput, - format!("Insufficient permissions to signal process {}", pid), + format!("Insufficient permissions to signal process {pid}"), )); } Err(ESRCH) => { return Err(io::Error::new( ErrorKind::InvalidInput, - format!("Process {} does not exist", pid), + format!("Process {pid} does not exist"), )); } Err(e) => { return Err(io::Error::new( ErrorKind::InvalidInput, - format!("Unexpected error {}", e), + format!("Unexpected error {e}"), )); } }; diff --git a/keygen/src/keygen.rs b/keygen/src/keygen.rs index 235ff0923..d11c85da0 100644 --- a/keygen/src/keygen.rs +++ b/keygen/src/keygen.rs @@ -127,7 +127,7 @@ impl KeyGenerationCommonArgs for Command<'_> { fn check_for_overwrite(outfile: &str, matches: &ArgMatches) { let force = matches.is_present("force"); if !force && Path::new(outfile).exists() { - eprintln!("Refusing to overwrite {} without --force flag", outfile); + eprintln!("Refusing to overwrite {outfile} without --force flag"); exit(1); } } @@ -159,7 +159,7 @@ fn output_keypair( write_keypair(keypair, &mut stdout)?; } else { write_keypair_file(keypair, outfile)?; - println!("Wrote {} keypair to {}", source, outfile); + println!("Wrote {source} keypair to {outfile}"); } Ok(()) } @@ -254,7 +254,7 @@ fn acquire_passphrase_and_message( } fn grind_print_info(grind_matches: &[GrindMatch], num_threads: usize) { - println!("Searching with {} threads for:", num_threads); + println!("Searching with {num_threads} threads for:"); for gm in grind_matches { let mut msg = Vec::::new(); if gm.count.load(Ordering::Relaxed) > 1 { @@ -587,7 +587,7 @@ fn do_main(matches: &ArgMatches) -> Result<(), Box> { check_for_overwrite(outfile, matches); write_pubkey_file(outfile, pubkey)?; } else { - println!("{}", pubkey); + println!("{pubkey}"); } } ("new", matches) => { @@ -629,7 +629,7 @@ fn do_main(matches: &ArgMatches) -> Result<(), Box> { if let Some(outfile) = outfile { output_keypair(&keypair, outfile, "new") - .map_err(|err| format!("Unable to write {}: {}", outfile, err))?; + .map_err(|err| format!("Unable to write {outfile}: {err}"))?; } if !silent { @@ -840,9 +840,9 @@ fn do_main(matches: &ArgMatches) -> Result<(), Box> { let pubkey_bs58 = matches.value_of("pubkey").unwrap(); let pubkey = bs58::decode(pubkey_bs58).into_vec().unwrap(); if signature.verify(&pubkey, &simple_message) { - println!("Verification for public key: {}: Success", pubkey_bs58); + println!("Verification for public key: {pubkey_bs58}: Success"); } else { - println!("Verification for public key: {}: Failed", pubkey_bs58); + println!("Verification for public key: {pubkey_bs58}: Failed"); exit(1); } } diff --git a/ledger-tool/src/bigtable.rs b/ledger-tool/src/bigtable.rs index a22e99d87..772992d80 100644 --- a/ledger-tool/src/bigtable.rs +++ b/ledger-tool/src/bigtable.rs @@ -45,7 +45,7 @@ async fn upload( ) -> Result<(), Box> { let bigtable = solana_storage_bigtable::LedgerStorage::new_with_config(config) .await - .map_err(|err| format!("Failed to connect to storage: {:?}", err))?; + .map_err(|err| format!("Failed to connect to storage: {err:?}"))?; let config = ConfirmedBlockUploadConfig { force_reupload, @@ -83,7 +83,7 @@ async fn delete_slots( let dry_run = config.read_only; let bigtable = solana_storage_bigtable::LedgerStorage::new_with_config(config) .await - .map_err(|err| format!("Failed to connect to storage: {:?}", err))?; + .map_err(|err| format!("Failed to connect to storage: {err:?}"))?; solana_ledger::bigtable_delete::delete_confirmed_blocks(bigtable, slots, dry_run).await } @@ -93,7 +93,7 @@ async fn first_available_block( ) -> Result<(), Box> { let bigtable = solana_storage_bigtable::LedgerStorage::new_with_config(config).await?; match bigtable.get_first_available_block().await? { - Some(block) => println!("{}", block), + Some(block) => println!("{block}"), None => println!("No blocks available"), } @@ -107,7 +107,7 @@ async fn block( ) -> Result<(), Box> { let bigtable = solana_storage_bigtable::LedgerStorage::new_with_config(config) .await - .map_err(|err| format!("Failed to connect to storage: {:?}", err))?; + .map_err(|err| format!("Failed to connect to storage: {err:?}"))?; let confirmed_block = bigtable.get_confirmed_block(slot).await?; let encoded_block = confirmed_block @@ -121,10 +121,7 @@ async fn block( ) .map_err(|err| match err { EncodeError::UnsupportedTransactionVersion(version) => { - format!( - "Failed to process unsupported transaction version ({}) in block", - version - ) + format!("Failed to process unsupported transaction version ({version}) in block") } })?; @@ -143,10 +140,10 @@ async fn blocks( ) -> Result<(), Box> { let bigtable = solana_storage_bigtable::LedgerStorage::new_with_config(config) .await - .map_err(|err| format!("Failed to connect to storage: {:?}", err))?; + .map_err(|err| format!("Failed to connect to storage: {err:?}"))?; let slots = bigtable.get_confirmed_blocks(starting_slot, limit).await?; - println!("{:?}", slots); + println!("{slots:?}"); println!("{} blocks found", slots.len()); Ok(()) @@ -160,7 +157,7 @@ async fn compare_blocks( ) -> Result<(), Box> { let owned_bigtable = solana_storage_bigtable::LedgerStorage::new_with_config(config) .await - .map_err(|err| format!("failed to connect to owned bigtable: {:?}", err))?; + .map_err(|err| format!("failed to connect to owned bigtable: {err:?}"))?; let owned_bigtable_slots = owned_bigtable .get_confirmed_blocks(starting_slot, limit) .await?; @@ -170,7 +167,7 @@ async fn compare_blocks( ); let reference_bigtable = solana_storage_bigtable::LedgerStorage::new_with_config(ref_config) .await - .map_err(|err| format!("failed to connect to reference bigtable: {:?}", err))?; + .map_err(|err| format!("failed to connect to reference bigtable: {err:?}"))?; let reference_bigtable_slots = reference_bigtable .get_confirmed_blocks(starting_slot, limit) @@ -201,7 +198,7 @@ async fn confirm( ) -> Result<(), Box> { let bigtable = solana_storage_bigtable::LedgerStorage::new_with_config(config) .await - .map_err(|err| format!("Failed to connect to storage: {:?}", err))?; + .map_err(|err| format!("Failed to connect to storage: {err:?}"))?; let transaction_status = bigtable.get_signature_status(signature).await?; @@ -227,7 +224,7 @@ async fn confirm( } Ok(None) => {} Err(err) => { - get_transaction_error = Some(format!("{:?}", err)); + get_transaction_error = Some(format!("{err:?}")); } } } @@ -280,7 +277,7 @@ pub async fn transaction_history( result.memo.unwrap_or_default(), match result.err { None => "Confirmed".to_string(), - Some(err) => format!("Failed: {:?}", err), + Some(err) => format!("Failed: {err:?}"), } ); } else { @@ -321,7 +318,7 @@ pub async fn transaction_history( } match bigtable.get_confirmed_block(result.slot).await { Err(err) => { - println!(" Unable to get confirmed transaction details: {}", err); + println!(" Unable to get confirmed transaction details: {err}"); break; } Ok(confirmed_block) => { @@ -786,7 +783,7 @@ pub fn bigtable_process_command( }; future.unwrap_or_else(|err| { - eprintln!("{:?}", err); + eprintln!("{err:?}"); exit(1); }); } diff --git a/ledger-tool/src/main.rs b/ledger-tool/src/main.rs index 60b9fb7b3..7c7889450 100644 --- a/ledger-tool/src/main.rs +++ b/ledger-tool/src/main.rs @@ -140,7 +140,7 @@ fn output_slot_rewards(blockstore: &Blockstore, slot: Slot, method: &LedgerOutpu " {:<44} {:^15} {}â—Ž{:<14.9} â—Ž{:<18.9} {}", reward.pubkey, if let Some(reward_type) = reward.reward_type { - format!("{}", reward_type) + format!("{reward_type}") } else { "-".to_string() }, @@ -149,7 +149,7 @@ fn output_slot_rewards(blockstore: &Blockstore, slot: Slot, method: &LedgerOutpu lamports_to_sol(reward.post_balance), reward .commission - .map(|commission| format!("{:>9}%", commission)) + .map(|commission| format!("{commission:>9}%")) .unwrap_or_else(|| " -".to_string()) ); } @@ -175,7 +175,7 @@ fn output_entry( entry.transactions.len() ); for (transactions_index, transaction) in entry.transactions.into_iter().enumerate() { - println!(" Transaction {}", transactions_index); + println!(" Transaction {transactions_index}"); let tx_signature = transaction.signatures[0]; let tx_status_meta = blockstore .read_transaction_status((tx_signature, slot)) @@ -225,12 +225,12 @@ fn output_slot( let (entries, num_shreds, is_full) = blockstore .get_slot_entries_with_shred_info(slot, 0, allow_dead_slots) - .map_err(|err| format!("Failed to load entries for slot {}: {:?}", slot, err))?; + .map_err(|err| format!("Failed to load entries for slot {slot}: {err:?}"))?; if *method == LedgerOutputMethod::Print { if let Ok(Some(meta)) = blockstore.meta(slot) { if verbose_level >= 1 { - println!(" {:?} is_full: {}", meta, is_full); + println!(" {meta:?} is_full: {is_full}"); } else { println!( " num_shreds: {}, parent_slot: {:?}, next_slots: {:?}, num_entries: {}, is_full: {}", @@ -289,10 +289,7 @@ fn output_slot( } } - println!( - " Transactions: {}, hashes: {}, block_hash: {}", - transactions, num_hashes, blockhash, - ); + println!(" Transactions: {transactions}, hashes: {num_hashes}, block_hash: {blockhash}",); for (pubkey, count) in program_ids.iter() { *all_program_ids.entry(*pubkey).or_insert(0) += count; } @@ -315,10 +312,7 @@ fn output_ledger( let slot_iterator = blockstore .slot_meta_iterator(starting_slot) .unwrap_or_else(|err| { - eprintln!( - "Failed to load entries starting from slot {}: {:?}", - starting_slot, err - ); + eprintln!("Failed to load entries starting from slot {starting_slot}: {err:?}"); exit(1); }); @@ -355,7 +349,7 @@ fn output_ledger( verbose_level, &mut all_program_ids, ) { - eprintln!("{}", err); + eprintln!("{err}"); } num_printed += 1; if num_printed >= num_slots as usize { @@ -387,12 +381,12 @@ fn output_account( print_account_data: bool, encoding: UiAccountEncoding, ) { - println!("{}:", pubkey); + println!("{pubkey}:"); println!(" balance: {} SOL", lamports_to_sol(account.lamports())); println!(" owner: '{}'", account.owner()); println!(" executable: {}", account.executable()); if let Some(slot) = modified_slot { - println!(" slot: {}", slot); + println!(" slot: {slot}"); } println!(" rent_epoch: {}", account.rent_epoch()); println!(" data_len: {}", account.data().len()); @@ -400,7 +394,7 @@ fn output_account( let account_data = UiAccount::encode(pubkey, account, encoding, None, None).data; match account_data { UiAccountData::Binary(data, data_encoding) => { - println!(" data: '{}'", data); + println!(" data: '{data}'"); println!( " encoding: {}", serde_json::to_string(&data_encoding).unwrap() @@ -420,12 +414,12 @@ fn output_account( fn render_dot(dot: String, output_file: &str, output_format: &str) -> io::Result<()> { let mut child = Command::new("dot") - .arg(format!("-T{}", output_format)) - .arg(format!("-o{}", output_file)) + .arg(format!("-T{output_format}")) + .arg(format!("-o{output_file}")) .stdin(Stdio::piped()) .spawn() .map_err(|err| { - eprintln!("Failed to spawn dot: {:?}", err); + eprintln!("Failed to spawn dot: {err:?}"); err })?; @@ -944,7 +938,7 @@ fn open_blockstore( }) } Err(err) => { - eprintln!("Failed to open blockstore at {:?}: {:?}", ledger_path, err); + eprintln!("Failed to open blockstore at {ledger_path:?}: {err:?}"); exit(1); } } @@ -988,10 +982,10 @@ fn print_blockstore_file_metadata( ) -> Result<(), String> { let live_files = blockstore .live_files_metadata() - .map_err(|err| format!("{:?}", err))?; + .map_err(|err| format!("{err:?}"))?; // All files under live_files_metadata are prefixed with "/". - let sst_file_name = file_name.as_ref().map(|name| format!("/{}", name)); + let sst_file_name = file_name.as_ref().map(|name| format!("/{name}")); for file in live_files { if sst_file_name.is_none() || file.name.eq(sst_file_name.as_ref().unwrap()) { println!( @@ -1011,8 +1005,7 @@ fn print_blockstore_file_metadata( } if sst_file_name.is_some() { return Err(format!( - "Failed to find or load the metadata of the specified file {:?}", - file_name + "Failed to find or load the metadata of the specified file {file_name:?}" )); } Ok(()) @@ -1075,10 +1068,7 @@ fn load_bank_forks( // Check if we have the slot data necessary to replay from starting_slot to >= halt_slot. // - This will not catch the case when loading from genesis without a full slot 0. if !blockstore.slot_range_connected(starting_slot, halt_slot) { - eprintln!( - "Unable to load bank forks at slot {} due to disconnected blocks.", - halt_slot, - ); + eprintln!("Unable to load bank forks at slot {halt_slot} due to disconnected blocks.",); exit(1); } } @@ -1123,7 +1113,7 @@ fn load_bank_forks( let geyser_service = GeyserPluginService::new(confirmed_bank_receiver, &geyser_config_files).unwrap_or_else( |err| { - eprintln!("Failed to setup Geyser service: {:?}", err); + eprintln!("Failed to setup Geyser service: {err:?}"); exit(1); }, ); @@ -1195,7 +1185,7 @@ fn compute_slot_cost(blockstore: &Blockstore, slot: Slot) -> Result<(), String> let (entries, _num_shreds, _is_full) = blockstore .get_slot_entries_with_shred_info(slot, 0, false) - .map_err(|err| format!(" Slot: {}, Failed to load entries, err {:?}", slot, err))?; + .map_err(|err| format!(" Slot: {slot}, Failed to load entries, err {err:?}"))?; let num_entries = entries.len(); let mut num_transactions = 0; @@ -1229,8 +1219,7 @@ fn compute_slot_cost(blockstore: &Blockstore, slot: Slot) -> Result<(), String> let result = cost_tracker.try_add(&tx_cost); if result.is_err() { println!( - "Slot: {}, CostModel rejected transaction {:?}, reason {:?}", - slot, transaction, result, + "Slot: {slot}, CostModel rejected transaction {transaction:?}, reason {result:?}", ); } for (program_id, _instruction) in transaction.message().program_instructions_iter() @@ -1241,10 +1230,9 @@ fn compute_slot_cost(blockstore: &Blockstore, slot: Slot) -> Result<(), String> } println!( - "Slot: {}, Entries: {}, Transactions: {}, Programs {}", - slot, num_entries, num_transactions, num_programs, + "Slot: {slot}, Entries: {num_entries}, Transactions: {num_transactions}, Programs {num_programs}", ); - println!(" Programs: {:?}", program_ids); + println!(" Programs: {program_ids:?}"); Ok(()) } @@ -1868,8 +1856,7 @@ fn main() { Ok(()) } else { Err(format!( - "Unable to parse as a number or the keyword ROOT, provided: {}", - value + "Unable to parse as a number or the keyword ROOT, provided: {value}" )) } }) @@ -2312,8 +2299,7 @@ fn main() { "Shred storage type of target_db cannot be inferred, \ the default RocksLevel will be used. \ If you want to use FIFO shred_storage_type on an empty target_db, \ - create {} foldar the specified target_db directory.", - BLOCKSTORE_DIRECTORY_ROCKS_FIFO, + create {BLOCKSTORE_DIRECTORY_ROCKS_FIFO} foldar the specified target_db directory.", ), ); @@ -2358,7 +2344,7 @@ fn main() { ); } } else { - println!("{}", genesis_config); + println!("{genesis_config}"); } } ("genesis-hash", Some(arg_matches)) => { @@ -2391,7 +2377,7 @@ fn main() { LedgerColumnOptions::default(), ) .unwrap_or_else(|err| { - eprintln!("Failed to write genesis config: {:?}", err); + eprintln!("Failed to write genesis config: {err:?}"); exit(1); }); @@ -2438,7 +2424,7 @@ fn main() { ); } Err(err) => { - eprintln!("Failed to load ledger: {:?}", err); + eprintln!("Failed to load ledger: {err:?}"); exit(1); } } @@ -2517,7 +2503,7 @@ fn main() { println!("{}", &bank_forks.read().unwrap().working_bank().hash()); } Err(err) => { - eprintln!("Failed to load ledger: {:?}", err); + eprintln!("Failed to load ledger: {err:?}"); exit(1); } } @@ -2533,7 +2519,7 @@ fn main() { force_update_to_open, ); for slot in slots { - println!("Slot {}", slot); + println!("Slot {slot}"); if let Err(err) = output_slot( &blockstore, slot, @@ -2542,7 +2528,7 @@ fn main() { verbose_level, &mut HashMap::new(), ) { - eprintln!("{}", err); + eprintln!("{err}"); } } } @@ -2576,7 +2562,7 @@ fn main() { ); let starting_slot = value_t_or_exit!(arg_matches, "starting_slot", Slot); for slot in blockstore.dead_slots_iterator(starting_slot).unwrap() { - println!("{}", slot); + println!("{slot}"); } } ("duplicate-slots", Some(arg_matches)) => { @@ -2589,7 +2575,7 @@ fn main() { ); let starting_slot = value_t_or_exit!(arg_matches, "starting_slot", Slot); for slot in blockstore.duplicate_slots_iterator(starting_slot).unwrap() { - println!("{}", slot); + println!("{slot}"); } } ("set-dead-slot", Some(arg_matches)) => { @@ -2603,8 +2589,8 @@ fn main() { ); for slot in slots { match blockstore.set_dead_slot(slot) { - Ok(_) => println!("Slot {} dead", slot), - Err(err) => eprintln!("Failed to set slot {} dead slot: {:?}", slot, err), + Ok(_) => println!("Slot {slot} dead"), + Err(err) => eprintln!("Failed to set slot {slot} dead slot: {err:?}"), } } } @@ -2619,9 +2605,9 @@ fn main() { ); for slot in slots { match blockstore.remove_dead_slot(slot) { - Ok(_) => println!("Slot {} not longer marked dead", slot), + Ok(_) => println!("Slot {slot} not longer marked dead"), Err(err) => { - eprintln!("Failed to remove dead flag for slot {}, {:?}", slot, err) + eprintln!("Failed to remove dead flag for slot {slot}, {err:?}") } } } @@ -2690,10 +2676,7 @@ fn main() { for ((slot1, frozen_log), (slot2, full_log)) in frozen.iter().zip(full.iter()) { assert_eq!(slot1, slot2); - println!( - "Slot: {}\n, full: {}\n, frozen: {}", - slot1, full_log, frozen_log - ); + println!("Slot: {slot1}\n, full: {full_log}\n, frozen: {frozen_log}"); } } ("verify", Some(arg_matches)) => { @@ -2819,7 +2802,7 @@ fn main() { incremental_snapshot_archive_path, ) .unwrap_or_else(|err| { - eprintln!("Ledger verification failed: {:?}", err); + eprintln!("Ledger verification failed: {err:?}"); exit(1); }); if print_accounts_stats { @@ -2877,12 +2860,12 @@ fn main() { }; match result { - Ok(_) => println!("Wrote {}", output_file), - Err(err) => eprintln!("Unable to write {}: {}", output_file, err), + Ok(_) => println!("Wrote {output_file}"), + Err(err) => eprintln!("Unable to write {output_file}: {err}"), } } Err(err) => { - eprintln!("Failed to load ledger: {:?}", err); + eprintln!("Failed to load ledger: {err:?}"); exit(1); } } @@ -2924,8 +2907,7 @@ fn main() { if bootstrap_validator_stake_lamports < minimum_stake_lamports { eprintln!( "Error: insufficient --bootstrap-validator-stake-lamports. \ - Minimum amount is {}", - minimum_stake_lamports + Minimum amount is {minimum_stake_lamports}" ); exit(1); } @@ -2941,7 +2923,7 @@ fn main() { SnapshotVersion::default(), |s| { s.parse::().unwrap_or_else(|e| { - eprintln!("Error: {}", e); + eprintln!("Error: {e}"); exit(1) }) }, @@ -2951,7 +2933,7 @@ fn main() { let archive_format_str = value_t_or_exit!(arg_matches, "snapshot_archive_format", String); ArchiveFormat::from_cli_arg(&archive_format_str).unwrap_or_else(|| { - panic!("Archive format not recognized: {}", archive_format_str) + panic!("Archive format not recognized: {archive_format_str}") }) }; @@ -2988,8 +2970,7 @@ fn main() { .is_none() { eprintln!( - "Error: snapshot slot {} does not exist in blockstore or is not full.", - snapshot_slot, + "Error: snapshot slot {snapshot_slot} does not exist in blockstore or is not full.", ); exit(1); } @@ -2998,8 +2979,7 @@ fn main() { let ending_slot = value_t_or_exit!(arg_matches, "ending_slot", Slot); if ending_slot <= snapshot_slot { eprintln!( - "Error: ending_slot ({}) must be greater than snapshot_slot ({})", - ending_slot, snapshot_slot + "Error: ending_slot ({ending_slot}) must be greater than snapshot_slot ({snapshot_slot})" ); exit(1); } @@ -3057,7 +3037,7 @@ fn main() { .unwrap() .get(snapshot_slot) .unwrap_or_else(|| { - eprintln!("Error: Slot {} is not available", snapshot_slot); + eprintln!("Error: Slot {snapshot_slot} is not available"); exit(1); }); @@ -3110,8 +3090,7 @@ fn main() { for address in accounts_to_remove { let mut account = bank.get_account(&address).unwrap_or_else(|| { eprintln!( - "Error: Account does not exist, unable to remove it: {}", - address + "Error: Account does not exist, unable to remove it: {address}" ); exit(1); }); @@ -3227,8 +3206,7 @@ fn main() { if let Some(warp_slot) = warp_slot { if warp_slot < minimum_warp_slot { eprintln!( - "Error: --warp-slot too close. Must be >= {}", - minimum_warp_slot + "Error: --warp-slot too close. Must be >= {minimum_warp_slot}" ); exit(1); } @@ -3300,7 +3278,7 @@ fn main() { maximum_incremental_snapshot_archives_to_retain, ) .unwrap_or_else(|err| { - eprintln!("Unable to create incremental snapshot: {}", err); + eprintln!("Unable to create incremental snapshot: {err}"); exit(1); }); @@ -3324,7 +3302,7 @@ fn main() { maximum_incremental_snapshot_archives_to_retain, ) .unwrap_or_else(|err| { - eprintln!("Unable to create snapshot: {}", err); + eprintln!("Unable to create snapshot: {err}"); exit(1); }); @@ -3355,7 +3333,7 @@ fn main() { ); } Err(err) => { - eprintln!("Failed to load ledger: {:?}", err); + eprintln!("Failed to load ledger: {err:?}"); exit(1); } } @@ -3386,7 +3364,7 @@ fn main() { incremental_snapshot_archive_path, ) .unwrap_or_else(|err| { - eprintln!("Failed to load ledger: {:?}", err); + eprintln!("Failed to load ledger: {err:?}"); exit(1); }); @@ -3447,7 +3425,7 @@ fn main() { json_serializer.end().unwrap(); } if summarize { - println!("\n{:#?}", total_accounts_stats); + println!("\n{total_accounts_stats:#?}"); } } ("capitalization", Some(arg_matches)) => { @@ -3478,7 +3456,7 @@ fn main() { let bank_forks = bank_forks.read().unwrap(); let slot = bank_forks.working_bank().slot(); let bank = bank_forks.get(slot).unwrap_or_else(|| { - eprintln!("Error: Slot {} is not available", slot); + eprintln!("Error: Slot {slot} is not available"); exit(1); }); @@ -3698,10 +3676,10 @@ fn main() { } InflationPointCalculationEvent::Skipped(skipped_reason) => { if detail.skipped_reasons.is_empty() { - detail.skipped_reasons = format!("{:?}", skipped_reason); + detail.skipped_reasons = format!("{skipped_reason:?}"); } else { use std::fmt::Write; - let _ = write!(&mut detail.skipped_reasons, "/{:?}", skipped_reason); + let _ = write!(&mut detail.skipped_reasons, "/{skipped_reason:?}"); } } } @@ -3806,7 +3784,7 @@ fn main() { detail_ref.as_ref().map(|detail_ref| detail_ref.value()); println!( "{:<45}({}): {} => {} (+{} {:>4.9}%) {:?}", - format!("{}", pubkey), // format! is needed to pad/justify correctly. + format!("{pubkey}"), // format! is needed to pad/justify correctly. base_account.owner(), Sol(base_account.lamports()), Sol(warped_account.lamports()), @@ -3853,7 +3831,7 @@ fn main() { fn format_or_na( data: Option, ) -> String { - data.map(|data| format!("{}", data)) + data.map(|data| format!("{data}")) .unwrap_or_else(|| "N/A".to_owned()) } let mut point_details = detail @@ -3872,7 +3850,7 @@ fn main() { base_bank.cluster_type() ), rewarded_epoch: base_bank.epoch(), - account: format!("{}", pubkey), + account: format!("{pubkey}"), owner: format!("{}", base_account.owner()), old_balance: base_account.lamports(), new_balance: warped_account.lamports(), @@ -3979,7 +3957,7 @@ fn main() { } } Err(err) => { - eprintln!("Failed to load ledger: {:?}", err); + eprintln!("Failed to load ledger: {err:?}"); exit(1); } } @@ -4015,17 +3993,14 @@ fn main() { *slots.last().unwrap() } Err(err) => { - eprintln!("Unable to read the Ledger: {:?}", err); + eprintln!("Unable to read the Ledger: {err:?}"); exit(1); } }, }; if end_slot < start_slot { - eprintln!( - "end slot {} is less than start slot {}", - end_slot, start_slot - ); + eprintln!("end slot {end_slot} is less than start slot {start_slot}"); exit(1); } info!( @@ -4134,7 +4109,7 @@ fn main() { .for_each(|(i, (slot, hash))| { if i < num_roots { output_file - .write_all(format!("{:?}: {:?}\n", slot, hash).as_bytes()) + .write_all(format!("{slot:?}: {hash:?}\n").as_bytes()) .expect("failed to write"); } }); @@ -4160,7 +4135,7 @@ fn main() { let datetime: DateTime = t.into(); datetime.to_rfc3339() }; - let hash_str = format!("{}", hash); + let hash_str = format!("{hash}"); println!("{:>20} {:>44} {:>32}", slot, &hash_str, &time_str); } } @@ -4188,10 +4163,9 @@ fn main() { let num_slots = start_root - end_root - 1; // Adjust by one since start_root need not be checked if arg_matches.is_present("end_root") && num_slots > max_slots { eprintln!( - "Requested range {} too large, max {}. \ + "Requested range {num_slots} too large, max {max_slots}. \ Either adjust `--until` value, or pass a larger `--repair-limit` \ to override the limit", - num_slots, max_slots, ); exit(1); } @@ -4203,19 +4177,16 @@ fn main() { if !roots_to_fix.is_empty() { eprintln!("{} slots to be rooted", roots_to_fix.len()); for chunk in roots_to_fix.chunks(100) { - eprintln!("{:?}", chunk); + eprintln!("{chunk:?}"); blockstore .set_roots(roots_to_fix.iter()) .unwrap_or_else(|err| { - eprintln!("Unable to set roots {:?}: {}", roots_to_fix, err); + eprintln!("Unable to set roots {roots_to_fix:?}: {err}"); exit(1); }); } } else { - println!( - "No missing roots found in range {} to {}", - end_root, start_root - ); + println!("No missing roots found in range {end_root} to {start_root}"); } } ("bounds", Some(arg_matches)) => { @@ -4244,10 +4215,10 @@ fn main() { last ); if all { - println!("Non-empty slots: {:?}", slots); + println!("Non-empty slots: {slots:?}"); } } else { - println!("Ledger has data for slot {:?}", first); + println!("Ledger has data for slot {first:?}"); } } if let Ok(rooted) = blockstore.rooted_slot_iterator(0) { @@ -4270,16 +4241,15 @@ fn main() { } } println!( - " with {} rooted slots from {:?} to {:?}", - total_rooted, first_rooted, last_rooted + " with {total_rooted} rooted slots from {first_rooted:?} to {last_rooted:?}" ); - println!(" and {} slots past the last root", count_past_root); + println!(" and {count_past_root} slots past the last root"); } else { println!(" with no rooted slots"); } } Err(err) => { - eprintln!("Unable to read the Ledger: {:?}", err); + eprintln!("Unable to read the Ledger: {err:?}"); exit(1); } }; @@ -4317,7 +4287,7 @@ fn main() { for slot in slots { if let Err(err) = compute_slot_cost(&blockstore, slot) { - eprintln!("{}", err); + eprintln!("{err}"); } } } @@ -4331,7 +4301,7 @@ fn main() { ); let sst_file_name = arg_matches.value_of("file_name"); if let Err(err) = print_blockstore_file_metadata(&blockstore, &sst_file_name) { - eprintln!("{}", err); + eprintln!("{err}"); } } ("", _) => { diff --git a/ledger/src/bigtable_delete.rs b/ledger/src/bigtable_delete.rs index dc3ede358..654b7d4ae 100644 --- a/ledger/src/bigtable_delete.rs +++ b/ledger/src/bigtable_delete.rs @@ -46,7 +46,7 @@ pub async fn delete_confirmed_blocks( measure.stop(); info!("{}", measure); if failures > 0 { - Err(format!("Incomplete deletion, {} operations failed", failures).into()) + Err(format!("Incomplete deletion, {failures} operations failed").into()) } else { Ok(()) } diff --git a/ledger/src/bigtable_upload.rs b/ledger/src/bigtable_upload.rs index 4881cedc1..f5c40c23c 100644 --- a/ledger/src/bigtable_upload.rs +++ b/ledger/src/bigtable_upload.rs @@ -55,20 +55,13 @@ pub async fn upload_confirmed_blocks( let blockstore_slots: Vec<_> = blockstore .rooted_slot_iterator(starting_slot) .map_err(|err| { - format!( - "Failed to load entries starting from slot {}: {:?}", - starting_slot, err - ) + format!("Failed to load entries starting from slot {starting_slot}: {err:?}") })? .map_while(|slot| (slot <= ending_slot).then_some(slot)) .collect(); if blockstore_slots.is_empty() { - return Err(format!( - "Ledger has no slots from {} to {:?}", - starting_slot, ending_slot - ) - .into()); + return Err(format!("Ledger has no slots from {starting_slot} to {ending_slot:?}").into()); } let first_blockstore_slot = blockstore_slots.first().unwrap(); @@ -274,7 +267,7 @@ pub async fn upload_confirmed_blocks( ); if failures > 0 { - Err(format!("Incomplete upload, {} operations failed", failures).into()) + Err(format!("Incomplete upload, {failures} operations failed").into()) } else { Ok(last_slot) } diff --git a/ledger/src/blockstore.rs b/ledger/src/blockstore.rs index 08760786e..9c88a0d5c 100644 --- a/ledger/src/blockstore.rs +++ b/ledger/src/blockstore.rs @@ -91,12 +91,12 @@ pub use { lazy_static! { static ref PAR_THREAD_POOL: ThreadPool = rayon::ThreadPoolBuilder::new() .num_threads(get_max_thread_count()) - .thread_name(|ix| format!("solBstore{:02}", ix)) + .thread_name(|ix| format!("solBstore{ix:02}")) .build() .unwrap(); static ref PAR_THREAD_POOL_ALL_CPUS: ThreadPool = rayon::ThreadPoolBuilder::new() .num_threads(num_cpus::get()) - .thread_name(|ix| format!("solBstoreAll{:02}", ix)) + .thread_name(|ix| format!("solBstoreAll{ix:02}")) .build() .unwrap(); } @@ -468,7 +468,7 @@ impl Blockstore { ( slot, deserialize(&slot_meta_bytes).unwrap_or_else(|e| { - panic!("Could not deserialize SlotMeta for slot {}: {:?}", slot, e) + panic!("Could not deserialize SlotMeta for slot {slot}: {e:?}") }), ) })) @@ -727,7 +727,7 @@ impl Blockstore { slot, erasure_meta, false, - format!("still need: {}", needed), + format!("still need: {needed}"), 0, ); } @@ -1452,8 +1452,7 @@ impl Blockstore { ( "error", format!( - "Leader {:?}, slot {}: received index {} >= slot.last_index {:?}, shred_source: {:?}", - leader_pubkey, slot, shred_index, last_index, shred_source + "Leader {leader_pubkey:?}, slot {slot}: received index {shred_index} >= slot.last_index {last_index:?}, shred_source: {shred_source:?}" ), String ) @@ -1601,7 +1600,7 @@ impl Blockstore { let shred = self.data_shred_cf.get_bytes((slot, index))?; let shred = shred.map(ShredData::resize_stored_shred).transpose(); shred.map_err(|err| { - let err = format!("Invalid stored shred: {}", err); + let err = format!("Invalid stored shred: {err}"); let err = Box::new(bincode::ErrorKind::Custom(err)); BlockstoreError::InvalidShredData(err) }) @@ -1946,7 +1945,7 @@ impl Blockstore { let blockhash = slot_entries .last() .map(|entry| entry.hash) - .unwrap_or_else(|| panic!("Rooted slot {:?} must have blockhash", slot)); + .unwrap_or_else(|| panic!("Rooted slot {slot:?} must have blockhash")); let slot_transaction_iterator = slot_entries .into_iter() .flat_map(|entry| entry.transactions) @@ -2451,7 +2450,7 @@ impl Blockstore { let block = self.get_complete_block(slot, false).map_err(|err| { BlockstoreError::Io(IoError::new( ErrorKind::Other, - format!("Unable to get block: {}", err), + format!("Unable to get block: {err}"), )) })?; @@ -2915,14 +2914,13 @@ impl Blockstore { } return Err(BlockstoreError::InvalidShredData(Box::new( bincode::ErrorKind::Custom(format!( - "Missing shred for slot {}, index {}", - slot, idx + "Missing shred for slot {slot}, index {idx}" )), ))); } Shred::new_from_serialized_shred(shred_bytes.unwrap()).map_err(|err| { BlockstoreError::InvalidShredData(Box::new(bincode::ErrorKind::Custom( - format!("Could not reconstruct shred from shred payload: {:?}", err), + format!("Could not reconstruct shred from shred payload: {err:?}"), ))) }) }) @@ -2933,16 +2931,14 @@ impl Blockstore { let deshred_payload = Shredder::deshred(&data_shreds).map_err(|e| { BlockstoreError::InvalidShredData(Box::new(bincode::ErrorKind::Custom(format!( - "Could not reconstruct data block from constituent shreds, error: {:?}", - e + "Could not reconstruct data block from constituent shreds, error: {e:?}" )))) })?; debug!("{:?} shreds in last FEC set", data_shreds.len(),); bincode::deserialize::>(&deshred_payload).map_err(|e| { BlockstoreError::InvalidShredData(Box::new(bincode::ErrorKind::Custom(format!( - "could not reconstruct entries: {:?}", - e + "could not reconstruct entries: {e:?}" )))) }) } @@ -3933,44 +3929,38 @@ pub fn create_new_ledger( fs::rename( ledger_path.join(DEFAULT_GENESIS_ARCHIVE), - ledger_path.join(format!("{}.failed", DEFAULT_GENESIS_ARCHIVE)), + ledger_path.join(format!("{DEFAULT_GENESIS_ARCHIVE}.failed")), ) .unwrap_or_else(|e| { let _ = write!( &mut error_messages, - "/failed to stash problematic {}: {}", - DEFAULT_GENESIS_ARCHIVE, e + "/failed to stash problematic {DEFAULT_GENESIS_ARCHIVE}: {e}" ); }); fs::rename( ledger_path.join(DEFAULT_GENESIS_FILE), - ledger_path.join(format!("{}.failed", DEFAULT_GENESIS_FILE)), + ledger_path.join(format!("{DEFAULT_GENESIS_FILE}.failed")), ) .unwrap_or_else(|e| { let _ = write!( &mut error_messages, - "/failed to stash problematic {}: {}", - DEFAULT_GENESIS_FILE, e + "/failed to stash problematic {DEFAULT_GENESIS_FILE}: {e}" ); }); fs::rename( ledger_path.join(blockstore_dir), - ledger_path.join(format!("{}.failed", blockstore_dir)), + ledger_path.join(format!("{blockstore_dir}.failed")), ) .unwrap_or_else(|e| { let _ = write!( &mut error_messages, - "/failed to stash problematic {}: {}", - blockstore_dir, e + "/failed to stash problematic {blockstore_dir}: {e}" ); }); return Err(BlockstoreError::Io(IoError::new( ErrorKind::Other, - format!( - "Error checking to unpack genesis archive: {}{}", - unpack_err, error_messages - ), + format!("Error checking to unpack genesis archive: {unpack_err}{error_messages}"), ))); } } @@ -8113,7 +8103,7 @@ pub mod tests { assert!(sig_infos.found_before); let results = sig_infos.infos; assert_eq!(results.len(), 1); - assert_eq!(results[0], all0[i], "Unexpected result for {}", i); + assert_eq!(results[0], all0[i], "Unexpected result for {i}"); } // Fetch all signatures for address 0 individually using `until` for i in 0..all0.len() { @@ -8136,7 +8126,7 @@ pub mod tests { .unwrap() .infos; assert_eq!(results.len(), 1); - assert_eq!(results[0], all0[i], "Unexpected result for {}", i); + assert_eq!(results[0], all0[i], "Unexpected result for {i}"); } let sig_infos = blockstore @@ -8284,7 +8274,7 @@ pub mod tests { .unwrap() .infos; assert_eq!(results.len(), 1); - assert_eq!(results[0], all0[i], "Unexpected result for {}", i); + assert_eq!(results[0], all0[i], "Unexpected result for {i}"); } // Fetch all signatures for address 0 individually using `until` for i in 0..all0.len() { @@ -8307,7 +8297,7 @@ pub mod tests { .unwrap() .infos; assert_eq!(results.len(), 1); - assert_eq!(results[0], all0[i], "Unexpected result for {}", i); + assert_eq!(results[0], all0[i], "Unexpected result for {i}"); } assert!(blockstore @@ -9546,7 +9536,7 @@ pub mod tests { // Check that each thread processed their task before continuing for _ in 1..=2 { let res = signal_receiver.recv().unwrap(); - assert!(res.is_ok(), "race condition: {:?}", res); + assert!(res.is_ok(), "race condition: {res:?}"); } } diff --git a/ledger/src/blockstore_options.rs b/ledger/src/blockstore_options.rs index c129046ff..614439c52 100644 --- a/ledger/src/blockstore_options.rs +++ b/ledger/src/blockstore_options.rs @@ -56,7 +56,7 @@ impl From<&str> for BlockstoreRecoveryMode { "absolute_consistency" => BlockstoreRecoveryMode::AbsoluteConsistency, "point_in_time" => BlockstoreRecoveryMode::PointInTime, "skip_any_corrupted_record" => BlockstoreRecoveryMode::SkipAnyCorruptedRecord, - bad_mode => panic!("Invalid recovery mode: {}", bad_mode), + bad_mode => panic!("Invalid recovery mode: {bad_mode}"), } } } diff --git a/ledger/src/blockstore_processor.rs b/ledger/src/blockstore_processor.rs index 127ae3ad9..9b8771aad 100644 --- a/ledger/src/blockstore_processor.rs +++ b/ledger/src/blockstore_processor.rs @@ -110,7 +110,7 @@ struct ReplayEntry { lazy_static! { static ref PAR_THREAD_POOL: ThreadPool = rayon::ThreadPoolBuilder::new() .num_threads(get_max_thread_count()) - .thread_name(|ix| format!("solBstoreProc{:02}", ix)) + .thread_name(|ix| format!("solBstoreProc{ix:02}")) .build() .unwrap(); } @@ -146,7 +146,7 @@ fn get_first_error( "validator_process_entry_error", ( "error", - format!("error: {:?}, transaction: {:?}", err, transaction), + format!("error: {err:?}, transaction: {transaction:?}"), String ) ); @@ -626,8 +626,7 @@ fn process_entries_with_callback( ( "error", format!( - "Lock accounts error, entry conflicts with itself, txs: {:?}", - transactions + "Lock accounts error, entry conflicts with itself, txs: {transactions:?}" ), String ) @@ -869,7 +868,7 @@ pub fn process_blockstore_from_root( let mut num_slots_processed = 0; if let Some(start_slot_meta) = blockstore .meta(start_slot) - .unwrap_or_else(|_| panic!("Failed to get meta for slot {}", start_slot)) + .unwrap_or_else(|_| panic!("Failed to get meta for slot {start_slot}")) { num_slots_processed = load_frozen_forks( bank_forks, @@ -4552,10 +4551,7 @@ pub mod tests { assert_eq!(err, expected_err); } (result, expected_result) => { - panic!( - "actual result {:?} != expected result {:?}", - result, expected_result - ); + panic!("actual result {result:?} != expected result {expected_result:?}"); } } } diff --git a/ledger/src/shredder.rs b/ledger/src/shredder.rs index 2c7dd0369..6c1e6b0b4 100644 --- a/ledger/src/shredder.rs +++ b/ledger/src/shredder.rs @@ -24,7 +24,7 @@ use { lazy_static! { static ref PAR_THREAD_POOL: ThreadPool = rayon::ThreadPoolBuilder::new() .num_threads(get_thread_count()) - .thread_name(|ix| format!("solShredder{:02}", ix)) + .thread_name(|ix| format!("solShredder{ix:02}")) .build() .unwrap(); } diff --git a/ledger/src/sigverify_shreds.rs b/ledger/src/sigverify_shreds.rs index 7f31f1d20..1064c7288 100644 --- a/ledger/src/sigverify_shreds.rs +++ b/ledger/src/sigverify_shreds.rs @@ -26,7 +26,7 @@ const SIGN_SHRED_GPU_MIN: usize = 256; lazy_static! { static ref SIGVERIFY_THREAD_POOL: ThreadPool = rayon::ThreadPoolBuilder::new() .num_threads(get_thread_count()) - .thread_name(|ix| format!("solSvrfyShred{:02}", ix)) + .thread_name(|ix| format!("solSvrfyShred{ix:02}")) .build() .unwrap(); } diff --git a/local-cluster/src/local_cluster_snapshot_utils.rs b/local-cluster/src/local_cluster_snapshot_utils.rs index bd005622c..55e6d1a9e 100644 --- a/local-cluster/src/local_cluster_snapshot_utils.rs +++ b/local-cluster/src/local_cluster_snapshot_utils.rs @@ -118,9 +118,7 @@ impl LocalCluster { if let Some(max_wait_duration) = max_wait_duration { assert!( timer.elapsed() < max_wait_duration, - "Waiting for next {:?} snapshot exceeded the {:?} maximum wait duration!", - next_snapshot_type, - max_wait_duration, + "Waiting for next {next_snapshot_type:?} snapshot exceeded the {max_wait_duration:?} maximum wait duration!", ); } sleep(Duration::from_secs(5)); diff --git a/local-cluster/tests/common.rs b/local-cluster/tests/common.rs index 8e7569a85..73f5e5fb7 100644 --- a/local-cluster/tests/common.rs +++ b/local-cluster/tests/common.rs @@ -63,7 +63,7 @@ pub fn restore_tower(tower_path: &Path, node_pubkey: &Pubkey) -> Option { if tower_err.is_file_missing() { return None; } else { - panic!("tower restore failed...: {:?}", tower_err); + panic!("tower restore failed...: {tower_err:?}"); } } // actually saved tower must have at least one vote. @@ -98,7 +98,7 @@ pub fn open_blockstore(ledger_path: &Path) -> Blockstore { }, ) .unwrap_or_else(|e| { - panic!("Failed to open ledger at {:?}, err: {}", ledger_path, e); + panic!("Failed to open ledger at {ledger_path:?}, err: {e}"); }) }) } diff --git a/local-cluster/tests/local_cluster.rs b/local-cluster/tests/local_cluster.rs index 391910f3f..fbd445339 100644 --- a/local-cluster/tests/local_cluster.rs +++ b/local-cluster/tests/local_cluster.rs @@ -1710,7 +1710,7 @@ fn test_optimistic_confirmation_violation_detection() { } sleep(Duration::from_millis(10)); } - print!("{}", output); + print!("{output}"); assert!(success); } else { panic!("dumped log and disabled testing"); @@ -2598,8 +2598,7 @@ fn test_votes_land_in_fork_during_long_partition() { // refreshing to refresh the vote on blockhash expiration for the vote // transaction. start.elapsed() <= Duration::from_millis(max_wait), - "Went too long {} ms without a root", - max_wait, + "Went too long {max_wait} ms without a root", ); let lighter_validator_blockstore = open_blockstore(&lighter_validator_ledger_path); if lighter_validator_blockstore.is_root(context.heavier_fork_slot) { diff --git a/local-cluster/tests/local_cluster_slow_2.rs b/local-cluster/tests/local_cluster_slow_2.rs index de8611081..cd1465cd6 100644 --- a/local-cluster/tests/local_cluster_slow_2.rs +++ b/local-cluster/tests/local_cluster_slow_2.rs @@ -238,7 +238,7 @@ fn test_ledger_cleanup_service() { .unwrap() .for_each(|_| slots += 1); // with 3 nodes up to 3 slots can be in progress and not complete so max slots in blockstore should be up to 103 - assert!(slots <= 103, "got {}", slots); + assert!(slots <= 103, "got {slots}"); } } diff --git a/log-analyzer/src/main.rs b/log-analyzer/src/main.rs index 280342697..baac6597f 100644 --- a/log-analyzer/src/main.rs +++ b/log-analyzer/src/main.rs @@ -188,7 +188,7 @@ fn analyze_logs(matches: &ArgMatches) { }) .unwrap_or_default(); if !diff.is_empty() { - println!("{}", diff); + println!("{diff}"); } }); } diff --git a/measure/src/measure.rs b/measure/src/measure.rs index 12ac962ae..a2999254c 100644 --- a/measure/src/measure.rs +++ b/measure/src/measure.rs @@ -88,30 +88,30 @@ mod tests { start: Instant::now(), duration: 1, }; - assert_eq!(format!("{}", measure), "test_ns took 1ns"); + assert_eq!(format!("{measure}"), "test_ns took 1ns"); let measure = Measure { name: "test_us", start: Instant::now(), duration: 1000, }; - assert_eq!(format!("{}", measure), "test_us took 1us"); + assert_eq!(format!("{measure}"), "test_us took 1us"); let measure = Measure { name: "test_ms", start: Instant::now(), duration: 1000 * 1000, }; - assert_eq!(format!("{}", measure), "test_ms took 1ms"); + assert_eq!(format!("{measure}"), "test_ms took 1ms"); let measure = Measure { name: "test_s", start: Instant::now(), duration: 1000 * 1000 * 1000, }; - assert_eq!(format!("{}", measure), "test_s took 1.0s"); + assert_eq!(format!("{measure}"), "test_s took 1.0s"); let measure = Measure::start("test_not_stopped"); - assert_eq!(format!("{}", measure), "test_not_stopped running"); + assert_eq!(format!("{measure}"), "test_not_stopped running"); } } diff --git a/merkle-root-bench/src/main.rs b/merkle-root-bench/src/main.rs index 5e15a677c..87fa93b31 100644 --- a/merkle-root-bench/src/main.rs +++ b/merkle-root-bench/src/main.rs @@ -45,7 +45,7 @@ fn main() { .collect(); for result in &elapsed { - println!("compute_merkle_root(us),{}", result); + println!("compute_merkle_root(us),{result}"); } println!( "compute_merkle_root(us) avg: {}", diff --git a/metrics/src/metrics.rs b/metrics/src/metrics.rs index 4b9b183de..7bd1eba65 100644 --- a/metrics/src/metrics.rs +++ b/metrics/src/metrics.rs @@ -98,7 +98,7 @@ pub fn serialize_points(points: &Vec, host_id: &str) -> String { for point in points { let _ = write!(line, "{},host_id={}", &point.name, host_id); for (name, value) in point.tags.iter() { - let _ = write!(line, ",{}={}", name, value); + let _ = write!(line, ",{name}={value}"); } let mut first = true; @@ -108,7 +108,7 @@ pub fn serialize_points(points: &Vec, host_id: &str) -> String { } let timestamp = point.timestamp.duration_since(UNIX_EPOCH); let nanos = timestamp.unwrap().as_nanos(); - let _ = writeln!(line, " {}", nanos); + let _ = writeln!(line, " {nanos}"); } line } @@ -390,13 +390,13 @@ impl MetricsConfig { fn get_metrics_config() -> Result { let mut config = MetricsConfig::default(); - let config_var = env::var("SOLANA_METRICS_CONFIG") - .map_err(|err| format!("SOLANA_METRICS_CONFIG: {}", err))?; + let config_var = + env::var("SOLANA_METRICS_CONFIG").map_err(|err| format!("SOLANA_METRICS_CONFIG: {err}"))?; for pair in config_var.split(',') { let nv: Vec<_> = pair.split('=').collect(); if nv.len() != 2 { - return Err(format!("SOLANA_METRICS_CONFIG is invalid: '{}'", pair)); + return Err(format!("SOLANA_METRICS_CONFIG is invalid: '{pair}'")); } let v = nv[1].to_string(); match nv[0] { @@ -404,7 +404,7 @@ fn get_metrics_config() -> Result { "db" => config.db = v, "u" => config.username = v, "p" => config.password = v, - _ => return Err(format!("SOLANA_METRICS_CONFIG is invalid: '{}'", pair)), + _ => return Err(format!("SOLANA_METRICS_CONFIG is invalid: '{pair}'")), } } diff --git a/metrics/src/poh_timing_point.rs b/metrics/src/poh_timing_point.rs index 4433fd14f..1d3f8cabb 100644 --- a/metrics/src/poh_timing_point.rs +++ b/metrics/src/poh_timing_point.rs @@ -24,9 +24,9 @@ pub enum PohTimingPoint { impl fmt::Display for PohTimingPoint { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - PohTimingPoint::PohSlotStart(t) => write!(f, "poh_start={}", t), - PohTimingPoint::PohSlotEnd(t) => write!(f, "poh_end ={}", t), - PohTimingPoint::FullSlotReceived(t) => write!(f, "poh_full ={}", t), + PohTimingPoint::PohSlotStart(t) => write!(f, "poh_start={t}"), + PohTimingPoint::PohSlotEnd(t) => write!(f, "poh_end ={t}"), + PohTimingPoint::FullSlotReceived(t) => write!(f, "poh_full ={t}"), } } } @@ -115,7 +115,7 @@ mod test { assert_eq!(p.root_slot, Some(101)); assert_eq!(p.timing_point, PohTimingPoint::PohSlotStart(100)); assert_eq!( - format!("{}", p), + format!("{p}"), "PohTimingPoint: poh_start=100, slot=100, root_slot=101" ); @@ -125,7 +125,7 @@ mod test { assert_eq!(p.root_slot, None); assert_eq!(p.timing_point, PohTimingPoint::PohSlotStart(100)); assert_eq!( - format!("{}", p), + format!("{p}"), "PohTimingPoint: poh_start=100, slot=100, root_slot=0" ); @@ -135,7 +135,7 @@ mod test { assert_eq!(p.root_slot, Some(101)); assert_eq!(p.timing_point, PohTimingPoint::PohSlotEnd(100)); assert_eq!( - format!("{}", p), + format!("{p}"), "PohTimingPoint: poh_end =100, slot=100, root_slot=101" ); @@ -145,7 +145,7 @@ mod test { assert_eq!(p.root_slot, None); assert_eq!(p.timing_point, PohTimingPoint::PohSlotEnd(100)); assert_eq!( - format!("{}", p), + format!("{p}"), "PohTimingPoint: poh_end =100, slot=100, root_slot=0" ); @@ -155,7 +155,7 @@ mod test { assert_eq!(p.root_slot, Some(101)); assert_eq!(p.timing_point, PohTimingPoint::FullSlotReceived(100)); assert_eq!( - format!("{}", p), + format!("{p}"), "PohTimingPoint: poh_full =100, slot=100, root_slot=101" ); @@ -166,7 +166,7 @@ mod test { assert_eq!(p.timing_point, PohTimingPoint::FullSlotReceived(100)); assert_eq!( - format!("{}", p), + format!("{p}"), "PohTimingPoint: poh_full =100, slot=100, root_slot=0" ); } diff --git a/net-shaper/src/main.rs b/net-shaper/src/main.rs index 2eeb0f63d..e72d8cedb 100644 --- a/net-shaper/src/main.rs +++ b/net-shaper/src/main.rs @@ -49,7 +49,7 @@ impl NetworkTopology { println!("Configure partition map (must add up to 100, e.g. [70, 20, 10]):"); let partitions_str = match io::stdin().read_line(&mut input) { Ok(_) => input, - Err(error) => panic!("error: {}", error), + Err(error) => panic!("error: {error}"), }; let partitions: Vec = serde_json::from_str(&partitions_str) @@ -59,11 +59,11 @@ impl NetworkTopology { for i in 0..partitions.len() - 1 { for j in i + 1..partitions.len() { - println!("Configure interconnect ({} <-> {}):", i, j); + println!("Configure interconnect ({i} <-> {j}):"); let mut input = String::new(); let mut interconnect_config = match io::stdin().read_line(&mut input) { Ok(_) => input, - Err(error) => panic!("error: {}", error), + Err(error) => panic!("error: {error}"), }; if interconnect_config.ends_with('\n') { @@ -121,14 +121,14 @@ impl NetworkTopology { for j in i + 1..partitions.len() { let drop_config = if max_packet_drop > 0 { let packet_drop = rng.gen_range(0, max_packet_drop + 1); - format!("loss {}% 25% ", packet_drop) + format!("loss {packet_drop}% 25% ") } else { String::default() }; let config = if max_packet_delay > 0 { let packet_delay = rng.gen_range(0, max_packet_delay + 1); - format!("{}delay {}ms 10ms", drop_config, packet_delay) + format!("{drop_config}delay {packet_delay}ms 10ms") } else { drop_config }; @@ -397,7 +397,7 @@ fn shape_network_steps( "my_index: {}, network_size: {}, partitions: {:?}", my_index, network_size, topology.partitions ); - println!("My partition is {}", my_partition); + println!("My partition is {my_partition}"); cleanup_network(interface); @@ -407,7 +407,7 @@ fn shape_network_steps( } let num_bands = topology.partitions.len() + 1; - let default_filter_class = format!("1:{}", num_bands); + let default_filter_class = format!("1:{num_bands}"); if !topology.interconnects.is_empty() { let num_bands_str = num_bands.to_string(); // Redirect ingress traffic to the virtual interface ifb0 so we can @@ -426,7 +426,7 @@ fn shape_network_steps( println!("Setting up interconnects"); for i in &topology.interconnects { if i.b as usize == my_partition { - println!("interconnects: {:#?}", i); + println!("interconnects: {i:#?}"); let tos = partition_id_to_tos(i.a as usize); if tos == 0 { println!("Incorrect value of TOS/Partition in config {}", i.a); @@ -478,7 +478,7 @@ fn configure(matches: &ArgMatches) { let topology = serde_json::to_string(&config).expect("Failed to write as JSON"); - println!("{}", topology); + println!("{topology}"); } fn main() { diff --git a/net-utils/src/bin/ip_address.rs b/net-utils/src/bin/ip_address.rs index 22990584e..227a4d783 100644 --- a/net-utils/src/bin/ip_address.rs +++ b/net-utils/src/bin/ip_address.rs @@ -14,12 +14,12 @@ fn main() { let host_port = matches.value_of("host_port").unwrap(); let addr = solana_net_utils::parse_host_port(host_port) - .unwrap_or_else(|_| panic!("failed to parse {}", host_port)); + .unwrap_or_else(|_| panic!("failed to parse {host_port}")); match solana_net_utils::get_public_ip_addr(&addr) { - Ok(ip) => println!("{}", ip), + Ok(ip) => println!("{ip}"), Err(err) => { - eprintln!("{}: {}", addr, err); + eprintln!("{addr}: {err}"); std::process::exit(1) } } diff --git a/net-utils/src/bin/ip_address_server.rs b/net-utils/src/bin/ip_address_server.rs index 0b6321617..729c99e3f 100644 --- a/net-utils/src/bin/ip_address_server.rs +++ b/net-utils/src/bin/ip_address_server.rs @@ -18,7 +18,7 @@ fn main() { let port = matches.value_of("port").unwrap(); let port = port .parse() - .unwrap_or_else(|_| panic!("Unable to parse {}", port)); + .unwrap_or_else(|_| panic!("Unable to parse {port}")); let bind_addr = SocketAddr::from(([0, 0, 0, 0], port)); let tcp_listener = TcpListener::bind(bind_addr).expect("unable to start tcp listener"); let _runtime = solana_net_utils::ip_echo_server(tcp_listener, /*shred_version=*/ None); diff --git a/net-utils/src/ip_echo_server.rs b/net-utils/src/ip_echo_server.rs index 486de5a1f..fcd5ab1a3 100644 --- a/net-utils/src/ip_echo_server.rs +++ b/net-utils/src/ip_echo_server.rs @@ -87,7 +87,7 @@ async fn process_connection( } return Err(io::Error::new( io::ErrorKind::Other, - format!("Bad request header: {}", request_header), + format!("Bad request header: {request_header}"), )); } @@ -95,7 +95,7 @@ async fn process_connection( bincode::deserialize::(&data[HEADER_LENGTH..]).map_err(|err| { io::Error::new( io::ErrorKind::Other, - format!("Failed to deserialize IpEchoServerMessage: {:?}", err), + format!("Failed to deserialize IpEchoServerMessage: {err:?}"), ) })?; diff --git a/net-utils/src/lib.rs b/net-utils/src/lib.rs index 47e296be5..7a66d502f 100644 --- a/net-utils/src/lib.rs +++ b/net-utils/src/lib.rs @@ -76,16 +76,14 @@ fn ip_echo_server_request( return Err(io::Error::new( io::ErrorKind::Other, format!( - "Invalid gossip entrypoint. {} looks to be an HTTP port: {}", - ip_echo_server_addr, http_response + "Invalid gossip entrypoint. {ip_echo_server_addr} looks to be an HTTP port: {http_response}" ), )); } return Err(io::Error::new( io::ErrorKind::Other, format!( - "Invalid gossip entrypoint. {} provided an invalid response header: '{}'", - ip_echo_server_addr, response_header + "Invalid gossip entrypoint. {ip_echo_server_addr} provided an invalid response header: '{response_header}'" ), )); } @@ -93,7 +91,7 @@ fn ip_echo_server_request( bincode::deserialize(&data[HEADER_LENGTH..]).map_err(|err| { io::Error::new( io::ErrorKind::Other, - format!("Failed to deserialize: {:?}", err), + format!("Failed to deserialize: {err:?}"), ) }) }) @@ -145,7 +143,7 @@ fn do_verify_reachable_ports( let (sender, receiver) = unbounded(); let listening_addr = tcp_listener.local_addr().unwrap(); let thread_handle = std::thread::Builder::new() - .name(format!("solVrfyTcp{:05}", port)) + .name(format!("solVrfyTcp{port:05}")) .spawn(move || { debug!("Waiting for incoming connection on tcp/{}", port); match tcp_listener.incoming().next() { @@ -227,7 +225,7 @@ fn do_verify_reachable_ports( let reachable_ports = reachable_ports.clone(); std::thread::Builder::new() - .name(format!("solVrfyUdp{:05}", port)) + .name(format!("solVrfyUdp{port:05}")) .spawn(move || { let start = Instant::now(); @@ -345,9 +343,9 @@ pub fn parse_port_range(port_range: &str) -> Option { pub fn parse_host(host: &str) -> Result { // First, check if the host syntax is valid. This check is needed because addresses // such as `("localhost:1234", 0)` will resolve to IPs on some networks. - let parsed_url = Url::parse(&format!("http://{}", host)).map_err(|e| e.to_string())?; + let parsed_url = Url::parse(&format!("http://{host}")).map_err(|e| e.to_string())?; if parsed_url.port().is_some() { - return Err(format!("Expected port in URL: {}", host)); + return Err(format!("Expected port in URL: {host}")); } // Next, check to see if it resolves to an IP address @@ -357,7 +355,7 @@ pub fn parse_host(host: &str) -> Result { .map(|socket_address| socket_address.ip()) .collect(); if ips.is_empty() { - Err(format!("Unable to resolve host: {}", host)) + Err(format!("Unable to resolve host: {host}")) } else { Ok(ips[0]) } @@ -370,10 +368,10 @@ pub fn is_host(string: String) -> Result<(), String> { pub fn parse_host_port(host_port: &str) -> Result { let addrs: Vec<_> = host_port .to_socket_addrs() - .map_err(|err| format!("Unable to resolve host {}: {}", host_port, err))? + .map_err(|err| format!("Unable to resolve host {host_port}: {err}"))? .collect(); if addrs.is_empty() { - Err(format!("Unable to resolve host: {}", host_port)) + Err(format!("Unable to resolve host: {host_port}")) } else { Ok(addrs[0]) } @@ -424,7 +422,7 @@ pub fn bind_common_in_range( Err(io::Error::new( io::ErrorKind::Other, - format!("No available TCP/UDP ports in {:?}", range), + format!("No available TCP/UDP ports in {range:?}"), )) } @@ -442,7 +440,7 @@ pub fn bind_in_range(ip_addr: IpAddr, range: PortRange) -> io::Result<(u16, UdpS Err(io::Error::new( io::ErrorKind::Other, - format!("No available UDP ports in {:?}", range), + format!("No available UDP ports in {range:?}"), )) } @@ -453,7 +451,7 @@ pub fn bind_with_any_port(ip_addr: IpAddr) -> io::Result { Ok(_) => Result::Ok(sock.into()), Err(err) => Err(io::Error::new( io::ErrorKind::Other, - format!("No available UDP port: {}", err), + format!("No available UDP port: {err}"), )), } } diff --git a/notifier/src/lib.rs b/notifier/src/lib.rs index 8a5c6b119..a36922577 100644 --- a/notifier/src/lib.rs +++ b/notifier/src/lib.rs @@ -66,7 +66,7 @@ fn get_twilio_config() -> Result, String> { for pair in config_var.unwrap().split(',') { let nv: Vec<_> = pair.split('=').collect(); if nv.len() != 2 { - return Err(format!("TWILIO_CONFIG is invalid: '{}'", pair)); + return Err(format!("TWILIO_CONFIG is invalid: '{pair}'")); } let v = nv[1].to_string(); match nv[0] { @@ -74,7 +74,7 @@ fn get_twilio_config() -> Result, String> { "TOKEN" => config.token = v, "TO" => config.to = v, "FROM" => config.from = v, - _ => return Err(format!("TWILIO_CONFIG is invalid: '{}'", pair)), + _ => return Err(format!("TWILIO_CONFIG is invalid: '{pair}'")), } } @@ -116,19 +116,19 @@ impl Notifier { let mut notifiers = vec![]; - if let Ok(webhook) = env::var(format!("{}DISCORD_WEBHOOK", env_prefix)) { + if let Ok(webhook) = env::var(format!("{env_prefix}DISCORD_WEBHOOK")) { notifiers.push(NotificationChannel::Discord(webhook)); } - if let Ok(webhook) = env::var(format!("{}SLACK_WEBHOOK", env_prefix)) { + if let Ok(webhook) = env::var(format!("{env_prefix}SLACK_WEBHOOK")) { notifiers.push(NotificationChannel::Slack(webhook)); } - if let Ok(routing_key) = env::var(format!("{}PAGERDUTY_INTEGRATION_KEY", env_prefix)) { + if let Ok(routing_key) = env::var(format!("{env_prefix}PAGERDUTY_INTEGRATION_KEY")) { notifiers.push(NotificationChannel::PagerDuty(routing_key)); } if let (Ok(bot_token), Ok(chat_id)) = ( - env::var(format!("{}TELEGRAM_BOT_TOKEN", env_prefix)), - env::var(format!("{}TELEGRAM_CHAT_ID", env_prefix)), + env::var(format!("{env_prefix}TELEGRAM_BOT_TOKEN")), + env::var(format!("{env_prefix}TELEGRAM_CHAT_ID")), ) { notifiers.push(NotificationChannel::Telegram(TelegramWebHook { bot_token, @@ -140,7 +140,7 @@ impl Notifier { notifiers.push(NotificationChannel::Twilio(webhook)); } - if let Ok(log_level) = env::var(format!("{}LOG_NOTIFIER_LEVEL", env_prefix)) { + if let Ok(log_level) = env::var(format!("{env_prefix}LOG_NOTIFIER_LEVEL")) { match Level::from_str(&log_level) { Ok(level) => notifiers.push(NotificationChannel::Log(level)), Err(e) => warn!( @@ -218,7 +218,7 @@ impl Notifier { NotificationChannel::Telegram(TelegramWebHook { chat_id, bot_token }) => { let data = json!({ "chat_id": chat_id, "text": msg }); - let url = format!("https://api.telegram.org/bot{}/sendMessage", bot_token); + let url = format!("https://api.telegram.org/bot{bot_token}/sendMessage"); if let Err(err) = self.client.post(url).json(&data).send() { warn!("Failed to send Telegram message: {:?}", err); @@ -232,8 +232,7 @@ impl Notifier { from, }) => { let url = format!( - "https://{}:{}@api.twilio.com/2010-04-01/Accounts/{}/Messages.json", - account, token, account + "https://{account}:{token}@api.twilio.com/2010-04-01/Accounts/{account}/Messages.json" ); let params = [("To", to), ("From", from), ("Body", &msg.to_string())]; if let Err(err) = self.client.post(url).form(¶ms).send() { diff --git a/perf/src/cuda_runtime.rs b/perf/src/cuda_runtime.rs index 81f466c58..6c802caa9 100644 --- a/perf/src/cuda_runtime.rs +++ b/perf/src/cuda_runtime.rs @@ -33,10 +33,7 @@ fn pin(_mem: &mut Vec) { }; assert!( err == CUDA_SUCCESS, - "cudaHostRegister error: {} ptr: {:?} bytes: {}", - err, - ptr, - size + "cudaHostRegister error: {err} ptr: {ptr:?} bytes: {size}" ); } } @@ -48,9 +45,7 @@ fn unpin(_mem: *mut T) { let err = unsafe { (api.cuda_host_unregister)(_mem as *mut c_void) }; assert!( err == CUDA_SUCCESS, - "cudaHostUnregister returned: {} ptr: {:?}", - err, - _mem + "cudaHostUnregister returned: {err} ptr: {_mem:?}" ); } } diff --git a/perf/src/sigverify.rs b/perf/src/sigverify.rs index 2ceaab2d6..af387e48d 100644 --- a/perf/src/sigverify.rs +++ b/perf/src/sigverify.rs @@ -45,7 +45,7 @@ pub const VERIFY_MIN_PACKETS_PER_THREAD: usize = 128; lazy_static! { static ref PAR_THREAD_POOL: ThreadPool = rayon::ThreadPoolBuilder::new() .num_threads(get_thread_count()) - .thread_name(|ix| format!("solSigVerify{:02}", ix)) + .thread_name(|ix| format!("solSigVerify{ix:02}")) .build() .unwrap(); } diff --git a/perf/src/thread.rs b/perf/src/thread.rs index e399929d0..6090b8de6 100644 --- a/perf/src/thread.rs +++ b/perf/src/thread.rs @@ -27,7 +27,7 @@ pub fn renice_this_thread(adjustment: i8) -> Result<(), String> { // is fixed to zero for SCHED_OTHER threads (which is the default). nice(adjustment) .map(|_| ()) - .map_err(|err| format!("Failed to change thread's nice value: {}", err)) + .map_err(|err| format!("Failed to change thread's nice value: {err}")) } /// Adds `adjustment` to the nice value of calling thread. Negative `adjustment` increases priority, diff --git a/program-runtime/src/invoke_context.rs b/program-runtime/src/invoke_context.rs index 95895693c..9dcadf57b 100644 --- a/program-runtime/src/invoke_context.rs +++ b/program-runtime/src/invoke_context.rs @@ -1053,7 +1053,7 @@ mod tests { process_instruction: mock_ix_processor, }, ]; - assert!(!format!("{:?}", builtin_programs).is_empty()); + assert!(!format!("{builtin_programs:?}").is_empty()); } #[allow(clippy::integer_arithmetic)] diff --git a/program-test/src/lib.rs b/program-test/src/lib.rs index 7df34e889..336c04363 100644 --- a/program-test/src/lib.rs +++ b/program-test/src/lib.rs @@ -289,7 +289,7 @@ impl solana_sdk::program_stubs::SyscallStubs for SyscallStubs { .set_data_from_slice(&account_info_data) .unwrap(), Err(err) if borrowed_account.get_data() != *account_info_data => { - panic!("{:?}", err); + panic!("{err:?}"); } _ => {} } @@ -545,7 +545,7 @@ impl ProgramTest { Account { lamports, data: read_file(find_file(filename).unwrap_or_else(|| { - panic!("Unable to locate {}", filename); + panic!("Unable to locate {filename}"); })), owner, executable: false, @@ -568,7 +568,7 @@ impl ProgramTest { Account { lamports, data: base64::decode(data_base64) - .unwrap_or_else(|err| panic!("Failed to base64 decode: {}", err)), + .unwrap_or_else(|err| panic!("Failed to base64 decode: {err}")), owner, executable: false, rent_epoch: 0, @@ -666,7 +666,7 @@ impl ProgramTest { } }; - let program_file = find_file(&format!("{}.so", program_name)); + let program_file = find_file(&format!("{program_name}.so")); match (self.prefer_bpf, program_file, process_instruction) { // If SBF is preferred (i.e., `test-sbf` is invoked) and a BPF shared object exists, // use that as the program data. @@ -681,18 +681,12 @@ impl ProgramTest { // Invalid: `test-sbf` invocation with no matching SBF shared object. (true, None, _) => { warn_invalid_program_name(); - panic!( - "Program file data not available for {} ({})", - program_name, program_id - ); + panic!("Program file data not available for {program_name} ({program_id})"); } // Invalid: regular `test` invocation without a processor. (false, _, None) => { - panic!( - "Program processor not available for {} ({})", - program_name, program_id - ); + panic!("Program processor not available for {program_name} ({program_id})"); } } } @@ -874,7 +868,7 @@ impl ProgramTest { .await; let banks_client = start_client(transport) .await - .unwrap_or_else(|err| panic!("Failed to start banks client: {}", err)); + .unwrap_or_else(|err| panic!("Failed to start banks client: {err}")); // Run a simulated PohService to provide the client with new blockhashes. New blockhashes // are required when sending multiple otherwise identical transactions in series from a @@ -908,7 +902,7 @@ impl ProgramTest { .await; let banks_client = start_client(transport) .await - .unwrap_or_else(|err| panic!("Failed to start banks client: {}", err)); + .unwrap_or_else(|err| panic!("Failed to start banks client: {err}")); ProgramTestContext::new( bank_forks, diff --git a/programs/bpf-loader-tests/tests/common.rs b/programs/bpf-loader-tests/tests/common.rs index e106d8b00..d2cfb7994 100644 --- a/programs/bpf-loader-tests/tests/common.rs +++ b/programs/bpf-loader-tests/tests/common.rs @@ -49,8 +49,7 @@ pub async fn assert_ix_error( .unwrap_err() .unwrap(), TransactionError::InstructionError(0, expected_err), - "{}", - assertion_failed_msg, + "{assertion_failed_msg}", ); } diff --git a/programs/bpf_loader/gen-syscall-list/build.rs b/programs/bpf_loader/gen-syscall-list/build.rs index 5bf6d8452..96af426ec 100644 --- a/programs/bpf_loader/gen-syscall-list/build.rs +++ b/programs/bpf_loader/gen-syscall-list/build.rs @@ -37,6 +37,6 @@ fn main() { let sysc_re = Regex::new(r#"register_syscall_by_name\([[:space:]]*b"([^"]+)","#).unwrap(); for caps in sysc_re.captures_iter(text) { let name = caps[1].to_string(); - writeln!(out, "{}", name).unwrap(); + writeln!(out, "{name}").unwrap(); } } diff --git a/programs/bpf_loader/src/lib.rs b/programs/bpf_loader/src/lib.rs index 268fd2829..69b80eb54 100644 --- a/programs/bpf_loader/src/lib.rs +++ b/programs/bpf_loader/src/lib.rs @@ -1377,7 +1377,7 @@ pub struct BpfExecutor { // Well, implement Debug for solana_rbpf::vm::Executable in solana-rbpf... impl Debug for BpfExecutor { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - write!(f, "BpfExecutor({:p})", self) + write!(f, "BpfExecutor({self:p})") } } diff --git a/programs/bpf_loader/src/serialization.rs b/programs/bpf_loader/src/serialization.rs index 3be548a50..46cf2a391 100644 --- a/programs/bpf_loader/src/serialization.rs +++ b/programs/bpf_loader/src/serialization.rs @@ -590,8 +590,7 @@ mod tests { assert_eq!( serialization_result.as_ref().err(), expected_err.as_ref(), - "{} test case failed", - name + "{name} test case failed" ); if expected_err.is_some() { continue; diff --git a/programs/bpf_loader/src/syscalls/logging.rs b/programs/bpf_loader/src/syscalls/logging.rs index 5af0b786f..8351a7ee6 100644 --- a/programs/bpf_loader/src/syscalls/logging.rs +++ b/programs/bpf_loader/src/syscalls/logging.rs @@ -50,10 +50,7 @@ declare_syscall!( stable_log::program_log( &invoke_context.get_log_collector(), - &format!( - "{:#x}, {:#x}, {:#x}, {:#x}, {:#x}", - arg1, arg2, arg3, arg4, arg5 - ), + &format!("{arg1:#x}, {arg2:#x}, {arg3:#x}, {arg4:#x}, {arg5:#x}"), ); Ok(0) } diff --git a/programs/stake/src/stake_state.rs b/programs/stake/src/stake_state.rs index dc1970979..1ee307714 100644 --- a/programs/stake/src/stake_state.rs +++ b/programs/stake/src/stake_state.rs @@ -1689,9 +1689,7 @@ pub fn create_lockup_stake_account( let rent_exempt_reserve = rent.minimum_balance(stake_account.data().len()); assert!( lamports >= rent_exempt_reserve, - "lamports: {} is less than rent_exempt_reserve {}", - lamports, - rent_exempt_reserve + "lamports: {lamports} is less than rent_exempt_reserve {rent_exempt_reserve}" ); stake_account diff --git a/pubsub-client/src/nonblocking/pubsub_client.rs b/pubsub-client/src/nonblocking/pubsub_client.rs index 1e091db9d..1f746bfa5 100644 --- a/pubsub-client/src/nonblocking/pubsub_client.rs +++ b/pubsub-client/src/nonblocking/pubsub_client.rs @@ -319,7 +319,7 @@ impl PubsubClient { let node_version: RpcVersionInfo = serde_json::from_value(result)?; let node_version = semver::Version::parse(&node_version.solana_core).map_err(|e| { PubsubClientError::RequestFailed { - reason: format!("failed to parse cluster version: {}", e), + reason: format!("failed to parse cluster version: {e}"), message: "getVersion".to_string(), } })?; @@ -550,7 +550,7 @@ impl PubsubClient { // Read message for subscribe Some((operation, params, response_tx)) = subscribe_rx.recv() => { request_id += 1; - let method = format!("{}Subscribe", operation); + let method = format!("{operation}Subscribe"); let text = json!({"jsonrpc":"2.0","id":request_id,"method":method,"params":params}).to_string(); ws.send(Message::Text(text)).await?; requests_subscribe.insert(request_id, (operation, response_tx)); @@ -559,7 +559,7 @@ impl PubsubClient { Some((operation, sid, response_tx)) = unsubscribe_rx.recv() => { subscriptions.remove(&sid); request_id += 1; - let method = format!("{}Unsubscribe", operation); + let method = format!("{operation}Unsubscribe"); let text = json!({"jsonrpc":"2.0","id":request_id,"method":method,"params":[sid]}).to_string(); ws.send(Message::Text(text)).await?; requests_unsubscribe.insert(request_id, response_tx); diff --git a/pubsub-client/src/pubsub_client.rs b/pubsub-client/src/pubsub_client.rs index 1f25972b0..271fbb7c8 100644 --- a/pubsub-client/src/pubsub_client.rs +++ b/pubsub-client/src/pubsub_client.rs @@ -183,8 +183,7 @@ where } // TODO: Add proper JSON RPC response/error handling... Err(PubsubClientError::UnexpectedMessageError(format!( - "{:?}", - json_msg + "{json_msg:?}" ))) } @@ -232,18 +231,14 @@ where node_version.as_str().unwrap_or_default(), ) .map_err(|e| { - PubsubClientError::RequestError(format!( - "failed to parse cluster version: {}", - e - )) + PubsubClientError::RequestError(format!("failed to parse cluster version: {e}")) })?; return Ok(node_version); } } // TODO: Add proper JSON RPC response/error handling... Err(PubsubClientError::UnexpectedMessageError(format!( - "{:?}", - json_msg + "{json_msg:?}" ))) } @@ -263,8 +258,7 @@ where // TODO: Add proper JSON RPC response/error handling... Err(PubsubClientError::UnexpectedMessageError(format!( - "{:?}", - json_msg + "{json_msg:?}" ))) } diff --git a/quic-client/src/nonblocking/quic_client.rs b/quic-client/src/nonblocking/quic_client.rs index 2def819fc..a1e1a2097 100644 --- a/quic-client/src/nonblocking/quic_client.rs +++ b/quic-client/src/nonblocking/quic_client.rs @@ -85,7 +85,7 @@ pub enum QuicError { impl From for ClientErrorKind { fn from(quic_error: QuicError) -> Self { - Self::Custom(format!("{:?}", quic_error)) + Self::Custom(format!("{quic_error:?}")) } } diff --git a/rbpf-cli/src/main.rs b/rbpf-cli/src/main.rs index abd8eb8ce..0758a8927 100644 --- a/rbpf-cli/src/main.rs +++ b/rbpf-cli/src/main.rs @@ -250,7 +250,7 @@ before execting it in the virtual machine.", let syscall_registry = register_syscalls(&invoke_context.feature_set, true).unwrap(); let executable = if magic == [0x7f, 0x45, 0x4c, 0x46] { Executable::::from_elf(&contents, config, syscall_registry) - .map_err(|err| format!("Executable constructor failed: {:?}", err)) + .map_err(|err| format!("Executable constructor failed: {err:?}")) } else { assemble::( std::str::from_utf8(contents.as_slice()).unwrap(), @@ -262,7 +262,7 @@ before execting it in the virtual machine.", let mut verified_executable = VerifiedExecutable::::from_executable(executable) - .map_err(|err| format!("Executable verifier failed: {:?}", err)) + .map_err(|err| format!("Executable verifier failed: {err:?}")) .unwrap(); verified_executable.jit_compile().unwrap(); @@ -304,7 +304,7 @@ before execting it in the virtual machine.", drop(vm); let output = Output { - result: format!("{:?}", result), + result: format!("{result:?}"), instruction_count, execution_time: duration, log: invoke_context @@ -323,7 +323,7 @@ before execting it in the virtual machine.", } _ => { println!("Program output:"); - println!("{:?}", output); + println!("{output:?}"); } } } @@ -342,7 +342,7 @@ impl Debug for Output { writeln!(f, "Instruction Count: {}", self.instruction_count)?; writeln!(f, "Execution time: {} us", self.execution_time.as_micros())?; for line in &self.log { - writeln!(f, "{}", line)?; + writeln!(f, "{line}")?; } Ok(()) } diff --git a/remote-wallet/src/ledger.rs b/remote-wallet/src/ledger.rs index b9cc80bc2..f7bf8a0ec 100644 --- a/remote-wallet/src/ledger.rs +++ b/remote-wallet/src/ledger.rs @@ -279,7 +279,7 @@ impl LedgerWallet { self.pretty_path ); let result = self.read()?; - println!("{}Approved", CHECK_MARK); + println!("{CHECK_MARK}Approved"); Ok(result) } else { self.read() @@ -633,8 +633,7 @@ pub fn get_ledger_from_info( let wallet_host_device_path = if host_device_paths.len() > 1 { let selection = Select::with_theme(&ColorfulTheme::default()) .with_prompt(&format!( - "Multiple hardware wallets found. Please select a device for {:?}", - keypair_name + "Multiple hardware wallets found. Please select a device for {keypair_name:?}" )) .default(0) .items(&items[..]) diff --git a/remote-wallet/src/locator.rs b/remote-wallet/src/locator.rs index be3aa3fec..d460554be 100644 --- a/remote-wallet/src/locator.rs +++ b/remote-wallet/src/locator.rs @@ -63,7 +63,7 @@ impl AsRef for Manufacturer { impl std::fmt::Display for Manufacturer { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { let s: &str = self.as_ref(); - write!(f, "{}", s) + write!(f, "{s}") } } @@ -108,7 +108,7 @@ impl std::fmt::Display for Locator { .unwrap(); let uri = builder.build().unwrap(); - write!(f, "{}", uri) + write!(f, "{uri}") } } @@ -344,11 +344,11 @@ mod tests { fn test_locator_new_from_path() { let manufacturer = Manufacturer::Ledger; let pubkey = Pubkey::new_unique(); - let path = format!("usb://ledger/{}?key=0/0", pubkey); + let path = format!("usb://ledger/{pubkey}?key=0/0"); Locator::new_from_path(path).unwrap(); // usb://ledger/{PUBKEY}?key=0'/0' - let path = format!("usb://ledger/{}?key=0'/0'", pubkey); + let path = format!("usb://ledger/{pubkey}?key=0'/0'"); let expect = Locator { manufacturer, pubkey: Some(pubkey), @@ -356,7 +356,7 @@ mod tests { assert_eq!(Locator::new_from_path(path), Ok(expect)); // usb://ledger/{PUBKEY} - let path = format!("usb://ledger/{}", pubkey); + let path = format!("usb://ledger/{pubkey}"); let expect = Locator { manufacturer, pubkey: Some(pubkey), diff --git a/remote-wallet/src/remote_wallet.rs b/remote-wallet/src/remote_wallet.rs index e1da0c7ba..89894c4c9 100644 --- a/remote-wallet/src/remote_wallet.rs +++ b/remote-wallet/src/remote_wallet.rs @@ -411,7 +411,7 @@ mod tests { }; assert_eq!( remote_wallet_info.get_pretty_path(), - format!("usb://ledger/{}", pubkey_str) + format!("usb://ledger/{pubkey_str}") ); } } diff --git a/rpc-client-api/src/client_error.rs b/rpc-client-api/src/client_error.rs index 4c17dea84..128f91594 100644 --- a/rpc-client-api/src/client_error.rs +++ b/rpc-client-api/src/client_error.rs @@ -59,11 +59,11 @@ impl From for TransportError { match client_error_kind { ErrorKind::Io(err) => Self::IoError(err), ErrorKind::TransactionError(err) => Self::TransactionError(err), - ErrorKind::Reqwest(err) => Self::Custom(format!("{:?}", err)), - ErrorKind::RpcError(err) => Self::Custom(format!("{:?}", err)), - ErrorKind::SerdeJson(err) => Self::Custom(format!("{:?}", err)), - ErrorKind::SigningError(err) => Self::Custom(format!("{:?}", err)), - ErrorKind::Custom(err) => Self::Custom(format!("{:?}", err)), + ErrorKind::Reqwest(err) => Self::Custom(format!("{err:?}")), + ErrorKind::RpcError(err) => Self::Custom(format!("{err:?}")), + ErrorKind::SerdeJson(err) => Self::Custom(format!("{err:?}")), + ErrorKind::SigningError(err) => Self::Custom(format!("{err:?}")), + ErrorKind::Custom(err) => Self::Custom(format!("{err:?}")), } } } diff --git a/rpc-client-api/src/custom_error.rs b/rpc-client-api/src/custom_error.rs index 483402dd4..116f5594c 100644 --- a/rpc-client-api/src/custom_error.rs +++ b/rpc-client-api/src/custom_error.rs @@ -98,8 +98,7 @@ impl From for Error { } => Self { code: ErrorCode::ServerError(JSON_RPC_SERVER_ERROR_BLOCK_CLEANED_UP), message: format!( - "Block {} cleaned up, does not exist on node. First available block: {}", - slot, first_available_block, + "Block {slot} cleaned up, does not exist on node. First available block: {first_available_block}", ), data: None, }, @@ -119,13 +118,13 @@ impl From for Error { }, RpcCustomError::BlockNotAvailable { slot } => Self { code: ErrorCode::ServerError(JSON_RPC_SERVER_ERROR_BLOCK_NOT_AVAILABLE), - message: format!("Block not available for slot {}", slot), + message: format!("Block not available for slot {slot}"), data: None, }, RpcCustomError::NodeUnhealthy { num_slots_behind } => Self { code: ErrorCode::ServerError(JSON_RPC_SERVER_ERROR_NODE_UNHEALTHY), message: if let Some(num_slots_behind) = num_slots_behind { - format!("Node is behind by {} slots", num_slots_behind) + format!("Node is behind by {num_slots_behind} slots") } else { "Node is unhealthy".to_string() }, @@ -137,14 +136,13 @@ impl From for Error { code: ErrorCode::ServerError( JSON_RPC_SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE, ), - message: format!("Transaction precompile verification failure {:?}", e), + message: format!("Transaction precompile verification failure {e:?}"), data: None, }, RpcCustomError::SlotSkipped { slot } => Self { code: ErrorCode::ServerError(JSON_RPC_SERVER_ERROR_SLOT_SKIPPED), message: format!( - "Slot {} was skipped, or missing due to ledger jump to recent snapshot", - slot + "Slot {slot} was skipped, or missing due to ledger jump to recent snapshot" ), data: None, }, @@ -155,7 +153,7 @@ impl From for Error { }, RpcCustomError::LongTermStorageSlotSkipped { slot } => Self { code: ErrorCode::ServerError(JSON_RPC_SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED), - message: format!("Slot {} was skipped, or missing in long-term storage", slot), + message: format!("Slot {slot} was skipped, or missing in long-term storage"), data: None, }, RpcCustomError::KeyExcludedFromSecondaryIndex { index_key } => Self { @@ -163,9 +161,8 @@ impl From for Error { JSON_RPC_SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX, ), message: format!( - "{} excluded from account secondary indexes; \ - this RPC method unavailable for key", - index_key + "{index_key} excluded from account secondary indexes; \ + this RPC method unavailable for key" ), data: None, }, @@ -190,16 +187,15 @@ impl From for Error { }, RpcCustomError::BlockStatusNotAvailableYet { slot } => Self { code: ErrorCode::ServerError(JSON_RPC_SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET), - message: format!("Block status not yet available for slot {}", slot), + message: format!("Block status not yet available for slot {slot}"), data: None, }, RpcCustomError::UnsupportedTransactionVersion(version) => Self { code: ErrorCode::ServerError(JSON_RPC_SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION), message: format!( - "Transaction version ({0}) is not supported by the requesting client. \ + "Transaction version ({version}) is not supported by the requesting client. \ Please try the request again with the following configuration parameter: \ - \"maxSupportedTransactionVersion\": {0}", - version + \"maxSupportedTransactionVersion\": {version}" ), data: None, }, diff --git a/rpc-client-api/src/request.rs b/rpc-client-api/src/request.rs index 07395d9ca..8980c7d1c 100644 --- a/rpc-client-api/src/request.rs +++ b/rpc-client-api/src/request.rs @@ -190,7 +190,7 @@ impl fmt::Display for RpcRequest { RpcRequest::SignVote => "signVote", }; - write!(f, "{}", method) + write!(f, "{method}") } } @@ -217,7 +217,7 @@ impl RpcRequest { json!({ "jsonrpc": jsonrpc, "id": id, - "method": format!("{}", self), + "method": format!("{self}"), "params": params, }) } diff --git a/rpc-client-api/src/response.rs b/rpc-client-api/src/response.rs index 25f62dc0f..044ccc2d6 100644 --- a/rpc-client-api/src/response.rs +++ b/rpc-client-api/src/response.rs @@ -343,7 +343,7 @@ impl fmt::Display for RpcVersionInfo { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if let Some(version) = self.solana_core.split_whitespace().next() { // Display just the semver if possible - write!(f, "{}", version) + write!(f, "{version}") } else { write!(f, "{}", self.solana_core) } diff --git a/rpc-client-api/src/version_req.rs b/rpc-client-api/src/version_req.rs index 515f85b35..8c8d57e35 100644 --- a/rpc-client-api/src/version_req.rs +++ b/rpc-client-api/src/version_req.rs @@ -8,7 +8,7 @@ impl VersionReq { let mut version_reqs = vec![]; for version in versions { let version_req = semver::VersionReq::parse(version.as_ref()) - .map_err(|err| format!("Could not parse version {:?}: {:?}", version, err))?; + .map_err(|err| format!("Could not parse version {version:?}: {err:?}"))?; version_reqs.push(version_req); } Ok(Self(version_reqs)) diff --git a/rpc-client-nonce-utils/src/blockhash_query.rs b/rpc-client-nonce-utils/src/blockhash_query.rs index 3f2b84bb3..134059a10 100644 --- a/rpc-client-nonce-utils/src/blockhash_query.rs +++ b/rpc-client-nonce-utils/src/blockhash_query.rs @@ -146,7 +146,7 @@ impl BlockhashQuery { #[allow(deprecated)] let fee_calculator = source .get_fee_calculator(rpc_client, hash, commitment)? - .ok_or(format!("Hash has expired {:?}", hash))?; + .ok_or(format!("Hash has expired {hash:?}"))?; Ok((*hash, fee_calculator)) } BlockhashQuery::All(source) => @@ -166,7 +166,7 @@ impl BlockhashQuery { BlockhashQuery::None(hash) => Ok(*hash), BlockhashQuery::FeeCalculator(source, hash) => { if !source.is_blockhash_valid(rpc_client, hash, commitment)? { - return Err(format!("Hash has expired {:?}", hash).into()); + return Err(format!("Hash has expired {hash:?}").into()); } Ok(*hash) } diff --git a/rpc-client-nonce-utils/src/lib.rs b/rpc-client-nonce-utils/src/lib.rs index f03570a6b..d1dc0b691 100644 --- a/rpc-client-nonce-utils/src/lib.rs +++ b/rpc-client-nonce-utils/src/lib.rs @@ -35,11 +35,11 @@ pub fn get_account_with_commitment( ) -> Result { rpc_client .get_account_with_commitment(nonce_pubkey, commitment) - .map_err(|e| Error::Client(format!("{}", e))) + .map_err(|e| Error::Client(format!("{e}"))) .and_then(|result| { result .value - .ok_or_else(|| Error::Client(format!("AccountNotFound: pubkey={}", nonce_pubkey))) + .ok_or_else(|| Error::Client(format!("AccountNotFound: pubkey={nonce_pubkey}"))) }) .and_then(|a| account_identity_ok(&a).map(|()| a)) } diff --git a/rpc-client-nonce-utils/src/nonblocking/blockhash_query.rs b/rpc-client-nonce-utils/src/nonblocking/blockhash_query.rs index 881f2b2d0..2b42f4ed3 100644 --- a/rpc-client-nonce-utils/src/nonblocking/blockhash_query.rs +++ b/rpc-client-nonce-utils/src/nonblocking/blockhash_query.rs @@ -97,7 +97,7 @@ impl BlockhashQuery { .is_blockhash_valid(rpc_client, hash, commitment) .await? { - return Err(format!("Hash has expired {:?}", hash).into()); + return Err(format!("Hash has expired {hash:?}").into()); } Ok(*hash) } diff --git a/rpc-client-nonce-utils/src/nonblocking/mod.rs b/rpc-client-nonce-utils/src/nonblocking/mod.rs index 4b8b0893d..fceeacf6f 100644 --- a/rpc-client-nonce-utils/src/nonblocking/mod.rs +++ b/rpc-client-nonce-utils/src/nonblocking/mod.rs @@ -61,11 +61,11 @@ pub async fn get_account_with_commitment( rpc_client .get_account_with_commitment(nonce_pubkey, commitment) .await - .map_err(|e| Error::Client(format!("{}", e))) + .map_err(|e| Error::Client(format!("{e}"))) .and_then(|result| { result .value - .ok_or_else(|| Error::Client(format!("AccountNotFound: pubkey={}", nonce_pubkey))) + .ok_or_else(|| Error::Client(format!("AccountNotFound: pubkey={nonce_pubkey}"))) }) .and_then(|a| account_identity_ok(&a).map(|()| a)) } diff --git a/rpc-client/src/nonblocking/rpc_client.rs b/rpc-client/src/nonblocking/rpc_client.rs index a1b4f0086..3bf4462ea 100644 --- a/rpc-client/src/nonblocking/rpc_client.rs +++ b/rpc-client/src/nonblocking/rpc_client.rs @@ -522,10 +522,10 @@ impl RpcClient { drop(r_node_version); let mut w_node_version = self.node_version.write().await; let node_version = self.get_version().await.map_err(|e| { - RpcError::RpcRequestError(format!("cluster version query failed: {}", e)) + RpcError::RpcRequestError(format!("cluster version query failed: {e}")) })?; let node_version = semver::Version::parse(&node_version.solana_core).map_err(|e| { - RpcError::RpcRequestError(format!("failed to parse cluster version: {}", e)) + RpcError::RpcRequestError(format!("failed to parse cluster version: {e}")) })?; *w_node_version = Some(node_version.clone()); Ok(node_version) @@ -1150,8 +1150,7 @@ impl RpcClient { let progress_bar = spinner::new_progress_bar(); progress_bar.set_message(format!( - "[{}/{}] Finalizing transaction {}", - confirmations, desired_confirmations, signature, + "[{confirmations}/{desired_confirmations}] Finalizing transaction {signature}", )); let now = Instant::now(); @@ -1986,11 +1985,8 @@ impl RpcClient { .iter() .map(|slot_leader| { Pubkey::from_str(slot_leader).map_err(|err| { - ClientErrorKind::Custom(format!( - "pubkey deserialization failed: {}", - err - )) - .into() + ClientErrorKind::Custom(format!("pubkey deserialization failed: {err}")) + .into() }) }) .collect() @@ -3289,7 +3285,7 @@ impl RpcClient { response .map(|result_json: Value| { if result_json.is_null() { - return Err(RpcError::ForUser(format!("Block Not Found: slot={}", slot)).into()); + return Err(RpcError::ForUser(format!("Block Not Found: slot={slot}")).into()); } let result = serde_json::from_value(result_json) .map_err(|err| ClientError::new_with_request(err.into(), request))?; @@ -3785,7 +3781,7 @@ impl RpcClient { self.get_account_with_commitment(pubkey, self.commitment()) .await? .value - .ok_or_else(|| RpcError::ForUser(format!("AccountNotFound: pubkey={}", pubkey)).into()) + .ok_or_else(|| RpcError::ForUser(format!("AccountNotFound: pubkey={pubkey}")).into()) } /// Returns all information associated with the account of the provided pubkey. @@ -3908,7 +3904,7 @@ impl RpcClient { .map(|result_json: Value| { if result_json.is_null() { return Err( - RpcError::ForUser(format!("AccountNotFound: pubkey={}", pubkey)).into(), + RpcError::ForUser(format!("AccountNotFound: pubkey={pubkey}")).into(), ); } let Response { @@ -3925,8 +3921,7 @@ impl RpcClient { }) .map_err(|err| { Into::::into(RpcError::ForUser(format!( - "AccountNotFound: pubkey={}: {}", - pubkey, err + "AccountNotFound: pubkey={pubkey}: {err}" ))) })? } @@ -4780,7 +4775,7 @@ impl RpcClient { .map(|result_json: Value| { if result_json.is_null() { return Err( - RpcError::ForUser(format!("AccountNotFound: pubkey={}", pubkey)).into(), + RpcError::ForUser(format!("AccountNotFound: pubkey={pubkey}")).into(), ); } let Response { @@ -4802,16 +4797,14 @@ impl RpcClient { } } Err(Into::::into(RpcError::ForUser(format!( - "Account could not be parsed as token account: pubkey={}", - pubkey + "Account could not be parsed as token account: pubkey={pubkey}" )))) }; response? }) .map_err(|err| { Into::::into(RpcError::ForUser(format!( - "AccountNotFound: pubkey={}: {}", - pubkey, err + "AccountNotFound: pubkey={pubkey}: {err}" ))) })? } @@ -5017,7 +5010,7 @@ impl RpcClient { .await .and_then(|signature: String| { Signature::from_str(&signature).map_err(|err| { - ClientErrorKind::Custom(format!("signature deserialization failed: {}", err)).into() + ClientErrorKind::Custom(format!("signature deserialization failed: {err}")).into() }) }) .map_err(|_| { @@ -5343,14 +5336,13 @@ where T: serde::ser::Serialize, { let serialized = serialize(input) - .map_err(|e| ClientErrorKind::Custom(format!("Serialization failed: {}", e)))?; + .map_err(|e| ClientErrorKind::Custom(format!("Serialization failed: {e}")))?; let encoded = match encoding { UiTransactionEncoding::Base58 => bs58::encode(serialized).into_string(), UiTransactionEncoding::Base64 => base64::encode(serialized), _ => { return Err(ClientErrorKind::Custom(format!( - "unsupported encoding: {}. Supported encodings: base58, base64", - encoding + "unsupported encoding: {encoding}. Supported encodings: base58, base64" )) .into()) } @@ -5360,9 +5352,9 @@ where pub(crate) fn get_rpc_request_str(rpc_addr: SocketAddr, tls: bool) -> String { if tls { - format!("https://{}", rpc_addr) + format!("https://{rpc_addr}") } else { - format!("http://{}", rpc_addr) + format!("http://{rpc_addr}") } } diff --git a/rpc/src/optimistically_confirmed_bank_tracker.rs b/rpc/src/optimistically_confirmed_bank_tracker.rs index 9caedb810..6495f4470 100644 --- a/rpc/src/optimistically_confirmed_bank_tracker.rs +++ b/rpc/src/optimistically_confirmed_bank_tracker.rs @@ -42,7 +42,7 @@ impl std::fmt::Debug for BankNotification { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { BankNotification::OptimisticallyConfirmed(slot) => { - write!(f, "OptimisticallyConfirmed({:?})", slot) + write!(f, "OptimisticallyConfirmed({slot:?})") } BankNotification::Frozen(bank) => write!(f, "Frozen({})", bank.slot()), BankNotification::Root(bank) => write!(f, "Root({})", bank.slot()), diff --git a/rpc/src/rpc.rs b/rpc/src/rpc.rs index 5d1ac664b..8779409f6 100644 --- a/rpc/src/rpc.rs +++ b/rpc/src/rpc.rs @@ -820,8 +820,7 @@ impl JsonRpcRequestProcessor { ); } else { return Err(Error::invalid_params(format!( - "Invalid slot range: leader schedule for epoch {} is unavailable", - epoch + "Invalid slot range: leader schedule for epoch {epoch} is unavailable" ))); } @@ -1226,8 +1225,7 @@ impl JsonRpcRequestProcessor { } if end_slot - start_slot > MAX_GET_CONFIRMED_BLOCKS_RANGE { return Err(Error::invalid_params(format!( - "Slot range too large; max {}", - MAX_GET_CONFIRMED_BLOCKS_RANGE + "Slot range too large; max {MAX_GET_CONFIRMED_BLOCKS_RANGE}" ))); } @@ -1293,8 +1291,7 @@ impl JsonRpcRequestProcessor { if limit > MAX_GET_CONFIRMED_BLOCKS_RANGE as usize { return Err(Error::invalid_params(format!( - "Limit too large; max {}", - MAX_GET_CONFIRMED_BLOCKS_RANGE + "Limit too large; max {MAX_GET_CONFIRMED_BLOCKS_RANGE}" ))); } @@ -1642,7 +1639,7 @@ impl JsonRpcRequestProcessor { } = self .blockstore .get_confirmed_signatures_for_address2(address, highest_slot, before, until, limit) - .map_err(|err| Error::invalid_params(format!("{}", err)))?; + .map_err(|err| Error::invalid_params(format!("{err}")))?; let map_results = |results: Vec| { results @@ -1763,14 +1760,12 @@ impl JsonRpcRequestProcessor { let epoch = config.epoch.unwrap_or_else(|| bank.epoch()); if bank.epoch().saturating_sub(epoch) > solana_sdk::stake_history::MAX_ENTRIES as u64 { return Err(Error::invalid_params(format!( - "Invalid param: epoch {:?} is too far in the past", - epoch + "Invalid param: epoch {epoch:?} is too far in the past" ))); } if epoch > bank.epoch() { return Err(Error::invalid_params(format!( - "Invalid param: epoch {:?} has not yet started", - epoch + "Invalid param: epoch {epoch:?} has not yet started" ))); } @@ -2260,25 +2255,25 @@ fn verify_transaction( fn verify_filter(input: &RpcFilterType) -> Result<()> { input .verify() - .map_err(|e| Error::invalid_params(format!("Invalid param: {:?}", e))) + .map_err(|e| Error::invalid_params(format!("Invalid param: {e:?}"))) } fn verify_pubkey(input: &str) -> Result { input .parse() - .map_err(|e| Error::invalid_params(format!("Invalid param: {:?}", e))) + .map_err(|e| Error::invalid_params(format!("Invalid param: {e:?}"))) } fn verify_hash(input: &str) -> Result { input .parse() - .map_err(|e| Error::invalid_params(format!("Invalid param: {:?}", e))) + .map_err(|e| Error::invalid_params(format!("Invalid param: {e:?}"))) } fn verify_signature(input: &str) -> Result { input .parse() - .map_err(|e| Error::invalid_params(format!("Invalid param: {:?}", e))) + .map_err(|e| Error::invalid_params(format!("Invalid param: {e:?}"))) } fn verify_token_account_filter( @@ -2311,8 +2306,7 @@ fn verify_and_parse_signatures_for_address_params( if limit == 0 || limit > MAX_GET_CONFIRMED_SIGNATURES_FOR_ADDRESS2_LIMIT { return Err(Error::invalid_params(format!( - "Invalid limit; max {}", - MAX_GET_CONFIRMED_SIGNATURES_FOR_ADDRESS2_LIMIT + "Invalid limit; max {MAX_GET_CONFIRMED_SIGNATURES_FOR_ADDRESS2_LIMIT}" ))); } Ok((address, before, until, limit)) @@ -2357,7 +2351,7 @@ fn encode_account( if (encoding == UiAccountEncoding::Binary || encoding == UiAccountEncoding::Base58) && account.data().len() > MAX_BASE58_BYTES { - let message = format!("Encoded binary (base 58) data should be less than {} bytes, please use Base64 encoding.", MAX_BASE58_BYTES); + let message = format!("Encoded binary (base 58) data should be less than {MAX_BASE58_BYTES} bytes, please use Base64 encoding."); Err(error::Error { code: error::ErrorCode::InvalidRequest, message, @@ -2887,8 +2881,7 @@ pub mod rpc_bank { let limit = limit as usize; if limit > MAX_GET_SLOT_LEADERS { return Err(Error::invalid_params(format!( - "Invalid limit; max {}", - MAX_GET_SLOT_LEADERS + "Invalid limit; max {MAX_GET_SLOT_LEADERS}" ))); } @@ -2924,8 +2917,7 @@ pub mod rpc_bank { let last_slot = range.last_slot.unwrap_or_else(|| bank.slot()); if last_slot < first_slot { return Err(Error::invalid_params(format!( - "lastSlot, {}, cannot be less than firstSlot, {}", - last_slot, first_slot + "lastSlot, {last_slot}, cannot be less than firstSlot, {first_slot}" ))); } (first_slot, last_slot) @@ -3082,8 +3074,7 @@ pub mod rpc_accounts { .unwrap_or(MAX_MULTIPLE_ACCOUNTS); if pubkey_strs.len() > max_multiple_accounts { return Err(Error::invalid_params(format!( - "Too many inputs provided; max {}", - max_multiple_accounts + "Too many inputs provided; max {max_multiple_accounts}" ))); } let pubkeys = pubkey_strs @@ -3241,8 +3232,7 @@ pub mod rpc_accounts_scan { }; if filters.len() > MAX_GET_PROGRAM_ACCOUNT_FILTERS { return Err(Error::invalid_params(format!( - "Too many filters provided; max {}", - MAX_GET_PROGRAM_ACCOUNT_FILTERS + "Too many filters provided; max {MAX_GET_PROGRAM_ACCOUNT_FILTERS}" ))); } for filter in &filters { @@ -3507,8 +3497,7 @@ pub mod rpc_full { if limit > PERFORMANCE_SAMPLES_LIMIT { return Err(Error::invalid_params(format!( - "Invalid limit; max {}", - PERFORMANCE_SAMPLES_LIMIT + "Invalid limit; max {PERFORMANCE_SAMPLES_LIMIT}" ))); } @@ -3583,8 +3572,7 @@ pub mod rpc_full { ); if signature_strs.len() > MAX_GET_SIGNATURE_STATUSES_QUERY_ITEMS { return Box::pin(future::err(Error::invalid_params(format!( - "Too many inputs provided; max {}", - MAX_GET_SIGNATURE_STATUSES_QUERY_ITEMS + "Too many inputs provided; max {MAX_GET_SIGNATURE_STATUSES_QUERY_ITEMS}" )))); } let mut signatures: Vec = vec![]; @@ -3685,8 +3673,7 @@ pub mod rpc_full { let tx_encoding = encoding.unwrap_or(UiTransactionEncoding::Base58); let binary_encoding = tx_encoding.into_binary_encoding().ok_or_else(|| { Error::invalid_params(format!( - "unsupported encoding: {}. Supported encodings: base58, base64", - tx_encoding + "unsupported encoding: {tx_encoding}. Supported encodings: base58, base64" )) })?; let (wire_transaction, unsanitized_tx) = @@ -3756,7 +3743,7 @@ pub mod rpc_full { } } return Err(RpcCustomError::SendTransactionPreflightFailure { - message: format!("Transaction simulation failed: {}", err), + message: format!("Transaction simulation failed: {err}"), result: RpcSimulateTransactionResult { err: Some(err), logs: Some(logs), @@ -3797,8 +3784,7 @@ pub mod rpc_full { let tx_encoding = encoding.unwrap_or(UiTransactionEncoding::Base58); let binary_encoding = tx_encoding.into_binary_encoding().ok_or_else(|| { Error::invalid_params(format!( - "unsupported encoding: {}. Supported encodings: base58, base64", - tx_encoding + "unsupported encoding: {tx_encoding}. Supported encodings: base58, base64" )) })?; let (_, mut unsanitized_tx) = @@ -3846,8 +3832,7 @@ pub mod rpc_full { if config_accounts.addresses.len() > number_of_accounts { return Err(Error::invalid_params(format!( - "Too many accounts provided; max {}", - number_of_accounts + "Too many accounts provided; max {number_of_accounts}" ))); } @@ -4038,8 +4023,8 @@ pub mod rpc_full { blockhash: String, config: Option, ) -> Result> { - let blockhash = Hash::from_str(&blockhash) - .map_err(|e| Error::invalid_params(format!("{:?}", e)))?; + let blockhash = + Hash::from_str(&blockhash).map_err(|e| Error::invalid_params(format!("{e:?}")))?; meta.is_blockhash_valid(&blockhash, config.unwrap_or_default()) } @@ -4057,11 +4042,11 @@ pub mod rpc_full { let bank = &*meta.get_bank_with_config(config.unwrap_or_default())?; let sanitized_versioned_message = SanitizedVersionedMessage::try_from(message) .map_err(|err| { - Error::invalid_params(format!("invalid transaction message: {}", err)) + Error::invalid_params(format!("invalid transaction message: {err}")) })?; let sanitized_message = SanitizedMessage::try_new(sanitized_versioned_message, bank) .map_err(|err| { - Error::invalid_params(format!("invalid transaction message: {}", err)) + Error::invalid_params(format!("invalid transaction message: {err}")) })?; let fee = bank.get_fee_for_message(&sanitized_message); Ok(new_response(bank, fee)) @@ -4088,8 +4073,7 @@ pub mod rpc_full { ); if pubkey_strs.len() > MAX_TX_ACCOUNT_LOCKS { return Err(Error::invalid_params(format!( - "Too many inputs provided; max {}", - MAX_TX_ACCOUNT_LOCKS + "Too many inputs provided; max {MAX_TX_ACCOUNT_LOCKS}" ))); } let pubkeys = pubkey_strs @@ -4170,8 +4154,8 @@ pub mod rpc_deprecated_v1_9 { commitment: Option, ) -> Result>> { debug!("get_fee_calculator_for_blockhash rpc request received"); - let blockhash = Hash::from_str(&blockhash) - .map_err(|e| Error::invalid_params(format!("{:?}", e)))?; + let blockhash = + Hash::from_str(&blockhash).map_err(|e| Error::invalid_params(format!("{e:?}")))?; meta.get_fee_calculator_for_blockhash(&blockhash, commitment) } @@ -4480,14 +4464,12 @@ pub mod rpc_obsolete_v1_7 { let pubkey = verify_pubkey(&pubkey_str)?; if end_slot < start_slot { return Err(Error::invalid_params(format!( - "start_slot {} must be less than or equal to end_slot {}", - start_slot, end_slot + "start_slot {start_slot} must be less than or equal to end_slot {end_slot}" ))); } if end_slot - start_slot > MAX_GET_CONFIRMED_SIGNATURES_FOR_ADDRESS_SLOT_RANGE { return Err(Error::invalid_params(format!( - "Slot range too large; max {}", - MAX_GET_CONFIRMED_SIGNATURES_FOR_ADDRESS_SLOT_RANGE + "Slot range too large; max {MAX_GET_CONFIRMED_SIGNATURES_FOR_ADDRESS_SLOT_RANGE}" ))); } Ok(meta @@ -4522,7 +4504,7 @@ where } bs58::decode(encoded) .into_vec() - .map_err(|e| Error::invalid_params(format!("invalid base58 encoding: {:?}", e)))? + .map_err(|e| Error::invalid_params(format!("invalid base58 encoding: {e:?}")))? } TransactionBinaryEncoding::Base64 => { inc_new_counter_info!("rpc-base64_encoded_tx", 1); @@ -4536,7 +4518,7 @@ where ))); } base64::decode(encoded) - .map_err(|e| Error::invalid_params(format!("invalid base64 encoding: {:?}", e)))? + .map_err(|e| Error::invalid_params(format!("invalid base64 encoding: {e:?}")))? } }; if wire_output.len() > PACKET_DATA_SIZE { @@ -4573,7 +4555,7 @@ fn sanitize_transaction( address_loader, true, // require_static_program_ids ) - .map_err(|err| Error::invalid_params(format!("invalid transaction: {}", err))) + .map_err(|err| Error::invalid_params(format!("invalid transaction: {err}"))) } pub(crate) fn create_validator_exit(exit: &Arc) -> Arc> { @@ -4767,7 +4749,7 @@ pub mod tests { match output { Output::Success(success) => serde_json::from_value(success.result).unwrap(), Output::Failure(failure) => { - panic!("Expected success but received: {:?}", failure); + panic!("Expected success but received: {failure:?}"); } } } else { @@ -4779,7 +4761,7 @@ pub mod tests { if let Response::Single(output) = response { match output { Output::Success(success) => { - panic!("Expected failure but received: {:?}", success); + panic!("Expected failure but received: {success:?}"); } Output::Failure(failure) => (failure.error.code.code(), failure.error.message), } @@ -5135,8 +5117,7 @@ pub mod tests { io.extend_with(rpc_minimal::MinimalImpl.to_delegate()); let req = format!( - r#"{{"jsonrpc":"2.0","id":1,"method":"getBalance","params":["{}"]}}"#, - mint_pubkey + r#"{{"jsonrpc":"2.0","id":1,"method":"getBalance","params":["{mint_pubkey}"]}}"# ); let res = io.handle_request_sync(&req, meta); let expected = json!({ @@ -5962,7 +5943,7 @@ pub mod tests { "id":1, "method":"simulateTransaction", "params":[ - "{}", + "{tx_serialized_encoded}", {{ "sigVerify": true, "accounts": {{ @@ -5976,7 +5957,6 @@ pub mod tests { }} ] }}"#, - tx_serialized_encoded, ); let res = io.handle_request_sync(&req, meta.clone()); let expected = json!({ @@ -5995,8 +5975,7 @@ pub mod tests { // Bad signature with sigVerify=true let req = format!( - r#"{{"jsonrpc":"2.0","id":1,"method":"simulateTransaction","params":["{}", {{"sigVerify": true}}]}}"#, - tx_badsig_serialized_encoded, + r#"{{"jsonrpc":"2.0","id":1,"method":"simulateTransaction","params":["{tx_badsig_serialized_encoded}", {{"sigVerify": true}}]}}"#, ); let res = io.handle_request_sync(&req, meta.clone()); let expected = json!({ @@ -6016,8 +5995,7 @@ pub mod tests { // Bad signature with sigVerify=false let req = format!( - r#"{{"jsonrpc":"2.0","id":1,"method":"simulateTransaction","params":["{}", {{"sigVerify": false}}]}}"#, - tx_serialized_encoded, + r#"{{"jsonrpc":"2.0","id":1,"method":"simulateTransaction","params":["{tx_serialized_encoded}", {{"sigVerify": false}}]}}"#, ); let res = io.handle_request_sync(&req, meta.clone()); let expected = json!({ @@ -6045,8 +6023,7 @@ pub mod tests { // Bad signature with default sigVerify setting (false) let req = format!( - r#"{{"jsonrpc":"2.0","id":1,"method":"simulateTransaction","params":["{}"]}}"#, - tx_serialized_encoded, + r#"{{"jsonrpc":"2.0","id":1,"method":"simulateTransaction","params":["{tx_serialized_encoded}"]}}"#, ); let res = io.handle_request_sync(&req, meta.clone()); let expected = json!({ @@ -6098,8 +6075,7 @@ pub mod tests { // Bad recent blockhash with replaceRecentBlockhash=false let req = format!( - r#"{{"jsonrpc":"2.0","id":1,"method":"simulateTransaction","params":["{}", {{"replaceRecentBlockhash": false}}]}}"#, - tx_invalid_recent_blockhash, + r#"{{"jsonrpc":"2.0","id":1,"method":"simulateTransaction","params":["{tx_invalid_recent_blockhash}", {{"replaceRecentBlockhash": false}}]}}"#, ); let res = io.handle_request_sync(&req, meta.clone()); let expected = json!({ @@ -6125,8 +6101,7 @@ pub mod tests { // Bad recent blockhash with replaceRecentBlockhash=true let req = format!( - r#"{{"jsonrpc":"2.0","id":1,"method":"simulateTransaction","params":["{}", {{"replaceRecentBlockhash": true}}]}}"#, - tx_invalid_recent_blockhash, + r#"{{"jsonrpc":"2.0","id":1,"method":"simulateTransaction","params":["{tx_invalid_recent_blockhash}", {{"replaceRecentBlockhash": true}}]}}"#, ); let res = io.handle_request_sync(&req, meta.clone()); let expected = json!({ @@ -6174,8 +6149,7 @@ pub mod tests { assert!(!bank.is_frozen()); let req = format!( - r#"{{"jsonrpc":"2.0","id":1,"method":"simulateTransaction","params":["{}", {{"sigVerify": true}}]}}"#, - tx_serialized_encoded, + r#"{{"jsonrpc":"2.0","id":1,"method":"simulateTransaction","params":["{tx_serialized_encoded}", {{"sigVerify": true}}]}}"#, ); // should panic because `bank` is not frozen @@ -6332,8 +6306,7 @@ pub mod tests { }; let req = format!( - r#"{{"jsonrpc":"2.0","id":1,"method":"getFeeCalculatorForBlockhash","params":["{:?}"]}}"#, - recent_blockhash + r#"{{"jsonrpc":"2.0","id":1,"method":"getFeeCalculatorForBlockhash","params":["{recent_blockhash:?}"]}}"# ); let res = io.handle_request_sync(&req, meta.clone()); let expected = json!({ @@ -6407,8 +6380,7 @@ pub mod tests { // Expect internal error because no faucet is available let bob_pubkey = solana_sdk::pubkey::new_rand(); let req = format!( - r#"{{"jsonrpc":"2.0","id":1,"method":"requestAirdrop","params":["{}", 50]}}"#, - bob_pubkey + r#"{{"jsonrpc":"2.0","id":1,"method":"requestAirdrop","params":["{bob_pubkey}", 50]}}"# ); let res = io.handle_request_sync(&req, meta); let expected = @@ -7501,8 +7473,7 @@ pub mod tests { if !secondary_index_enabled { // Test first with no accounts added & no secondary indexes enabled: let req = format!( - r#"{{"jsonrpc":"2.0","id":1,"method":"getSecondaryIndexKeySize","params":["{}"]}}"#, - token_account1_pubkey, + r#"{{"jsonrpc":"2.0","id":1,"method":"getSecondaryIndexKeySize","params":["{token_account1_pubkey}"]}}"#, ); let res = io.handle_request_sync(&req, meta.clone()); let result: Value = serde_json::from_str(&res.expect("actual response")) @@ -7671,8 +7642,7 @@ pub mod tests { if secondary_index_enabled { // ----------- Test for a non-existant key ----------- let req = format!( - r#"{{"jsonrpc":"2.0","id":1,"method":"getSecondaryIndexKeySize","params":["{}"]}}"#, - non_existent_pubkey, + r#"{{"jsonrpc":"2.0","id":1,"method":"getSecondaryIndexKeySize","params":["{non_existent_pubkey}"]}}"#, ); let res = io.handle_request_sync(&req, meta.clone()); let result: Value = serde_json::from_str(&res.expect("actual response")) @@ -7683,8 +7653,7 @@ pub mod tests { // --------------- Test Queries --------------- // 1) Wallet1 - Owns 1 SPL Token let req = format!( - r#"{{"jsonrpc":"2.0","id":1,"method":"getSecondaryIndexKeySize","params":["{}"]}}"#, - wallet1_pubkey, + r#"{{"jsonrpc":"2.0","id":1,"method":"getSecondaryIndexKeySize","params":["{wallet1_pubkey}"]}}"#, ); let res = io.handle_request_sync(&req, meta.clone()); let result: Value = serde_json::from_str(&res.expect("actual response")) @@ -7695,8 +7664,7 @@ pub mod tests { assert_eq!(*sizes.get(&RpcAccountIndex::SplTokenOwner).unwrap(), 1); // 2) Wallet2 - Owns 2 SPL Tokens let req = format!( - r#"{{"jsonrpc":"2.0","id":1,"method":"getSecondaryIndexKeySize","params":["{}"]}}"#, - wallet2_pubkey, + r#"{{"jsonrpc":"2.0","id":1,"method":"getSecondaryIndexKeySize","params":["{wallet2_pubkey}"]}}"#, ); let res = io.handle_request_sync(&req, meta.clone()); let result: Value = serde_json::from_str(&res.expect("actual response")) @@ -7707,8 +7675,7 @@ pub mod tests { assert_eq!(*sizes.get(&RpcAccountIndex::SplTokenOwner).unwrap(), 2); // 3) Mint1 - Is in 2 SPL Accounts let req = format!( - r#"{{"jsonrpc":"2.0","id":1,"method":"getSecondaryIndexKeySize","params":["{}"]}}"#, - mint1_pubkey, + r#"{{"jsonrpc":"2.0","id":1,"method":"getSecondaryIndexKeySize","params":["{mint1_pubkey}"]}}"#, ); let res = io.handle_request_sync(&req, meta.clone()); let result: Value = serde_json::from_str(&res.expect("actual response")) @@ -7719,8 +7686,7 @@ pub mod tests { assert_eq!(*sizes.get(&RpcAccountIndex::SplTokenMint).unwrap(), 2); // 4) Mint2 - Is in 1 SPL Account let req = format!( - r#"{{"jsonrpc":"2.0","id":1,"method":"getSecondaryIndexKeySize","params":["{}"]}}"#, - mint2_pubkey, + r#"{{"jsonrpc":"2.0","id":1,"method":"getSecondaryIndexKeySize","params":["{mint2_pubkey}"]}}"#, ); let res = io.handle_request_sync(&req, meta.clone()); let result: Value = serde_json::from_str(&res.expect("actual response")) @@ -7762,8 +7728,7 @@ pub mod tests { } else { // ------------ Secondary Indexes Disabled ------------ let req = format!( - r#"{{"jsonrpc":"2.0","id":1,"method":"getSecondaryIndexKeySize","params":["{}"]}}"#, - token_account2_pubkey, + r#"{{"jsonrpc":"2.0","id":1,"method":"getSecondaryIndexKeySize","params":["{token_account2_pubkey}"]}}"#, ); let res = io.handle_request_sync(&req, meta.clone()); let result: Value = serde_json::from_str(&res.expect("actual response")) @@ -7947,8 +7912,7 @@ pub mod tests { } let req = format!( - r#"{{"jsonrpc":"2.0","id":1,"method":"getTokenAccountBalance","params":["{}"]}}"#, - token_account_pubkey, + r#"{{"jsonrpc":"2.0","id":1,"method":"getTokenAccountBalance","params":["{token_account_pubkey}"]}}"#, ); let res = io.handle_request_sync(&req, meta.clone()); let result: Value = serde_json::from_str(&res.expect("actual response")) @@ -7973,8 +7937,7 @@ pub mod tests { // Test get token supply, pulls supply from mint let req = format!( - r#"{{"jsonrpc":"2.0","id":1,"method":"getTokenSupply","params":["{}"]}}"#, - mint, + r#"{{"jsonrpc":"2.0","id":1,"method":"getTokenSupply","params":["{mint}"]}}"#, ); let res = io.handle_request_sync(&req, meta.clone()); let result: Value = serde_json::from_str(&res.expect("actual response")) @@ -8003,9 +7966,8 @@ pub mod tests { "jsonrpc":"2.0", "id":1, "method":"getTokenAccountsByOwner", - "params":["{}", {{"programId": "{}"}}, {{"encoding":"base64"}}] + "params":["{owner}", {{"programId": "{program_id}"}}, {{"encoding":"base64"}}] }}"#, - owner, program_id, ); let res = io.handle_request_sync(&req, meta.clone()); let result: Value = serde_json::from_str(&res.expect("actual response")) @@ -8020,9 +7982,8 @@ pub mod tests { "jsonrpc":"2.0", "id":1, "method":"getTokenAccountsByOwner", - "params":["{}", {{"programId": "{}"}}, {{"encoding": "jsonParsed"}}] + "params":["{owner}", {{"programId": "{program_id}"}}, {{"encoding": "jsonParsed"}}] }}"#, - owner, program_id, ); let res = io.handle_request_sync(&req, meta.clone()); let result: Value = serde_json::from_str(&res.expect("actual response")) @@ -8037,9 +7998,8 @@ pub mod tests { "jsonrpc":"2.0", "id":1, "method":"getProgramAccounts", - "params":["{}", {{"encoding": "jsonParsed"}}] + "params":["{program_id}", {{"encoding": "jsonParsed"}}] }}"#, - program_id, ); let res = io.handle_request_sync(&req, meta.clone()); let result: Value = serde_json::from_str(&res.expect("actual response")) @@ -8058,9 +8018,8 @@ pub mod tests { r#"{{ "jsonrpc":"2.0", "id":1,"method":"getTokenAccountsByOwner", - "params":["{}", {{"mint": "{}"}}, {{"encoding":"base64"}}] + "params":["{owner}", {{"mint": "{mint}"}}, {{"encoding":"base64"}}] }}"#, - owner, mint, ); let res = io.handle_request_sync(&req, meta.clone()); let result: Value = serde_json::from_str(&res.expect("actual response")) @@ -8123,9 +8082,8 @@ pub mod tests { "jsonrpc":"2.0", "id":1, "method":"getTokenAccountsByDelegate", - "params":["{}", {{"programId": "{}"}}, {{"encoding":"base64"}}] + "params":["{delegate}", {{"programId": "{program_id}"}}, {{"encoding":"base64"}}] }}"#, - delegate, program_id, ); let res = io.handle_request_sync(&req, meta.clone()); let result: Value = serde_json::from_str(&res.expect("actual response")) @@ -8140,9 +8098,8 @@ pub mod tests { "jsonrpc":"2.0", "id":1,"method": "getTokenAccountsByDelegate", - "params":["{}", {{"mint": "{}"}}, {{"encoding":"base64"}}] + "params":["{delegate}", {{"mint": "{mint}"}}, {{"encoding":"base64"}}] }}"#, - delegate, mint, ); let res = io.handle_request_sync(&req, meta.clone()); let result: Value = serde_json::from_str(&res.expect("actual response")) @@ -8242,8 +8199,7 @@ pub mod tests { // Test largest token accounts let req = format!( - r#"{{"jsonrpc":"2.0","id":1,"method":"getTokenLargestAccounts","params":["{}"]}}"#, - new_mint, + r#"{{"jsonrpc":"2.0","id":1,"method":"getTokenLargestAccounts","params":["{new_mint}"]}}"#, ); let res = io.handle_request_sync(&req, meta); let result: Value = serde_json::from_str(&res.expect("actual response")) @@ -8400,8 +8356,7 @@ pub mod tests { }; let req = format!( - r#"{{"jsonrpc":"2.0","id":1,"method":"getAccountInfo","params":["{}", {{"encoding": "jsonParsed"}}]}}"#, - token_account_pubkey, + r#"{{"jsonrpc":"2.0","id":1,"method":"getAccountInfo","params":["{token_account_pubkey}", {{"encoding": "jsonParsed"}}]}}"#, ); let res = io.handle_request_sync(&req, meta.clone()); let result: Value = serde_json::from_str(&res.expect("actual response")) @@ -8456,8 +8411,7 @@ pub mod tests { // Test Mint let req = format!( - r#"{{"jsonrpc":"2.0","id":1,"method":"getAccountInfo","params":["{}", {{"encoding": "jsonParsed"}}]}}"#, - mint, + r#"{{"jsonrpc":"2.0","id":1,"method":"getAccountInfo","params":["{mint}", {{"encoding": "jsonParsed"}}]}}"#, ); let res = io.handle_request_sync(&req, meta); let result: Value = serde_json::from_str(&res.expect("actual response")) @@ -8816,8 +8770,7 @@ pub mod tests { decode_and_deserialize::(tx58, TransactionBinaryEncoding::Base58) .unwrap_err(), Error::invalid_params(format!( - "base58 encoded solana_sdk::transaction::Transaction too large: {} bytes (max: encoded/raw {}/{})", - tx58_len, MAX_BASE58_SIZE, PACKET_DATA_SIZE, + "base58 encoded solana_sdk::transaction::Transaction too large: {tx58_len} bytes (max: encoded/raw {MAX_BASE58_SIZE}/{PACKET_DATA_SIZE})", ) )); @@ -8827,8 +8780,7 @@ pub mod tests { decode_and_deserialize::(tx64, TransactionBinaryEncoding::Base64) .unwrap_err(), Error::invalid_params(format!( - "base64 encoded solana_sdk::transaction::Transaction too large: {} bytes (max: encoded/raw {}/{})", - tx64_len, MAX_BASE64_SIZE, PACKET_DATA_SIZE, + "base64 encoded solana_sdk::transaction::Transaction too large: {tx64_len} bytes (max: encoded/raw {MAX_BASE64_SIZE}/{PACKET_DATA_SIZE})", ) )); @@ -8839,8 +8791,7 @@ pub mod tests { decode_and_deserialize::(tx58, TransactionBinaryEncoding::Base58) .unwrap_err(), Error::invalid_params(format!( - "decoded solana_sdk::transaction::Transaction too large: {} bytes (max: {} bytes)", - too_big, PACKET_DATA_SIZE + "decoded solana_sdk::transaction::Transaction too large: {too_big} bytes (max: {PACKET_DATA_SIZE} bytes)" )) ); @@ -8849,8 +8800,7 @@ pub mod tests { decode_and_deserialize::(tx64, TransactionBinaryEncoding::Base64) .unwrap_err(), Error::invalid_params(format!( - "decoded solana_sdk::transaction::Transaction too large: {} bytes (max: {} bytes)", - too_big, PACKET_DATA_SIZE + "decoded solana_sdk::transaction::Transaction too large: {too_big} bytes (max: {PACKET_DATA_SIZE} bytes)" )) ); diff --git a/rpc/src/rpc_pubsub.rs b/rpc/src/rpc_pubsub.rs index 30c72591d..f0dfa341c 100644 --- a/rpc/src/rpc_pubsub.rs +++ b/rpc/src/rpc_pubsub.rs @@ -405,7 +405,7 @@ impl RpcSolPubSubImpl { fn param(param_str: &str, thing: &str) -> Result { param_str.parse::().map_err(|_e| Error { code: ErrorCode::InvalidParams, - message: format!("Invalid Request: Invalid {} provided", thing), + message: format!("Invalid Request: Invalid {thing} provided"), data: None, }) } @@ -1095,8 +1095,7 @@ mod tests { io.extend_with(rpc.to_delegate()); let req = format!( - r#"{{"jsonrpc":"2.0","id":1,"method":"accountSubscribe","params":["{}"]}}"#, - bob_pubkey + r#"{{"jsonrpc":"2.0","id":1,"method":"accountSubscribe","params":["{bob_pubkey}"]}}"# ); let _res = io.handle_request_sync(&req); @@ -1280,8 +1279,7 @@ mod tests { let expected_res_str = serde_json::to_string(&expected_res).unwrap(); let expected = format!( - r#"{{"jsonrpc":"2.0","method":"slotNotification","params":{{"result":{},"subscription":0}}}}"#, - expected_res_str + r#"{{"jsonrpc":"2.0","method":"slotNotification","params":{{"result":{expected_res_str},"subscription":0}}}}"# ); assert_eq!(expected, response); } @@ -1310,8 +1308,7 @@ mod tests { let expected_res_str = serde_json::to_string(&expected_res).unwrap(); let expected = format!( - r#"{{"jsonrpc":"2.0","method":"slotNotification","params":{{"result":{},"subscription":0}}}}"#, - expected_res_str + r#"{{"jsonrpc":"2.0","method":"slotNotification","params":{{"result":{expected_res_str},"subscription":0}}}}"# ); assert_eq!(expected, response); diff --git a/rpc/src/rpc_pubsub_service.rs b/rpc/src/rpc_pubsub_service.rs index 9b5139a9e..d6394199b 100644 --- a/rpc/src/rpc_pubsub_service.rs +++ b/rpc/src/rpc_pubsub_service.rs @@ -194,7 +194,7 @@ pub struct TestBroadcastReceiver { impl TestBroadcastReceiver { pub fn recv(&mut self) -> String { match self.recv_timeout(std::time::Duration::from_secs(10)) { - Err(err) => panic!("broadcast receiver error: {}", err), + Err(err) => panic!("broadcast receiver error: {err}"), Ok(str) => str, } } diff --git a/rpc/src/rpc_subscriptions.rs b/rpc/src/rpc_subscriptions.rs index 47a8c597b..18438c886 100644 --- a/rpc/src/rpc_subscriptions.rs +++ b/rpc/src/rpc_subscriptions.rs @@ -105,24 +105,24 @@ pub enum NotificationEntry { impl std::fmt::Debug for NotificationEntry { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { - NotificationEntry::Root(root) => write!(f, "Root({})", root), - NotificationEntry::Vote(vote) => write!(f, "Vote({:?})", vote), - NotificationEntry::Slot(slot_info) => write!(f, "Slot({:?})", slot_info), + NotificationEntry::Root(root) => write!(f, "Root({root})"), + NotificationEntry::Vote(vote) => write!(f, "Vote({vote:?})"), + NotificationEntry::Slot(slot_info) => write!(f, "Slot({slot_info:?})"), NotificationEntry::SlotUpdate(slot_update) => { - write!(f, "SlotUpdate({:?})", slot_update) + write!(f, "SlotUpdate({slot_update:?})") } NotificationEntry::Bank(commitment_slots) => { write!(f, "Bank({{slot: {:?}}})", commitment_slots.slot) } NotificationEntry::SignaturesReceived(slot_signatures) => { - write!(f, "SignaturesReceived({:?})", slot_signatures) + write!(f, "SignaturesReceived({slot_signatures:?})") } - NotificationEntry::Gossip(slot) => write!(f, "Gossip({:?})", slot), + NotificationEntry::Gossip(slot) => write!(f, "Gossip({slot:?})"), NotificationEntry::Subscribed(params, id) => { - write!(f, "Subscribed({:?}, {:?})", params, id) + write!(f, "Subscribed({params:?}, {id:?})") } NotificationEntry::Unsubscribed(params, id) => { - write!(f, "Unsubscribed({:?}, {:?})", params, id) + write!(f, "Unsubscribed({params:?}, {id:?})") } } } @@ -652,7 +652,7 @@ impl RpcSubscriptions { .spawn(move || { let pool = rayon::ThreadPoolBuilder::new() .num_threads(notification_threads) - .thread_name(|i| format!("solRpcNotify{:02}", i)) + .thread_name(|i| format!("solRpcNotify{i:02}")) .build() .unwrap(); pool.install(|| { @@ -2648,8 +2648,7 @@ pub(crate) mod tests { let expected_res_str = serde_json::to_string(&expected_res).unwrap(); let expected = format!( - r#"{{"jsonrpc":"2.0","method":"slotNotification","params":{{"result":{},"subscription":0}}}}"#, - expected_res_str + r#"{{"jsonrpc":"2.0","method":"slotNotification","params":{{"result":{expected_res_str},"subscription":0}}}}"# ); assert_eq!(expected, response); @@ -2691,8 +2690,7 @@ pub(crate) mod tests { let expected_res_str = serde_json::to_string(&serde_json::to_value(expected_root).unwrap()).unwrap(); let expected = format!( - r#"{{"jsonrpc":"2.0","method":"rootNotification","params":{{"result":{},"subscription":0}}}}"#, - expected_res_str + r#"{{"jsonrpc":"2.0","method":"rootNotification","params":{{"result":{expected_res_str},"subscription":0}}}}"# ); assert_eq!(expected, response); } diff --git a/runtime/benches/append_vec.rs b/runtime/benches/append_vec.rs index 439752c07..9ff8e7bd6 100644 --- a/runtime/benches/append_vec.rs +++ b/runtime/benches/append_vec.rs @@ -75,7 +75,7 @@ fn append_vec_sequential_read(bencher: &mut Bencher) { let mut indexes = add_test_accounts(&vec, size); bencher.iter(|| { let (sample, pos) = indexes.pop().unwrap(); - println!("reading pos {} {}", sample, pos); + println!("reading pos {sample} {pos}"); let (account, _next) = vec.get_account(pos).unwrap(); let (_meta, test) = create_test_account(sample); assert_eq!(account.data, test.data()); diff --git a/runtime/src/accounts.rs b/runtime/src/accounts.rs index 22db8e77b..7f38fc71c 100644 --- a/runtime/src/accounts.rs +++ b/runtime/src/accounts.rs @@ -1668,8 +1668,7 @@ mod tests { assert_eq!( map.cache_ranges_held.read().unwrap().to_vec(), expected, - "bin: {}", - bin + "bin: {bin}" ); }); accts.hold_range_in_memory(&range, false, &test_thread_pool()); diff --git a/runtime/src/accounts_background_service.rs b/runtime/src/accounts_background_service.rs index 391f44b11..867424422 100644 --- a/runtime/src/accounts_background_service.rs +++ b/runtime/src/accounts_background_service.rs @@ -97,7 +97,7 @@ impl DropCallback for SendDroppedBankCallback { impl Debug for SendDroppedBankCallback { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { - write!(f, "SendDroppedBankCallback({:p})", self) + write!(f, "SendDroppedBankCallback({self:p})") } } diff --git a/runtime/src/accounts_db.rs b/runtime/src/accounts_db.rs index 8e5d4df69..54670669c 100644 --- a/runtime/src/accounts_db.rs +++ b/runtime/src/accounts_db.rs @@ -2125,7 +2125,7 @@ pub fn make_min_priority_thread_pool() -> ThreadPool { // Use lower thread count to reduce priority. let num_threads = quarter_thread_count(); rayon::ThreadPoolBuilder::new() - .thread_name(|i| format!("solAccountsLo{:02}", i)) + .thread_name(|i| format!("solAccountsLo{i:02}")) .num_threads(num_threads) .build() .unwrap() @@ -2329,7 +2329,7 @@ impl AccountsDb { file_size: DEFAULT_FILE_SIZE, thread_pool: rayon::ThreadPoolBuilder::new() .num_threads(num_threads) - .thread_name(|i| format!("solAccounts{:02}", i)) + .thread_name(|i| format!("solAccounts{i:02}")) .stack_size(ACCOUNTS_STACK_SIZE) .build() .unwrap(), @@ -5236,9 +5236,8 @@ impl AccountsDb { // fetched from storage. This means a race occurred between this function and clean // accounts/purge_slots let message = format!( - "do_load() failed to get key: {} from storage, latest attempt was for \ - slot: {}, storage_location: {:?}, load_hint: {:?}", - pubkey, slot, storage_location, load_hint, + "do_load() failed to get key: {pubkey} from storage, latest attempt was for \ + slot: {slot}, storage_location: {storage_location:?}, load_hint: {load_hint:?}", ); datapoint_warn!("accounts_db-do_load_warn", ("warn", message, String)); true @@ -5971,8 +5970,7 @@ impl AccountsDb { // storage entries should be purged from self.storage assert!( self.storage.get_slot_stores(remove_slot).is_none(), - "slot {} is not none", - remove_slot + "slot {remove_slot} is not none" ); } @@ -6006,8 +6004,7 @@ impl AccountsDb { .get_rooted_from_list(remove_slots.iter().map(|(slot, _)| slot)); assert!( rooted_slots.is_empty(), - "Trying to remove accounts for rooted slots {:?}", - rooted_slots + "Trying to remove accounts for rooted slots {rooted_slots:?}" ); let RemoveUnrootedSlotsSynchronization { @@ -7558,10 +7555,7 @@ impl AccountsDb { let current = Self::get_slot_one_epoch_prior(slot, epoch_schedule); assert!( previous <= current, - "get_accounts_hash_complete_one_epoch_old: {}, get_slot_one_epoch_prior: {}, slot: {}", - previous, - current, - slot + "get_accounts_hash_complete_one_epoch_old: {previous}, get_slot_one_epoch_prior: {current}, slot: {slot}" ); } @@ -12205,7 +12199,7 @@ pub mod tests { fn assert_not_load_account(accounts: &AccountsDb, slot: Slot, pubkey: Pubkey) { let ancestors = vec![(slot, 0)].into_iter().collect(); let load = accounts.load_without_fixed_root(&ancestors, &pubkey); - assert!(load.is_none(), "{:?}", load); + assert!(load.is_none(), "{load:?}"); } fn reconstruct_accounts_db_via_serialization(accounts: &AccountsDb, slot: Slot) -> AccountsDb { @@ -12537,7 +12531,7 @@ pub mod tests { let (account, slot) = db .load_without_fixed_root(&Ancestors::default(), &pubkey) .unwrap_or_else(|| { - panic!("Could not fetch stored account {}, iter {}", pubkey, i) + panic!("Could not fetch stored account {pubkey}, iter {i}") }); assert_eq!(slot, slot); assert_eq!(account.lamports(), account_bal); @@ -14601,10 +14595,7 @@ pub mod tests { db.accounts_cache .slot_cache(unrooted_slot as Slot) .is_some(), - "unrooted_slot: {}, total_slots: {}, expected_size: {}", - unrooted_slot, - total_slots, - expected_size + "unrooted_slot: {unrooted_slot}, total_slots: {total_slots}, expected_size: {expected_size}" ); } } @@ -16062,7 +16053,7 @@ pub mod tests { assert!(db.accounts_cache.slot_cache(*slot).is_none()); let account_in_slot = slot_to_pubkey_map[slot]; let item = db.accounts_index.get_account_read_entry(&account_in_slot); - assert!(item.is_none(), "item: {:?}", item); + assert!(item.is_none(), "item: {item:?}"); } // Wait for flush to finish before starting next trial @@ -16672,7 +16663,7 @@ pub mod tests { assert!(result.is_empty()); for extra in 1..3 { let result = db.calc_alive_ancient_historical_roots(extra); - assert_eq!(result, HashSet::default(), "extra: {}", extra); + assert_eq!(result, HashSet::default(), "extra: {extra}"); } let extra = 3; @@ -16680,7 +16671,7 @@ pub mod tests { db.accounts_index.add_root(active_root, false); let result = db.calc_alive_ancient_historical_roots(extra); let expected_alive_roots = [active_root].into_iter().collect(); - assert_eq!(result, expected_alive_roots, "extra: {}", extra); + assert_eq!(result, expected_alive_roots, "extra: {extra}"); } impl AccountsDb { @@ -17129,8 +17120,7 @@ pub mod tests { Some(MAX_ITEMS_PER_CHUNK..plus_1 + offset), None ], - "{:?}", - splitter + "{splitter:?}" ); // 2 full chunks, aligned @@ -17145,8 +17135,7 @@ pub mod tests { None, None ], - "{:?}", - splitter + "{splitter:?}" ); // 2 full chunks + 1, mis-aligned @@ -17161,8 +17150,7 @@ pub mod tests { Some(MAX_ITEMS_PER_CHUNK * 2..MAX_ITEMS_PER_CHUNK * 2 + offset), None, ], - "{:?}", - splitter + "{splitter:?}" ); // 3 full chunks - 1, mis-aligned by 2 @@ -17178,8 +17166,7 @@ pub mod tests { Some(MAX_ITEMS_PER_CHUNK * 2..MAX_ITEMS_PER_CHUNK * 3), Some(MAX_ITEMS_PER_CHUNK * 3..MAX_ITEMS_PER_CHUNK * 3 + 1), ], - "{:?}", - splitter + "{splitter:?}" ); // 1 full chunk - 1, mis-aligned by 2 @@ -17193,8 +17180,7 @@ pub mod tests { Some(offset..MAX_ITEMS_PER_CHUNK), Some(MAX_ITEMS_PER_CHUNK..MAX_ITEMS_PER_CHUNK + 1), ], - "{:?}", - splitter + "{splitter:?}" ); // 1 full chunk - 1, aligned at big offset @@ -17206,8 +17192,7 @@ pub mod tests { assert_eq!( result, [Some(offset..MAX_ITEMS_PER_CHUNK * 101 - 1), None,], - "{:?}", - splitter + "{splitter:?}" ); // 1 full chunk - 1, mis-aligned by 2 at big offset @@ -17222,8 +17207,7 @@ pub mod tests { Some(offset..MAX_ITEMS_PER_CHUNK * 101), Some(MAX_ITEMS_PER_CHUNK * 101..MAX_ITEMS_PER_CHUNK * 101 + 1), ], - "{:?}", - splitter + "{splitter:?}" ); } @@ -17242,8 +17226,7 @@ pub mod tests { Some(offset..MAX_ITEMS_PER_CHUNK * 101), Some(MAX_ITEMS_PER_CHUNK * 101..MAX_ITEMS_PER_CHUNK * 101 + 1), ], - "{:?}", - splitter + "{splitter:?}" ); } @@ -17787,7 +17770,7 @@ pub mod tests { .filter_map(|slot| { let storages = db.get_storages_for_slot(slot); storages.map(|storages| { - assert_eq!(storages.len(), 1, "slot: {}, slots: {:?}", slot, slots); + assert_eq!(storages.len(), 1, "slot: {slot}, slots: {slots:?}"); let storage = storages.first().unwrap(); storage .accounts diff --git a/runtime/src/accounts_hash.rs b/runtime/src/accounts_hash.rs index c007c9bfd..7d000ed1a 100644 --- a/runtime/src/accounts_hash.rs +++ b/runtime/src/accounts_hash.rs @@ -823,10 +823,7 @@ impl AccountsHasher { pub fn checked_cast_for_capitalization(balance: u128) -> u64 { balance.try_into().unwrap_or_else(|_| { - panic!( - "overflow is detected while summing capitalization: {}", - balance - ) + panic!("overflow is detected while summing capitalization: {balance}") }) } @@ -1450,20 +1447,12 @@ pub mod tests { assert_eq!( expected2, hashes4.into_iter().flatten().collect::>(), - "last_slice: {}, start: {}, end: {}, slice: {:?}", - last_slice, - start, - end, - slice + "last_slice: {last_slice}, start: {start}, end: {end}, slice: {slice:?}" ); assert_eq!( expected2.clone(), hashes5.iter().flatten().copied().collect::>(), - "last_slice: {}, start: {}, end: {}, slice: {:?}", - last_slice, - start, - end, - slice + "last_slice: {last_slice}, start: {start}, end: {end}, slice: {slice:?}" ); assert_eq!( expected2.clone(), @@ -1491,7 +1480,7 @@ pub mod tests { }) .collect::(); - let hash_result_as_string = format!("{:?}", hashes2); + let hash_result_as_string = format!("{hashes2:?}"); let packaged_result: ExpectedType = ( human_readable, diff --git a/runtime/src/accounts_index_storage.rs b/runtime/src/accounts_index_storage.rs index 6218109aa..bea6242f2 100644 --- a/runtime/src/accounts_index_storage.rs +++ b/runtime/src/accounts_index_storage.rs @@ -75,7 +75,7 @@ impl BgThreads { // note that using rayon here causes us to exhaust # rayon threads and many tests running in parallel deadlock Builder::new() - .name(format!("solIdxFlusher{:02}", idx)) + .name(format!("solIdxFlusher{idx:02}")) .spawn(move || { storage_.background( vec![local_exit_, system_exit_], diff --git a/runtime/src/append_vec.rs b/runtime/src/append_vec.rs index 661df861c..61e740aaf 100644 --- a/runtime/src/append_vec.rs +++ b/runtime/src/append_vec.rs @@ -368,7 +368,7 @@ impl AppendVec { if file_size == 0 { Err(std::io::Error::new( std::io::ErrorKind::Other, - format!("too small file size {} for AppendVec", file_size), + format!("too small file size {file_size} for AppendVec"), )) } else if usize::try_from(MAXIMUM_APPEND_VEC_FILE_SIZE) .map(|max| file_size > max) @@ -376,12 +376,12 @@ impl AppendVec { { Err(std::io::Error::new( std::io::ErrorKind::Other, - format!("too large file size {} for AppendVec", file_size), + format!("too large file size {file_size} for AppendVec"), )) } else if current_len > file_size { Err(std::io::Error::new( std::io::ErrorKind::Other, - format!("current_len is larger than file size ({})", file_size), + format!("current_len is larger than file size ({file_size})"), )) } else { Ok(()) @@ -417,7 +417,7 @@ impl AppendVec { } pub fn file_name(slot: Slot, id: impl std::fmt::Display) -> String { - format!("{}.{}", slot, id) + format!("{slot}.{id}") } pub fn new_from_file>(path: P, current_len: usize) -> io::Result<(Self, usize)> { diff --git a/runtime/src/append_vec/test_utils.rs b/runtime/src/append_vec/test_utils.rs index 4cd2c023d..a731b4585 100644 --- a/runtime/src/append_vec/test_utils.rs +++ b/runtime/src/append_vec/test_utils.rs @@ -27,9 +27,9 @@ pub fn get_append_vec_path(path: &str) -> TempFile { .sample_iter(&Alphanumeric) .take(30) .collect(); - let dir = format!("{}/{}", out_dir, rand_string); + let dir = format!("{out_dir}/{rand_string}"); let mut buf = PathBuf::new(); - buf.push(&format!("{}/{}", dir, path)); + buf.push(&format!("{dir}/{path}")); std::fs::create_dir_all(dir).expect("Create directory failed"); TempFile { path: buf } } diff --git a/runtime/src/bank.rs b/runtime/src/bank.rs index a6befa10c..b64d4eb5a 100644 --- a/runtime/src/bank.rs +++ b/runtime/src/bank.rs @@ -3306,8 +3306,7 @@ impl Bank { for (pubkey, account) in genesis_config.accounts.iter() { assert!( self.get_account(pubkey).is_none(), - "{} repeated in genesis config", - pubkey + "{pubkey} repeated in genesis config" ); self.store_account(pubkey, account); self.capitalization.fetch_add(account.lamports(), Relaxed); @@ -3320,8 +3319,7 @@ impl Bank { for (pubkey, account) in genesis_config.rewards_pools.iter() { assert!( self.get_account(pubkey).is_none(), - "{} repeated in genesis config", - pubkey + "{pubkey} repeated in genesis config" ); self.store_account(pubkey, account); self.accounts_data_size_initial += account.data().len() as u64; @@ -3396,8 +3394,7 @@ impl Bank { // updating builtin program match &existing_genuine_program { None => panic!( - "There is no account to replace with builtin program ({}, {}).", - name, program_id + "There is no account to replace with builtin program ({name}, {program_id})." ), Some(account) => { if *name == String::from_utf8_lossy(account.data()) { @@ -3416,10 +3413,8 @@ impl Bank { assert!( !self.freeze_started(), - "Can't change frozen bank by adding not-existing new builtin program ({}, {}). \ - Maybe, inconsistent program activation is detected on snapshot restore?", - name, - program_id + "Can't change frozen bank by adding not-existing new builtin program ({name}, {program_id}). \ + Maybe, inconsistent program activation is detected on snapshot restore?" ); // Add a bogus executable builtin account, which will be loaded and ignored. @@ -3449,9 +3444,8 @@ impl Bank { assert!( !self.freeze_started(), - "Can't change frozen bank by adding not-existing new precompiled program ({}). \ - Maybe, inconsistent program activation is detected on snapshot restore?", - program_id + "Can't change frozen bank by adding not-existing new precompiled program ({program_id}). \ + Maybe, inconsistent program activation is detected on snapshot restore?" ); // Add a bogus executable account, which will be loaded and ignored. @@ -5720,8 +5714,8 @@ impl Bank { end_index, partition_count, (end_key_prefix - start_key_prefix), - start_pubkey.iter().map(|x| format!("{:02x}", x)).join(""), - end_pubkey.iter().map(|x| format!("{:02x}", x)).join(""), + start_pubkey.iter().map(|x| format!("{x:02x}")).join(""), + end_pubkey.iter().map(|x| format!("{x:02x}")).join(""), ); #[cfg(test)] if start_index != end_index { @@ -5732,21 +5726,12 @@ impl Bank { start_index + 1 }, Self::partition_from_pubkey(&start_pubkey_final, partition_count), - "{}, {}, start_key_prefix: {}, {}, {}", - start_index, - end_index, - start_key_prefix, - start_pubkey_final, - partition_count + "{start_index}, {end_index}, start_key_prefix: {start_key_prefix}, {start_pubkey_final}, {partition_count}" ); assert_eq!( end_index, Self::partition_from_pubkey(&end_pubkey_final, partition_count), - "{}, {}, {}, {}", - start_index, - end_index, - end_pubkey_final, - partition_count + "{start_index}, {end_index}, {end_pubkey_final}, {partition_count}" ); if start_index != 0 { start_pubkey[0..PREFIX_SIZE] @@ -13108,7 +13093,7 @@ pub(crate) mod tests { if num_banks % 100 == 0 { #[cfg(target_os = "linux")] { - let pages_consumed = std::fs::read_to_string(format!("/proc/{}/statm", pid)) + let pages_consumed = std::fs::read_to_string(format!("/proc/{pid}/statm")) .unwrap() .split_whitespace() .next() @@ -14561,7 +14546,7 @@ pub(crate) mod tests { .enumerate() .map(|i| { let key = solana_sdk::pubkey::new_rand(); - let name = format!("program{:?}", i); + let name = format!("program{i:?}"); bank.add_builtin(&name, &key, mock_ok_vote_processor); (key, name.as_bytes().to_vec()) }) @@ -14698,7 +14683,7 @@ pub(crate) mod tests { assert_eq!(account.data(), name); } info!("result: {:?}", result); - let result_key = format!("{:?}", result); + let result_key = format!("{result:?}"); *results.entry(result_key).or_insert(0) += 1; } info!("results: {:?}", results); @@ -16749,7 +16734,7 @@ pub(crate) mod tests { let (genesis_config, _mint_keypair) = create_genesis_config(50000); let mut bank = Bank::new_for_tests(&genesis_config); bank.finish_init(&genesis_config, None, false); - let debug = format!("{:#?}", bank); + let debug = format!("{bank:#?}"); assert!(!debug.is_empty()); } @@ -20207,7 +20192,7 @@ pub(crate) mod tests { let index1 = Bank::partition_from_pubkey(&pk1, n); let index2 = Bank::partition_from_pubkey(&pk2, n); assert!(index1 > 0, "{}", index1); - assert!(index2 > index1, "{}, {}", index2, index1); + assert!(index2 > index1, "{index2}, {index1}"); let epoch_schedule = EpochSchedule::custom(n, 0, false); diff --git a/runtime/src/bucket_map_holder.rs b/runtime/src/bucket_map_holder.rs index 1de9bf3bc..765a487bd 100644 --- a/runtime/src/bucket_map_holder.rs +++ b/runtime/src/bucket_map_holder.rs @@ -418,7 +418,7 @@ pub mod tests { }); }); visited.iter().enumerate().for_each(|(bin, visited)| { - assert_eq!(visited.load(Ordering::Relaxed), expected, "bin: {}", bin) + assert_eq!(visited.load(Ordering::Relaxed), expected, "bin: {bin}") }); } diff --git a/runtime/src/cache_hash_data.rs b/runtime/src/cache_hash_data.rs index 43988af00..5849c2fc1 100644 --- a/runtime/src/cache_hash_data.rs +++ b/runtime/src/cache_hash_data.rs @@ -50,9 +50,7 @@ impl CacheHashDataFile { let mut pubkey_to_bin_index = bin_calculator.bin_from_pubkey(&d.pubkey); assert!( pubkey_to_bin_index >= start_bin_index, - "{}, {}", - pubkey_to_bin_index, - start_bin_index + "{pubkey_to_bin_index}, {start_bin_index}" ); // this would indicate we put a pubkey in too high of a bin pubkey_to_bin_index -= start_bin_index; accumulator[pubkey_to_bin_index].push(d.clone()); // may want to avoid clone here @@ -161,7 +159,7 @@ impl CacheHashData { let cache_folder = Self::get_cache_root_path(parent_folder); std::fs::create_dir_all(cache_folder.clone()) - .unwrap_or_else(|_| panic!("error creating cache dir: {:?}", cache_folder)); + .unwrap_or_else(|_| panic!("error creating cache dir: {cache_folder:?}")); let result = CacheHashData { cache_folder, @@ -271,8 +269,7 @@ impl CacheHashData { cache_file.capacity = capacity; assert_eq!( capacity, file_len, - "expected: {}, len on disk: {} {:?}, entries: {}, cell_size: {}", - capacity, file_len, path, entries, cell_size + "expected: {capacity}, len on disk: {file_len} {path:?}, entries: {entries}, cell_size: {cell_size}" ); stats.total_entries = entries; @@ -420,8 +417,7 @@ pub mod tests { } assert_eq!( accum, data_this_pass, - "bins: {}, start_bin_this_pass: {}, pass: {}, flatten: {}, passes: {}", - bins, start_bin_this_pass, pass, flatten_data, passes + "bins: {bins}, start_bin_this_pass: {start_bin_this_pass}, pass: {pass}, flatten: {flatten_data}, passes: {passes}" ); } } diff --git a/runtime/src/epoch_stakes.rs b/runtime/src/epoch_stakes.rs index bd878bd06..3f1cda0a2 100644 --- a/runtime/src/epoch_stakes.rs +++ b/runtime/src/epoch_stakes.rs @@ -77,7 +77,7 @@ impl EpochStakes { "parse_epoch_vote_accounts", ( "warn", - format!("Unable to get vote_state from account {}", key), + format!("Unable to get vote_state from account {key}"), String ), ); diff --git a/runtime/src/hardened_unpack.rs b/runtime/src/hardened_unpack.rs index 80ed4853d..9c8e85ec1 100644 --- a/runtime/src/hardened_unpack.rs +++ b/runtime/src/hardened_unpack.rs @@ -55,8 +55,7 @@ fn checked_total_size_sum(total_size: u64, entry_size: u64, limit_size: u64) -> let total_size = total_size.saturating_add(entry_size); if total_size > limit_size { return Err(UnpackError::Archive(format!( - "too large archive: {} than limit: {}", - total_size, limit_size, + "too large archive: {total_size} than limit: {limit_size}", ))); } Ok(total_size) @@ -66,8 +65,7 @@ fn checked_total_count_increment(total_count: u64, limit_count: u64) -> Result limit_count { return Err(UnpackError::Archive(format!( - "too many files in snapshot: {:?}", - total_count + "too many files in snapshot: {total_count:?}" ))); } Ok(total_count) @@ -75,10 +73,7 @@ fn checked_total_count_increment(total_count: u64, limit_count: u64) -> Result Result<()> { if !unpack_result { - return Err(UnpackError::Archive(format!( - "failed to unpack: {:?}", - path - ))); + return Err(UnpackError::Archive(format!("failed to unpack: {path:?}"))); } Ok(()) } @@ -132,8 +127,7 @@ where if parts.clone().any(|p| p.is_none()) || reject_legacy_dir_entry { return Err(UnpackError::Archive(format!( - "invalid path found: {:?}", - path_str + "invalid path found: {path_str:?}" ))); } @@ -982,7 +976,7 @@ mod tests { result, Err(UnpackError::Archive(ref message)) if message == &format!( - "too large archive: 1125899906842624 than limit: {}", MAX_SNAPSHOT_ARCHIVE_UNPACKED_APPARENT_SIZE + "too large archive: 1125899906842624 than limit: {MAX_SNAPSHOT_ARCHIVE_UNPACKED_APPARENT_SIZE}" ) ); } @@ -1007,7 +1001,7 @@ mod tests { result, Err(UnpackError::Archive(ref message)) if message == &format!( - "too large archive: 18446744073709551615 than limit: {}", MAX_SNAPSHOT_ARCHIVE_UNPACKED_ACTUAL_SIZE + "too large archive: 18446744073709551615 than limit: {MAX_SNAPSHOT_ARCHIVE_UNPACKED_ACTUAL_SIZE}" ) ); } diff --git a/runtime/src/in_mem_accounts_index.rs b/runtime/src/in_mem_accounts_index.rs index 006f60fe7..ca11c4ed9 100644 --- a/runtime/src/in_mem_accounts_index.rs +++ b/runtime/src/in_mem_accounts_index.rs @@ -595,10 +595,7 @@ impl InMemAccountsIndex { let matched_other_slot = !matched_slot; assert!( !(found_slot && matched_slot || matched_other_slot && found_other_slot), - "{:?}, slot: {}, other_slot: {:?}", - slot_list, - slot, - other_slot + "{slot_list:?}, slot: {slot}, other_slot: {other_slot:?}" ); let is_cur_account_cached = cur_account_info.is_cached(); @@ -1700,8 +1697,7 @@ mod tests { &mut reclaims, reclaim ), - "other_slot: {:?}", - other_slot + "other_slot: {other_slot:?}" ); assert_eq!(slot_list, vec![at_new_slot]); assert!(reclaims.is_empty()); @@ -1724,8 +1720,7 @@ mod tests { &mut reclaims, reclaim ), - "other_slot: {:?}", - other_slot + "other_slot: {other_slot:?}" ); assert_eq!(slot_list, vec![at_new_slot]); assert_eq!(reclaims, expected_reclaims); @@ -1745,8 +1740,7 @@ mod tests { &mut reclaims, reclaim ), - "other_slot: {:?}", - other_slot + "other_slot: {other_slot:?}" ); assert_eq!(slot_list, vec![at_new_slot]); assert_eq!( @@ -1838,24 +1832,21 @@ mod tests { } assert_eq!( expected_result, result, - "return value different. other: {:?}, {:?}, {:?}, original: {:?}", - other_slot, expected, slot_list, original + "return value different. other: {other_slot:?}, {expected:?}, {slot_list:?}, original: {original:?}" ); // sort for easy comparison expected_reclaims.sort_unstable(); reclaims.sort_unstable(); assert_eq!( expected_reclaims, reclaims, - "reclaims different. other: {:?}, {:?}, {:?}, original: {:?}", - other_slot, expected, slot_list, original + "reclaims different. other: {other_slot:?}, {expected:?}, {slot_list:?}, original: {original:?}" ); // sort for easy comparison slot_list.sort_unstable(); expected.sort_unstable(); assert_eq!( slot_list, expected, - "slot_list different. other: {:?}, {:?}, {:?}, original: {:?}", - other_slot, expected, slot_list, original + "slot_list different. other: {other_slot:?}, {expected:?}, {slot_list:?}, original: {original:?}" ); } } diff --git a/runtime/src/pubkey_bins.rs b/runtime/src/pubkey_bins.rs index 1be2ff28d..c2191cfb7 100644 --- a/runtime/src/pubkey_bins.rs +++ b/runtime/src/pubkey_bins.rs @@ -63,7 +63,7 @@ pub mod tests { for i in 0..=24 { let bins = 2u32.pow(i); let calc = PubkeyBinCalculator24::new(bins as usize); - assert_eq!(calc.shift_bits, 24 - i, "i: {}", i); + assert_eq!(calc.shift_bits, 24 - i, "i: {i}"); for bin in 0..bins { assert_eq!( bin as usize, diff --git a/runtime/src/serde_snapshot.rs b/runtime/src/serde_snapshot.rs index d305c535e..76bc9fefe 100644 --- a/runtime/src/serde_snapshot.rs +++ b/runtime/src/serde_snapshot.rs @@ -730,8 +730,7 @@ where let max_append_vec_id = next_append_vec_id - 1; assert!( max_append_vec_id <= AppendVecId::MAX / 2, - "Storage id {} larger than allowed max", - max_append_vec_id + "Storage id {max_append_vec_id} larger than allowed max" ); // Process deserialized data, set necessary fields in self diff --git a/runtime/src/shared_buffer_reader.rs b/runtime/src/shared_buffer_reader.rs index 41c57b0d4..ecb313c57 100644 --- a/runtime/src/shared_buffer_reader.rs +++ b/runtime/src/shared_buffer_reader.rs @@ -700,8 +700,8 @@ pub mod tests { let expected_len = 1; for i in 0..sent.len() { let len = reader2.read(&mut data[i..=i]); - assert!(len.is_ok(), "{:?}, progress: {}", len, i); - assert_eq!(len.unwrap(), expected_len, "progress: {}", i); + assert!(len.is_ok(), "{len:?}, progress: {i}"); + assert_eq!(len.unwrap(), expected_len, "progress: {i}"); } assert_eq!(sent, data); assert_eq!( diff --git a/runtime/src/snapshot_utils.rs b/runtime/src/snapshot_utils.rs index 927b92d15..6734e6b54 100644 --- a/runtime/src/snapshot_utils.rs +++ b/runtime/src/snapshot_utils.rs @@ -635,8 +635,7 @@ where let consumed_size = data_file_stream.stream_position()?; if consumed_size > maximum_file_size { let error_message = format!( - "too large snapshot data file to serialize: {:?} has {} bytes", - data_file_path, consumed_size + "too large snapshot data file to serialize: {data_file_path:?} has {consumed_size} bytes" ); return Err(get_io_error(&error_message)); } @@ -2975,8 +2974,7 @@ mod tests { for snap_name in expected_snapshots { assert!( retained_snaps.contains(snap_name.as_str()), - "{} not found", - snap_name + "{snap_name} not found" ); } assert_eq!(retained_snaps.len(), expected_snapshots.len()); diff --git a/runtime/src/snapshot_utils/archive_format.rs b/runtime/src/snapshot_utils/archive_format.rs index 3151a5a51..4ef271cbb 100644 --- a/runtime/src/snapshot_utils/archive_format.rs +++ b/runtime/src/snapshot_utils/archive_format.rs @@ -80,7 +80,7 @@ impl fmt::Display for ParseError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { ParseError::InvalidExtension(extension) => { - write!(f, "Invalid archive extension: {}", extension) + write!(f, "Invalid archive extension: {extension}") } } } diff --git a/runtime/src/snapshot_utils/snapshot_storage_rebuilder.rs b/runtime/src/snapshot_utils/snapshot_storage_rebuilder.rs index f4e464507..48ae5880e 100644 --- a/runtime/src/snapshot_utils/snapshot_storage_rebuilder.rs +++ b/runtime/src/snapshot_utils/snapshot_storage_rebuilder.rs @@ -71,8 +71,7 @@ impl SnapshotStorageRebuilder { let snapshot_version_str = snapshot_version_from_file(snapshot_version_path)?; let snapshot_version = snapshot_version_str.parse().map_err(|_| { get_io_error(&format!( - "unsupported snapshot version: {}", - snapshot_version_str, + "unsupported snapshot version: {snapshot_version_str}", )) })?; let snapshot_storage_lengths = diff --git a/runtime/src/sorted_storages.rs b/runtime/src/sorted_storages.rs index 2b4c8a310..ffcfd3832 100644 --- a/runtime/src/sorted_storages.rs +++ b/runtime/src/sorted_storages.rs @@ -267,9 +267,7 @@ pub mod tests { let check = |(slot, storages): (Slot, Option<&SnapshotStorage>)| { assert!( (slot != 3) ^ storages.is_some(), - "slot: {}, storages: {:?}", - slot, - storages + "slot: {slot}, storages: {storages:?}" ); slot }; @@ -307,9 +305,7 @@ pub mod tests { ^ storages .map(|storages| storages.capacity() == (slot as usize)) .unwrap_or(false), - "slot: {}, storages: {:?}", - slot, - storages + "slot: {slot}, storages: {storages:?}" ); slot }; diff --git a/runtime/src/stakes.rs b/runtime/src/stakes.rs index 5a3d63983..b9cd322f7 100644 --- a/runtime/src/stakes.rs +++ b/runtime/src/stakes.rs @@ -141,7 +141,7 @@ impl StakesCache { datapoint_warn!( "bank-stake_delegation_accounts-invalid-account", ("slot", current_slot as i64, i64), - ("stake-address", format!("{:?}", stake_pubkey), String), + ("stake-address", format!("{stake_pubkey:?}"), String), ("reason", reason.to_i64().unwrap_or_default(), i64), ); } @@ -151,7 +151,7 @@ impl StakesCache { datapoint_warn!( "bank-stake_delegation_accounts-invalid-account", ("slot", current_slot as i64, i64), - ("vote-address", format!("{:?}", vote_pubkey), String), + ("vote-address", format!("{vote_pubkey:?}"), String), ("reason", reason.to_i64().unwrap_or_default(), i64), ); } diff --git a/runtime/src/status_cache.rs b/runtime/src/status_cache.rs index 751db2200..61e66f250 100644 --- a/runtime/src/status_cache.rs +++ b/runtime/src/status_cache.rs @@ -101,8 +101,7 @@ impl StatusCache { } } else { panic!( - "Map for key must exist if key exists in self.slot_deltas, slot: {}", - slot + "Map for key must exist if key exists in self.slot_deltas, slot: {slot}" ) } } @@ -111,10 +110,7 @@ impl StatusCache { o_blockhash_entries.remove_entry(); } } else { - panic!( - "Blockhash must exist if it exists in self.slot_deltas, slot: {}", - slot - ) + panic!("Blockhash must exist if it exists in self.slot_deltas, slot: {slot}") } } } diff --git a/sdk/cargo-build-sbf/src/main.rs b/sdk/cargo-build-sbf/src/main.rs index b61b0d075..602afce9b 100644 --- a/sdk/cargo-build-sbf/src/main.rs +++ b/sdk/cargo-build-sbf/src/main.rs @@ -100,7 +100,7 @@ where let file = File::create(&script_name).unwrap(); let mut out = BufWriter::new(file); for (key, value) in env::vars() { - writeln!(out, "{}=\"{}\" \\", key, value).unwrap(); + writeln!(out, "{key}=\"{value}\" \\").unwrap(); } write!(out, "{}", program.display()).unwrap(); for arg in args.iter() { @@ -263,7 +263,7 @@ fn postprocess_dump(program_dump: &Path) { if head_re.is_match(line) { let captures = head_re.captures(line).unwrap(); pc = u64::from_str_radix(&captures[1], 16).unwrap(); - writeln!(out, "{}", line).unwrap(); + writeln!(out, "{line}").unwrap(); continue; } if insn_re.is_match(line) { @@ -286,11 +286,11 @@ fn postprocess_dump(program_dump: &Path) { if a2n.contains_key(&address) { writeln!(out, "{} ; {}", line, a2n[&address]).unwrap(); } else { - writeln!(out, "{}", line).unwrap(); + writeln!(out, "{line}").unwrap(); } } } else { - writeln!(out, "{}", line).unwrap(); + writeln!(out, "{line}").unwrap(); } pc = pc.checked_add(step).unwrap(); } @@ -659,11 +659,11 @@ fn build_sbf_package(config: &Config, target_directory: &Path, package: &cargo_m } if let Some(program_name) = program_name { - let program_unstripped_so = target_build_directory.join(format!("{}.so", program_name)); - let program_dump = sbf_out_dir.join(format!("{}-dump.txt", program_name)); - let program_so = sbf_out_dir.join(format!("{}.so", program_name)); - let program_debug = sbf_out_dir.join(format!("{}.debug", program_name)); - let program_keypair = sbf_out_dir.join(format!("{}-keypair.json", program_name)); + let program_unstripped_so = target_build_directory.join(format!("{program_name}.so")); + let program_dump = sbf_out_dir.join(format!("{program_name}-dump.txt")); + let program_so = sbf_out_dir.join(format!("{program_name}.so")); + let program_debug = sbf_out_dir.join(format!("{program_name}.debug")); + let program_keypair = sbf_out_dir.join(format!("{program_name}-keypair.json")); fn file_older_or_missing(prerequisite_file: &Path, target_file: &Path) -> bool { let prerequisite_metadata = fs::metadata(prerequisite_file).unwrap_or_else(|err| { diff --git a/sdk/cargo-test-bpf/src/main.rs b/sdk/cargo-test-bpf/src/main.rs index af5a382fd..344bb042e 100644 --- a/sdk/cargo-test-bpf/src/main.rs +++ b/sdk/cargo-test-bpf/src/main.rs @@ -37,7 +37,7 @@ fn main() { args.insert(index, "--arch".to_string()); print!("cargo-test-bpf child: {}", program.display()); for a in &args { - print!(" {}", a); + print!(" {a}"); } println!(); let child = Command::new(&program) diff --git a/sdk/cargo-test-sbf/src/main.rs b/sdk/cargo-test-sbf/src/main.rs index 4662eb3b7..b8d2b6444 100644 --- a/sdk/cargo-test-sbf/src/main.rs +++ b/sdk/cargo-test-sbf/src/main.rs @@ -86,7 +86,7 @@ where let file = File::create(&script_name).unwrap(); let mut out = BufWriter::new(file); for (key, value) in env::vars() { - writeln!(out, "{}=\"{}\" \\", key, value).unwrap(); + writeln!(out, "{key}=\"{value}\" \\").unwrap(); } write!(out, "{}", program.display()).unwrap(); for arg in args.iter() { diff --git a/sdk/gen-headers/src/main.rs b/sdk/gen-headers/src/main.rs index bc51bd118..9d81438f1 100644 --- a/sdk/gen-headers/src/main.rs +++ b/sdk/gen-headers/src/main.rs @@ -86,43 +86,41 @@ fn transform(inc: &PathBuf) { let func = &caps[2].to_string(); let args = &caps[3].to_string(); let warn = format!("/* DO NOT MODIFY THIS GENERATED FILE. INSTEAD CHANGE {} AND RUN `cargo run --bin gen-headers` */", inc.display()); - let ifndef = format!("#ifndef SOL_SBFV2\n{} {}({});", ty, func, args); + let ifndef = format!("#ifndef SOL_SBFV2\n{ty} {func}({args});"); let hash = sys_hash(func); - let typedef_statement = format!("typedef {}(*{}_pointer_type)({});", ty, func, args); + let typedef_statement = format!("typedef {ty}(*{func}_pointer_type)({args});"); let mut arg = 0; let mut arg_list = "".to_string(); if !args.is_empty() { arg_list = comm_re .replace_all(args, |_caps: &Captures| { arg += 1; - format!(" arg{},", arg) + format!(" arg{arg},") }) .to_string(); arg += 1; - arg_list = format!("{} arg{}", arg_list, arg); + arg_list = format!("{arg_list} arg{arg}"); } - let function_signature = format!("static {} {}({})", ty, func, arg_list); + let function_signature = format!("static {ty} {func}({arg_list})"); let pointer_assignment = format!( - "{}_pointer_type {}_pointer = ({}_pointer_type) {};", - func, func, func, hash + "{func}_pointer_type {func}_pointer = ({func}_pointer_type) {hash};" ); if !args.is_empty() { arg_list = "arg1".to_string(); for a in 2..arg + 1 { - arg_list = format!("{}, arg{}", arg_list, a); + arg_list = format!("{arg_list}, arg{a}"); } } let return_statement = if ty == "void" { - format!("{}_pointer({});", func, arg_list) + format!("{func}_pointer({arg_list});") } else { - format!("return {}_pointer({});", func, arg_list) + format!("return {func}_pointer({arg_list});") }; format!( - "{}\n{}\n#else\n{}\n{} {{\n {}\n {}\n}}\n#endif", - warn, ifndef, typedef_statement, function_signature, pointer_assignment, return_statement, + "{warn}\n{ifndef}\n#else\n{typedef_statement}\n{function_signature} {{\n {pointer_assignment}\n {return_statement}\n}}\n#endif", ) }); - write!(output_writer, "{}", output_content).unwrap(); + write!(output_writer, "{output_content}").unwrap(); } const fn sys_hash(name: &str) -> usize { diff --git a/sdk/program/src/account_info.rs b/sdk/program/src/account_info.rs index 3652e2251..9592746e7 100644 --- a/sdk/program/src/account_info.rs +++ b/sdk/program/src/account_info.rs @@ -450,7 +450,7 @@ mod tests { let data_str = format!("{:?}", Hex(&data[..MAX_DEBUG_ACCOUNT_DATA])); let info = AccountInfo::new(&key, false, false, &mut lamports, &mut data, &key, false, 0); assert_eq!( - format!("{:?}", info), + format!("{info:?}"), format!( "AccountInfo {{ \ key: {}, \ @@ -478,7 +478,7 @@ mod tests { let data_str = format!("{:?}", Hex(&data)); let info = AccountInfo::new(&key, false, false, &mut lamports, &mut data, &key, false, 0); assert_eq!( - format!("{:?}", info), + format!("{info:?}"), format!( "AccountInfo {{ \ key: {}, \ @@ -505,7 +505,7 @@ mod tests { let mut data = vec![]; let info = AccountInfo::new(&key, false, false, &mut lamports, &mut data, &key, false, 0); assert_eq!( - format!("{:?}", info), + format!("{info:?}"), format!( "AccountInfo {{ \ key: {}, \ diff --git a/sdk/program/src/borsh.rs b/sdk/program/src/borsh.rs index e19d4326e..608ef1e95 100644 --- a/sdk/program/src/borsh.rs +++ b/sdk/program/src/borsh.rs @@ -52,7 +52,7 @@ fn get_declaration_packed_len( "u64" | "i64" => 8, "u128" | "i128" => 16, "nil" => 0, - _ => panic!("Missing primitive type: {}", declaration), + _ => panic!("Missing primitive type: {declaration}"), }, } } diff --git a/sdk/program/src/debug_account_data.rs b/sdk/program/src/debug_account_data.rs index 0ced70e5a..5575feb3f 100644 --- a/sdk/program/src/debug_account_data.rs +++ b/sdk/program/src/debug_account_data.rs @@ -19,7 +19,7 @@ pub(crate) struct Hex<'a>(pub(crate) &'a [u8]); impl fmt::Debug for Hex<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { for &byte in self.0 { - write!(f, "{:02x}", byte)?; + write!(f, "{byte:02x}")?; } Ok(()) } diff --git a/sdk/program/src/message/legacy.rs b/sdk/program/src/message/legacy.rs index a73f93bbc..194e0073f 100644 --- a/sdk/program/src/message/legacy.rs +++ b/sdk/program/src/message/legacy.rs @@ -627,7 +627,7 @@ mod tests { let keys: HashSet = BUILTIN_PROGRAMS_KEYS.iter().copied().collect(); assert_eq!(keys.len(), 10); for k in keys { - let k = format!("{}", k); + let k = format!("{k}"); assert!(k.ends_with("11111111111111111111111")); } } diff --git a/sdk/program/src/program_error.rs b/sdk/program/src/program_error.rs index c8fa9f071..a3b3febf3 100644 --- a/sdk/program/src/program_error.rs +++ b/sdk/program/src/program_error.rs @@ -295,6 +295,6 @@ impl From for ProgramError { impl From for ProgramError { fn from(error: BorshIoError) -> Self { - Self::BorshIoError(format!("{}", error)) + Self::BorshIoError(format!("{error}")) } } diff --git a/sdk/program/src/program_stubs.rs b/sdk/program/src/program_stubs.rs index 17ecfb41e..131309978 100644 --- a/sdk/program/src/program_stubs.rs +++ b/sdk/program/src/program_stubs.rs @@ -24,7 +24,7 @@ pub fn set_syscall_stubs(syscall_stubs: Box) -> Box(&buffer); assert!(out.is_err()); assert_eq!( - format!("{:?}", out), + format!("{out:?}"), r#"Err(Custom("Invalid Trailing Zeros"))"# ); let buffer = [0x80, 0x0]; let out = bincode::deserialize::(&buffer); assert!(out.is_err()); assert_eq!( - format!("{:?}", out), + format!("{out:?}"), r#"Err(Custom("Invalid Trailing Zeros"))"# ); } @@ -215,10 +215,7 @@ mod tests { let buffer = [0xe4, 0xd7, 0x88, 0xf6, 0x6f, 0xd4, 0xb9, 0x59]; let out = bincode::deserialize::(&buffer); assert!(out.is_err()); - assert_eq!( - format!("{:?}", out), - r#"Err(Custom("Last Byte Truncated"))"# - ); + assert_eq!(format!("{out:?}"), r#"Err(Custom("Last Byte Truncated"))"#); } #[test] @@ -226,10 +223,7 @@ mod tests { let buffer = [0x84, 0xdf, 0x96, 0xfa, 0xef]; let out = bincode::deserialize::(&buffer); assert!(out.is_err()); - assert_eq!( - format!("{:?}", out), - r#"Err(Custom("Left Shift Overflows"))"# - ); + assert_eq!(format!("{out:?}"), r#"Err(Custom("Left Shift Overflows"))"#); } #[test] @@ -237,7 +231,7 @@ mod tests { let buffer = [0x84, 0xdf, 0x96, 0xfa]; let out = bincode::deserialize::(&buffer); assert!(out.is_err()); - assert_eq!(format!("{:?}", out), r#"Err(Io(Kind(UnexpectedEof)))"#); + assert_eq!(format!("{out:?}"), r#"Err(Io(Kind(UnexpectedEof)))"#); } #[test] diff --git a/sdk/program/src/slot_history.rs b/sdk/program/src/slot_history.rs index 1eea9e176..7e62b0798 100644 --- a/sdk/program/src/slot_history.rs +++ b/sdk/program/src/slot_history.rs @@ -116,10 +116,10 @@ mod tests { assert_eq!(slot_history.check(*i), Check::Found); } for i in 3..20 { - assert_eq!(slot_history.check(i), Check::NotFound, "i: {}", i); + assert_eq!(slot_history.check(i), Check::NotFound, "i: {i}"); } for i in 21..MAX_ENTRIES { - assert_eq!(slot_history.check(i), Check::NotFound, "i: {}", i); + assert_eq!(slot_history.check(i), Check::NotFound, "i: {i}"); } assert_eq!(slot_history.check(MAX_ENTRIES + 1), Check::Future); @@ -132,7 +132,7 @@ mod tests { let start = slot - MAX_ENTRIES + 1; let end = slot; for i in start..end { - assert_eq!(slot_history.check(i), Check::NotFound, "i: {}", i); + assert_eq!(slot_history.check(i), Check::NotFound, "i: {i}"); } assert_eq!(slot_history.check(slot), Check::Found); } @@ -160,7 +160,7 @@ mod tests { assert_eq!(slot_history.check(MAX_ENTRIES + 19), Check::Found); assert_eq!(slot_history.check(20), Check::Found); for i in 21..MAX_ENTRIES + 19 { - assert_eq!(slot_history.check(i), Check::NotFound, "found: {}", i); + assert_eq!(slot_history.check(i), Check::NotFound, "found: {i}"); } assert_eq!(slot_history.check(MAX_ENTRIES + 20), Check::Future); } @@ -179,7 +179,7 @@ mod tests { slot_history.add(MAX_ENTRIES + 5); assert_eq!(slot_history.check(5), Check::TooOld); for i in 6..MAX_ENTRIES + 5 { - assert_eq!(slot_history.check(i), Check::NotFound, "i: {}", i); + assert_eq!(slot_history.check(i), Check::NotFound, "i: {i}"); } assert_eq!(slot_history.check(MAX_ENTRIES + 5), Check::Found); } diff --git a/sdk/src/commitment_config.rs b/sdk/src/commitment_config.rs index 1c5d3d0c8..2626ce04f 100644 --- a/sdk/src/commitment_config.rs +++ b/sdk/src/commitment_config.rs @@ -230,7 +230,7 @@ impl std::fmt::Display for CommitmentLevel { CommitmentLevel::Confirmed => "confirmed", CommitmentLevel::Finalized => "finalized", }; - write!(f, "{}", s) + write!(f, "{s}") } } diff --git a/sdk/src/derivation_path.rs b/sdk/src/derivation_path.rs index f9396e554..0f14e39e1 100644 --- a/sdk/src/derivation_path.rs +++ b/sdk/src/derivation_path.rs @@ -63,7 +63,7 @@ impl DerivationPath { let master_path = if path == "m" { path.to_string() } else { - format!("m/{}", path) + format!("m/{path}") }; let extend = DerivationPathInner::from_str(&master_path) .map_err(|err| DerivationPathError::InvalidDerivationPath(err.to_string()))?; @@ -72,8 +72,7 @@ impl DerivationPath { let change = extend.next().map(|index| index.to_u32()); if extend.next().is_some() { return Err(DerivationPathError::InvalidDerivationPath(format!( - "key path `{}` too deep, only / supported", - path + "key path `{path}` too deep, only / supported" ))); } Ok(Self::new_bip44_with_coin(coin, account, change)) @@ -124,9 +123,9 @@ impl DerivationPath { pub fn get_query(&self) -> String { if let Some(account) = &self.account() { if let Some(change) = &self.change() { - format!("?key={}/{}", account, change) + format!("?key={account}/{change}") } else { - format!("?key={}", account) + format!("?key={account}") } } else { "".to_string() @@ -164,8 +163,7 @@ impl DerivationPath { } if key_only { return Err(DerivationPathError::InvalidDerivationPath(format!( - "invalid query string `{}`, only `key` supported", - query_str, + "invalid query string `{query_str}`, only `key` supported", ))); } let full_path = query.get(QueryKey::FullPath.as_ref()); @@ -173,8 +171,7 @@ impl DerivationPath { return Self::from_absolute_path_str(full_path).map(Some); } Err(DerivationPathError::InvalidDerivationPath(format!( - "invalid query string `{}`, only `key` and `full-path` supported", - query_str, + "invalid query string `{query_str}`, only `key` and `full-path` supported", ))) } else { Ok(None) @@ -186,7 +183,7 @@ impl fmt::Debug for DerivationPath { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "m")?; for index in self.0.path() { - write!(f, "/{}", index)?; + write!(f, "/{index}")?; } Ok(()) } @@ -236,7 +233,7 @@ impl AsRef for QueryKey { impl std::fmt::Display for QueryKey { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { let s: &str = self.as_ref(); - write!(f, "{}", s) + write!(f, "{s}") } } @@ -752,12 +749,12 @@ mod tests { #[test] fn test_derivation_path_debug() { let path = DerivationPath::default(); - assert_eq!(format!("{:?}", path), "m/44'/501'".to_string()); + assert_eq!(format!("{path:?}"), "m/44'/501'".to_string()); let path = DerivationPath::new_bip44(Some(1), None); - assert_eq!(format!("{:?}", path), "m/44'/501'/1'".to_string()); + assert_eq!(format!("{path:?}"), "m/44'/501'/1'".to_string()); let path = DerivationPath::new_bip44(Some(1), Some(2)); - assert_eq!(format!("{:?}", path), "m/44'/501'/1'/2'".to_string()); + assert_eq!(format!("{path:?}"), "m/44'/501'/1'/2'".to_string()); } } diff --git a/sdk/src/genesis_config.rs b/sdk/src/genesis_config.rs index 7024671ee..7b3dde3ca 100644 --- a/sdk/src/genesis_config.rs +++ b/sdk/src/genesis_config.rs @@ -62,7 +62,7 @@ impl FromStr for ClusterType { "devnet" => Ok(ClusterType::Devnet), "testnet" => Ok(ClusterType::Testnet), "mainnet-beta" => Ok(ClusterType::MainnetBeta), - _ => Err(format!("{} is unrecognized for cluster type", s)), + _ => Err(format!("{s} is unrecognized for cluster type")), } } } @@ -168,7 +168,7 @@ impl GenesisConfig { .map_err(|err| { std::io::Error::new( std::io::ErrorKind::Other, - format!("Unable to open {:?}: {:?}", filename, err), + format!("Unable to open {filename:?}: {err:?}"), ) })?; @@ -176,14 +176,14 @@ impl GenesisConfig { let mem = unsafe { Mmap::map(&file) }.map_err(|err| { std::io::Error::new( std::io::ErrorKind::Other, - format!("Unable to map {:?}: {:?}", filename, err), + format!("Unable to map {filename:?}: {err:?}"), ) })?; let genesis_config = deserialize(&mem).map_err(|err| { std::io::Error::new( std::io::ErrorKind::Other, - format!("Unable to deserialize {:?}: {:?}", filename, err), + format!("Unable to deserialize {filename:?}: {err:?}"), ) })?; Ok(genesis_config) @@ -193,7 +193,7 @@ impl GenesisConfig { let serialized = serialize(&self).map_err(|err| { std::io::Error::new( std::io::ErrorKind::Other, - format!("Unable to serialize: {:?}", err), + format!("Unable to serialize: {err:?}"), ) })?; diff --git a/sdk/src/pubkey.rs b/sdk/src/pubkey.rs index b28672b7f..4032c19ec 100644 --- a/sdk/src/pubkey.rs +++ b/sdk/src/pubkey.rs @@ -10,7 +10,7 @@ pub fn new_rand() -> Pubkey { pub fn write_pubkey_file(outfile: &str, pubkey: Pubkey) -> Result<(), Box> { use std::io::Write; - let printable = format!("{}", pubkey); + let printable = format!("{pubkey}"); let serialized = serde_json::to_string(&printable)?; if let Some(outdir) = std::path::Path::new(&outfile).parent() { diff --git a/sdk/src/signer/keypair.rs b/sdk/src/signer/keypair.rs index 6e7ad0ee4..3818c5abd 100644 --- a/sdk/src/signer/keypair.rs +++ b/sdk/src/signer/keypair.rs @@ -210,7 +210,7 @@ pub fn generate_seed_from_seed_phrase_and_passphrase( const PBKDF2_ROUNDS: u32 = 2048; const PBKDF2_BYTES: usize = 64; - let salt = format!("mnemonic{}", passphrase); + let salt = format!("mnemonic{passphrase}"); let mut seed = vec![0u8; PBKDF2_BYTES]; pbkdf2::pbkdf2::>( diff --git a/sdk/src/transaction/mod.rs b/sdk/src/transaction/mod.rs index b304ea193..48dcdc695 100644 --- a/sdk/src/transaction/mod.rs +++ b/sdk/src/transaction/mod.rs @@ -707,7 +707,7 @@ impl Transaction { /// ``` pub fn sign(&mut self, keypairs: &T, recent_blockhash: Hash) { if let Err(e) = self.try_sign(keypairs, recent_blockhash) { - panic!("Transaction::sign failed with error {:?}", e); + panic!("Transaction::sign failed with error {e:?}"); } } @@ -733,7 +733,7 @@ impl Transaction { /// conditions. pub fn partial_sign(&mut self, keypairs: &T, recent_blockhash: Hash) { if let Err(e) = self.try_partial_sign(keypairs, recent_blockhash) { - panic!("Transaction::partial_sign failed with error {:?}", e); + panic!("Transaction::partial_sign failed with error {e:?}"); } } @@ -757,10 +757,7 @@ impl Transaction { recent_blockhash: Hash, ) { if let Err(e) = self.try_partial_sign_unchecked(keypairs, positions, recent_blockhash) { - panic!( - "Transaction::partial_sign_unchecked failed with error {:?}", - e - ); + panic!("Transaction::partial_sign_unchecked failed with error {e:?}"); } } diff --git a/stake-accounts/src/main.rs b/stake-accounts/src/main.rs index bc6debf03..d9f9ebc23 100644 --- a/stake-accounts/src/main.rs +++ b/stake-accounts/src/main.rs @@ -228,7 +228,7 @@ fn send_and_confirm_messages( for message in messages { let signature = send_and_confirm_message(client, message, signers, no_wait)?; signatures.push(signature); - println!("{}", signature); + println!("{signature}"); } Ok(signatures) } @@ -245,7 +245,7 @@ fn main() -> Result<(), Box> { } Command::Count(args) => { let num_accounts = count_stake_accounts(&client, &args.base_pubkey)?; - println!("{}", num_accounts); + println!("{num_accounts}"); } Command::Addresses(args) => { let addresses = stake_accounts::derive_stake_account_addresses( @@ -253,7 +253,7 @@ fn main() -> Result<(), Box> { args.num_accounts, ); for address in addresses { - println!("{:?}", address); + println!("{address:?}"); } } Command::Balance(args) => { @@ -264,7 +264,7 @@ fn main() -> Result<(), Box> { let balances = get_balances(&client, addresses)?; let lamports: u64 = balances.into_iter().map(|(_, bal)| bal).sum(); let sol = lamports_to_sol(lamports); - println!("{} SOL", sol); + println!("{sol} SOL"); } Command::Authorize(args) => { process_authorize_stake_accounts(&client, &args)?; diff --git a/storage-bigtable/src/access_token.rs b/storage-bigtable/src/access_token.rs index c6664ba88..f4d5e9ade 100644 --- a/storage-bigtable/src/access_token.rs +++ b/storage-bigtable/src/access_token.rs @@ -27,11 +27,11 @@ fn load_credentials(filepath: Option) -> Result { })?, }; Credentials::from_file(&path) - .map_err(|err| format!("Failed to read GCP credentials from {}: {}", path, err)) + .map_err(|err| format!("Failed to read GCP credentials from {path}: {err}")) } fn load_stringified_credentials(credential: String) -> Result { - Credentials::from_str(&credential).map_err(|err| format!("{}", err)) + Credentials::from_str(&credential).map_err(|err| format!("{err}")) } #[derive(Clone)] @@ -50,7 +50,7 @@ impl AccessToken { }; if let Err(err) = credentials.rsa_key() { - Err(format!("Invalid rsa key: {}", err)) + Err(format!("Invalid rsa key: {err}")) } else { let token = Arc::new(RwLock::new(Self::get_token(&credentials, &scope).await?)); let access_token = Self { @@ -84,7 +84,7 @@ impl AccessToken { let token = goauth::get_token(&jwt, credentials) .await - .map_err(|err| format!("Failed to refresh access token: {}", err))?; + .map_err(|err| format!("Failed to refresh access token: {err}"))?; info!("Token expires in {} seconds", token.expires_in()); Ok((token, Instant::now())) diff --git a/storage-bigtable/src/bigtable.rs b/storage-bigtable/src/bigtable.rs index d2e01e4c1..6d981cd01 100644 --- a/storage-bigtable/src/bigtable.rs +++ b/storage-bigtable/src/bigtable.rs @@ -139,10 +139,10 @@ impl BigTableConnection { Ok(Self { access_token: None, - channel: tonic::transport::Channel::from_shared(format!("http://{}", endpoint)) + channel: tonic::transport::Channel::from_shared(format!("http://{endpoint}")) .map_err(|err| Error::InvalidUri(endpoint, err.to_string()))? .connect_lazy(), - table_prefix: format!("projects/emulator/instances/{}/tables/", instance_name), + table_prefix: format!("projects/emulator/instances/{instance_name}/tables/"), app_profile_id: app_profile_id.to_string(), timeout, }) @@ -838,13 +838,13 @@ where let value = &row_data .iter() .find(|(name, _)| name == "proto") - .ok_or_else(|| Error::ObjectNotFound(format!("{}/{}", table, key)))? + .ok_or_else(|| Error::ObjectNotFound(format!("{table}/{key}")))? .1; let data = decompress(value)?; T::decode(&data[..]).map_err(|err| { warn!("Failed to deserialize {}/{}: {}", table, key, err); - Error::ObjectCorrupt(format!("{}/{}", table, key)) + Error::ObjectCorrupt(format!("{table}/{key}")) }) } @@ -859,13 +859,13 @@ where let value = &row_data .iter() .find(|(name, _)| name == "bin") - .ok_or_else(|| Error::ObjectNotFound(format!("{}/{}", table, key)))? + .ok_or_else(|| Error::ObjectNotFound(format!("{table}/{key}")))? .1; let data = decompress(value)?; bincode::deserialize(&data).map_err(|err| { warn!("Failed to deserialize {}/{}: {}", table, key, err); - Error::ObjectCorrupt(format!("{}/{}", table, key)) + Error::ObjectCorrupt(format!("{table}/{key}")) }) } diff --git a/storage-bigtable/src/compression.rs b/storage-bigtable/src/compression.rs index 90b8ccbe0..e14a3b484 100644 --- a/storage-bigtable/src/compression.rs +++ b/storage-bigtable/src/compression.rs @@ -36,7 +36,7 @@ pub fn decompress(data: &[u8]) -> Result, io::Error> { let method = bincode::deserialize(&data[..method_size as usize]).map_err(|err| { io::Error::new( io::ErrorKind::Other, - format!("method deserialize failed: {}", err), + format!("method deserialize failed: {err}"), ) })?; diff --git a/storage-bigtable/src/lib.rs b/storage-bigtable/src/lib.rs index 2349e0b76..1726afeb1 100644 --- a/storage-bigtable/src/lib.rs +++ b/storage-bigtable/src/lib.rs @@ -78,7 +78,7 @@ pub type Result = std::result::Result; // Convert a slot to its bucket representation whereby lower slots are always lexically ordered // before higher slots fn slot_to_key(slot: Slot) -> String { - format!("{:016x}", slot) + format!("{slot:016x}") } fn slot_to_blocks_key(slot: Slot) -> String { @@ -701,7 +701,7 @@ impl LedgerStorage { ); inc_new_counter_debug!("storage-bigtable-query", 1); let mut bigtable = self.connection.client(); - let address_prefix = format!("{}/", address); + let address_prefix = format!("{address}/"); // Figure out where to start listing from based on `before_signature` let (first_slot, before_transaction_index) = match before_signature { @@ -765,8 +765,7 @@ impl LedgerStorage { 'outer: for (row_key, data) in tx_by_addr_data { let slot = !key_to_slot(&row_key[address_prefix.len()..]).ok_or_else(|| { bigtable::Error::ObjectCorrupt(format!( - "Failed to convert key to slot: tx-by-addr/{}", - row_key + "Failed to convert key to slot: tx-by-addr/{row_key}" )) })?; diff --git a/storage-bigtable/src/root_ca_certificate.rs b/storage-bigtable/src/root_ca_certificate.rs index e39721102..edc53c4f9 100644 --- a/storage-bigtable/src/root_ca_certificate.rs +++ b/storage-bigtable/src/root_ca_certificate.rs @@ -12,7 +12,7 @@ pub fn load() -> Result { let mut pem = Vec::new(); file.read_to_end(&mut pem).map(|_| pem) }) - .map_err(|err| format!("Failed to read {}: {}", cert_file, err))?, + .map_err(|err| format!("Failed to read {cert_file}: {err}"))?, None => { // PEM file from Google Trust Services (https://pki.goog/roots.pem) include_bytes!("pki-goog-roots.pem").to_vec() diff --git a/storage-proto/src/convert.rs b/storage-proto/src/convert.rs index 0251fed87..3aef05649 100644 --- a/storage-proto/src/convert.rs +++ b/storage-proto/src/convert.rs @@ -1794,7 +1794,7 @@ mod test { let transaction_error: TransactionError = tx_by_addr_error .clone() .try_into() - .unwrap_or_else(|_| panic!("{:?} conversion implemented?", error)); + .unwrap_or_else(|_| panic!("{error:?} conversion implemented?")); assert_eq!(tx_by_addr_error, transaction_error.into()); } tx_by_addr::TransactionErrorType::InstructionError => { @@ -1809,10 +1809,10 @@ mod test { }), transaction_details: None, }; - let transaction_error: TransactionError = - tx_by_addr_error.clone().try_into().unwrap_or_else(|_| { - panic!("{:?} conversion implemented?", ix_error) - }); + let transaction_error: TransactionError = tx_by_addr_error + .clone() + .try_into() + .unwrap_or_else(|_| panic!("{ix_error:?} conversion implemented?")); assert_eq!(tx_by_addr_error, transaction_error.into()); } else { let tx_by_addr_error = tx_by_addr::TransactionError { @@ -1841,7 +1841,7 @@ mod test { let transaction_error: TransactionError = tx_by_addr_error .clone() .try_into() - .unwrap_or_else(|_| panic!("{:?} conversion implemented?", error)); + .unwrap_or_else(|_| panic!("{error:?} conversion implemented?")); assert_eq!(tx_by_addr_error, transaction_error.into()); } } diff --git a/streamer/src/sendmmsg.rs b/streamer/src/sendmmsg.rs index e035341fe..da82d6d75 100644 --- a/streamer/src/sendmmsg.rs +++ b/streamer/src/sendmmsg.rs @@ -29,7 +29,7 @@ pub enum SendPktsError { impl From for TransportError { fn from(err: SendPktsError) -> Self { - Self::Custom(format!("{:?}", err)) + Self::Custom(format!("{err:?}")) } } diff --git a/streamer/src/streamer.rs b/streamer/src/streamer.rs index fd2645206..ab5955620 100644 --- a/streamer/src/streamer.rs +++ b/streamer/src/streamer.rs @@ -372,7 +372,7 @@ pub fn responder( stats_reporter_sender: Option>>, ) -> JoinHandle<()> { Builder::new() - .name(format!("solRspndr{}", name)) + .name(format!("solRspndr{name}")) .spawn(move || { let mut errors = 0; let mut last_error = None; diff --git a/sys-tuner/src/main.rs b/sys-tuner/src/main.rs index 7c55e044b..64d08f02b 100644 --- a/sys-tuner/src/main.rs +++ b/sys-tuner/src/main.rs @@ -50,7 +50,7 @@ fn tune_poh_service_priority(uid: u32) { }) }) { info!("PoH thread PID is {}", pid); - let pid = format!("{}", pid); + let pid = format!("{pid}"); let output = Command::new("chrt") .args(["-r", "-p", "99", pid.as_str()]) .output() @@ -136,7 +136,7 @@ fn main() { unsafe { libc::umask(0o077) }; if let Err(e) = std::fs::remove_file(solana_sys_tuner::SOLANA_SYS_TUNER_PATH) { if e.kind() != std::io::ErrorKind::NotFound { - panic!("Failed to remove stale socket file: {:?}", e) + panic!("Failed to remove stale socket file: {e:?}") } } @@ -156,7 +156,7 @@ fn main() { ) .expect("Expected to change UID of the socket file"); } else { - panic!("Could not find UID for {:?} user", user); + panic!("Could not find UID for {user:?} user"); } info!("Waiting for tuning requests"); diff --git a/test-validator/src/lib.rs b/test-validator/src/lib.rs index 67e88fd19..53dacedc2 100644 --- a/test-validator/src/lib.rs +++ b/test-validator/src/lib.rs @@ -300,14 +300,14 @@ impl TestValidatorGenesis { info!("Fetching {:?} over RPC...", chunk); let responses = rpc_client .get_multiple_accounts(chunk) - .map_err(|err| format!("Failed to fetch: {}", err))?; + .map_err(|err| format!("Failed to fetch: {err}"))?; for (address, res) in chunk.iter().zip(responses) { if let Some(account) = res { self.add_account(*address, AccountSharedData::from(account)); } else if skip_missing { warn!("Could not find {}, skipping.", address); } else { - return Err(format!("Failed to fetch {}", address)); + return Err(format!("Failed to fetch {address}")); } } } @@ -401,7 +401,7 @@ impl TestValidatorGenesis { lamports, data: solana_program_test::read_file( solana_program_test::find_file(filename).unwrap_or_else(|| { - panic!("Unable to locate {}", filename); + panic!("Unable to locate {filename}"); }), ), owner, @@ -425,7 +425,7 @@ impl TestValidatorGenesis { AccountSharedData::from(Account { lamports, data: base64::decode(data_base64) - .unwrap_or_else(|err| panic!("Failed to base64 decode: {}", err)), + .unwrap_or_else(|err| panic!("Failed to base64 decode: {err}")), owner, executable: false, rent_epoch: 0, @@ -438,8 +438,8 @@ impl TestValidatorGenesis { /// `program_name` will also used to locate the SBF shared object in the current or fixtures /// directory. pub fn add_program(&mut self, program_name: &str, program_id: Pubkey) -> &mut Self { - let program_path = solana_program_test::find_file(&format!("{}.so", program_name)) - .unwrap_or_else(|| panic!("Unable to locate program {}", program_name)); + let program_path = solana_program_test::find_file(&format!("{program_name}.so")) + .unwrap_or_else(|| panic!("Unable to locate program {program_name}")); self.programs.push(ProgramInfo { program_id, @@ -500,7 +500,7 @@ impl TestValidatorGenesis { let mint_keypair = Keypair::new(); self.start_with_mint_address(mint_keypair.pubkey(), socket_addr_space) .map(|test_validator| (test_validator, mint_keypair)) - .unwrap_or_else(|err| panic!("Test validator failed to start: {}", err)) + .unwrap_or_else(|err| panic!("Test validator failed to start: {err}")) } pub async fn start_async(&self) -> (TestValidator, Keypair) { @@ -520,7 +520,7 @@ impl TestValidatorGenesis { test_validator.wait_for_nonzero_fees().await; (test_validator, mint_keypair) } - Err(err) => panic!("Test validator failed to start: {}", err), + Err(err) => panic!("Test validator failed to start: {err}"), } } } @@ -849,7 +849,7 @@ impl TestValidator { // Needed to avoid panics in `solana-responder-gossip` in tests that create a number of // test validators concurrently... discover_cluster(&gossip, 1, socket_addr_space) - .map_err(|err| format!("TestValidator startup failed: {:?}", err))?; + .map_err(|err| format!("TestValidator startup failed: {err:?}"))?; let test_validator = TestValidator { ledger_path, @@ -887,7 +887,7 @@ impl TestValidator { if num_tries > MAX_TRIES { break; } - println!("Waiting for fees to stabilize {:?}...", num_tries); + println!("Waiting for fees to stabilize {num_tries:?}..."); match rpc_client.get_latest_blockhash().await { Ok(blockhash) => { message.recent_blockhash = blockhash; diff --git a/thin-client/src/thin_client.rs b/thin-client/src/thin_client.rs index 48192a311..7a43b71d2 100644 --- a/thin-client/src/thin_client.rs +++ b/thin-client/src/thin_client.rs @@ -246,7 +246,7 @@ impl ThinClient

{ } Err(io::Error::new( io::ErrorKind::Other, - format!("retry_transfer failed in {} retries", tries), + format!("retry_transfer failed in {tries} retries"), ) .into()) } @@ -454,7 +454,7 @@ impl SyncClient for ThinClient

{ .map_err(|err| { io::Error::new( io::ErrorKind::Other, - format!("send_transaction failed with error {:?}", err), + format!("send_transaction failed with error {err:?}"), ) })?; Ok(status) @@ -471,7 +471,7 @@ impl SyncClient for ThinClient

{ .map_err(|err| { io::Error::new( io::ErrorKind::Other, - format!("send_transaction failed with error {:?}", err), + format!("send_transaction failed with error {err:?}"), ) })?; Ok(status) @@ -491,7 +491,7 @@ impl SyncClient for ThinClient

{ .map_err(|err| { io::Error::new( io::ErrorKind::Other, - format!("send_transaction failed with error {:?}", err), + format!("send_transaction failed with error {err:?}"), ) })?; Ok(slot) diff --git a/tokens/src/commands.rs b/tokens/src/commands.rs index f91ce7181..9dbfbe415 100644 --- a/tokens/src/commands.rs +++ b/tokens/src/commands.rs @@ -76,7 +76,7 @@ impl std::fmt::Debug for FundingSources { if i > 0 { write!(f, "/")?; } - write!(f, "{:?}", source)?; + write!(f, "{source:?}")?; } Ok(()) } @@ -1581,7 +1581,7 @@ mod tests { use std::env; let out_dir = env::var("FARF_DIR").unwrap_or_else(|_| "farf".to_string()); - format!("{}/tmp/{}-{}", out_dir, name, pubkey) + format!("{out_dir}/tmp/{name}-{pubkey}") } fn initialize_check_payer_balances_inputs( diff --git a/tokens/src/db.rs b/tokens/src/db.rs index f8b462715..8074269b5 100644 --- a/tokens/src/db.rs +++ b/tokens/src/db.rs @@ -142,8 +142,7 @@ pub fn update_finalized_transaction( if opt_transaction_status.is_none() { if finalized_block_height > last_valid_block_height { eprintln!( - "Signature not found {} and blockhash expired. Transaction either dropped or the validator purged the transaction status.", - signature + "Signature not found {signature} and blockhash expired. Transaction either dropped or the validator purged the transaction status." ); eprintln!(); @@ -165,7 +164,7 @@ pub fn update_finalized_transaction( if let Some(e) = &transaction_status.err { // The transaction was finalized, but execution failed. Drop it. - eprintln!("Error in transaction with signature {}: {}", signature, e); + eprintln!("Error in transaction with signature {signature}: {e}"); eprintln!("Discarding transaction record"); eprintln!(); db.rem(&signature.to_string())?; diff --git a/tokens/src/spl_token.rs b/tokens/src/spl_token.rs index 5b80c850c..3850e7467 100644 --- a/tokens/src/spl_token.rs +++ b/tokens/src/spl_token.rs @@ -142,8 +142,8 @@ pub fn print_token_balances( let delta_string = real_number_string(recipient_token.amount - expected, spl_token_args.decimals); ( - style(format!("{:>24}", actual_ui_amount)), - format!("{:>24}", delta_string), + style(format!("{actual_ui_amount:>24}")), + format!("{delta_string:>24}"), ) } else { ( diff --git a/tokens/src/token_display.rs b/tokens/src/token_display.rs index c78ac26a6..726cced7c 100644 --- a/tokens/src/token_display.rs +++ b/tokens/src/token_display.rs @@ -26,11 +26,11 @@ impl Token { match &self.token_type { TokenType::Sol => { let amount = lamports_to_sol(self.amount); - write!(f, "{}{}", SOL_SYMBOL, amount) + write!(f, "{SOL_SYMBOL}{amount}") } TokenType::SplToken => { let amount = real_number_string_trimmed(self.amount, self.decimals); - write!(f, "{} tokens", amount) + write!(f, "{amount} tokens") } } } diff --git a/tpu-client/src/nonblocking/tpu_client.rs b/tpu-client/src/nonblocking/tpu_client.rs index f0c6cf158..0edafb4f0 100644 --- a/tpu-client/src/nonblocking/tpu_client.rs +++ b/tpu-client/src/nonblocking/tpu_client.rs @@ -482,10 +482,7 @@ impl TpuClient

{ total_transactions, Some(block_height), last_valid_block_height, - &format!( - "Waiting for next block, {} transactions pending...", - num_transactions - ), + &format!("Waiting for next block, {num_transactions} transactions pending..."), ); let mut new_block_height = block_height; while block_height == new_block_height && block_height_refreshes > 0 { @@ -514,10 +511,8 @@ impl TpuClient

{ if let Some((i, _)) = pending_transactions.remove(signature) { confirmed_transactions += 1; if status.err.is_some() { - progress_bar.println(format!( - "Failed transaction: {:?}", - status - )); + progress_bar + .println(format!("Failed transaction: {status:?}")); } transaction_errors[i] = status.err; } @@ -542,8 +537,7 @@ impl TpuClient

{ transactions = pending_transactions.into_values().collect(); progress_bar.println(format!( - "Blockhash expired. {} retries remaining", - expired_blockhash_retries + "Blockhash expired. {expired_blockhash_retries} retries remaining" )); expired_blockhash_retries -= 1; } diff --git a/tpu-client/src/tpu_connection_cache.rs b/tpu-client/src/tpu_connection_cache.rs index aa687634b..a9c58852a 100644 --- a/tpu-client/src/tpu_connection_cache.rs +++ b/tpu-client/src/tpu_connection_cache.rs @@ -506,7 +506,7 @@ mod tests { let c = rng.gen_range(1, 255); let d = rng.gen_range(1, 255); - let addr_str = format!("{}.{}.{}.{}:80", a, b, c, d); + let addr_str = format!("{a}.{b}.{c}.{d}:80"); addr_str.parse().expect("Invalid address") } diff --git a/transaction-dos/src/main.rs b/transaction-dos/src/main.rs index 96d94c8fe..0bea00049 100644 --- a/transaction-dos/src/main.rs +++ b/transaction-dos/src/main.rs @@ -69,22 +69,20 @@ pub fn airdrop_lamports( } if tries >= 5 { panic!( - "Error requesting airdrop: to addr: {:?} amount: {} {:?}", - faucet_addr, airdrop_amount, result + "Error requesting airdrop: to addr: {faucet_addr:?} amount: {airdrop_amount} {result:?}" ) } } } Err(err) => { panic!( - "Error requesting airdrop: {:?} to addr: {:?} amount: {}", - err, faucet_addr, airdrop_amount + "Error requesting airdrop: {err:?} to addr: {faucet_addr:?} amount: {airdrop_amount}" ); } }; let current_balance = client.get_balance(&id.pubkey()).unwrap_or_else(|e| { - panic!("airdrop error {}", e); + panic!("airdrop error {e}"); }); info!("current balance {}...", current_balance); @@ -544,14 +542,14 @@ fn main() { let mut entrypoint_addr = SocketAddr::from(([127, 0, 0, 1], port)); if let Some(addr) = matches.value_of("entrypoint") { entrypoint_addr = solana_net_utils::parse_host_port(addr).unwrap_or_else(|e| { - eprintln!("failed to parse entrypoint address: {}", e); + eprintln!("failed to parse entrypoint address: {e}"); exit(1) }); } let mut faucet_addr = SocketAddr::from(([127, 0, 0, 1], FAUCET_PORT)); if let Some(addr) = matches.value_of("faucet_addr") { faucet_addr = solana_net_utils::parse_host_port(addr).unwrap_or_else(|e| { - eprintln!("failed to parse entrypoint address: {}", e); + eprintln!("failed to parse entrypoint address: {e}"); exit(1) }); } @@ -563,7 +561,7 @@ fn main() { let num_program_iterations = value_t!(matches, "num_program_iterations", usize).unwrap_or(10); let num_instructions = value_t!(matches, "num_instructions", usize).unwrap_or(1); if num_instructions == 0 || num_instructions > 500 { - eprintln!("bad num_instructions: {}", num_instructions); + eprintln!("bad num_instructions: {num_instructions}"); exit(1); } let batch_sleep_ms = value_t!(matches, "batch_sleep_ms", u64).unwrap_or(500); @@ -574,7 +572,7 @@ fn main() { .iter() .map(|keypair_string| { read_keypair_file(keypair_string) - .unwrap_or_else(|_| panic!("bad keypair {:?}", keypair_string)) + .unwrap_or_else(|_| panic!("bad keypair {keypair_string:?}")) }) .collect(); @@ -582,7 +580,7 @@ fn main() { .iter() .map(|keypair_string| { read_keypair_file(keypair_string) - .unwrap_or_else(|_| panic!("bad keypair {:?}", keypair_string)) + .unwrap_or_else(|_| panic!("bad keypair {keypair_string:?}")) }) .collect(); @@ -604,7 +602,7 @@ fn main() { SocketAddrSpace::Unspecified, ) .unwrap_or_else(|err| { - eprintln!("Failed to discover {} node: {:?}", entrypoint_addr, err); + eprintln!("Failed to discover {entrypoint_addr} node: {err:?}"); exit(1); }); diff --git a/transaction-status/src/extract_memos.rs b/transaction-status/src/extract_memos.rs index 9e8308ae6..c040ad3b9 100644 --- a/transaction-status/src/extract_memos.rs +++ b/transaction-status/src/extract_memos.rs @@ -36,7 +36,7 @@ pub fn extract_and_fmt_memos(message: &T) -> Option { fn extract_and_fmt_memo_data(data: &[u8]) -> String { let memo_len = data.len(); let parsed_memo = parse_memo_data(data).unwrap_or_else(|_| "(unparseable)".to_string()); - format!("[{}] {}", memo_len, parsed_memo) + format!("[{memo_len}] {parsed_memo}") } pub trait ExtractMemos { diff --git a/transaction-status/src/lib.rs b/transaction-status/src/lib.rs index 4465666b7..0e833ce26 100644 --- a/transaction-status/src/lib.rs +++ b/transaction-status/src/lib.rs @@ -111,7 +111,7 @@ impl fmt::Display for UiTransactionEncoding { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let v = serde_json::to_value(self).map_err(|_| fmt::Error)?; let s = v.as_str().ok_or(fmt::Error)?; - write!(f, "{}", s) + write!(f, "{s}") } } diff --git a/transaction-status/src/parse_instruction.rs b/transaction-status/src/parse_instruction.rs index f4a2a9748..5e539ba94 100644 --- a/transaction-status/src/parse_instruction.rs +++ b/transaction-status/src/parse_instruction.rs @@ -136,7 +136,7 @@ pub fn parse( ParsableProgram::Vote => serde_json::to_value(parse_vote(instruction, account_keys)?)?, }; Ok(ParsedInstruction { - program: format!("{:?}", program_name).to_kebab_case(), + program: format!("{program_name:?}").to_kebab_case(), program_id: program_id.to_string(), parsed: parsed_json, stack_height, diff --git a/transaction-status/src/parse_token/extension/cpi_guard.rs b/transaction-status/src/parse_token/extension/cpi_guard.rs index 8d198249f..6c1373f6a 100644 --- a/transaction-status/src/parse_token/extension/cpi_guard.rs +++ b/transaction-status/src/parse_token/extension/cpi_guard.rs @@ -31,7 +31,7 @@ pub(in crate::parse_token) fn parse_cpi_guard_instruction( "multisigOwner", ); Ok(ParsedInstructionEnum { - instruction_type: format!("{}CpiGuard", instruction_type_str), + instruction_type: format!("{instruction_type_str}CpiGuard"), info: value, }) } diff --git a/transaction-status/src/parse_token/extension/default_account_state.rs b/transaction-status/src/parse_token/extension/default_account_state.rs index 3f0ab914a..f847e8f6c 100644 --- a/transaction-status/src/parse_token/extension/default_account_state.rs +++ b/transaction-status/src/parse_token/extension/default_account_state.rs @@ -19,7 +19,7 @@ pub(in crate::parse_token) fn parse_default_account_state_instruction( DefaultAccountStateInstruction::Initialize => { check_num_token_accounts(account_indexes, 1)?; Ok(ParsedInstructionEnum { - instruction_type: format!("initialize{}", instruction_type), + instruction_type: format!("initialize{instruction_type}"), info: json!({ "mint": account_keys[account_indexes[0] as usize].to_string(), "accountState": UiAccountState::from(account_state), @@ -42,7 +42,7 @@ pub(in crate::parse_token) fn parse_default_account_state_instruction( "multisigFreezeAuthority", ); Ok(ParsedInstructionEnum { - instruction_type: format!("update{}", instruction_type), + instruction_type: format!("update{instruction_type}"), info: value, }) } diff --git a/transaction-status/src/parse_token/extension/memo_transfer.rs b/transaction-status/src/parse_token/extension/memo_transfer.rs index c9783455b..98ee0fb8b 100644 --- a/transaction-status/src/parse_token/extension/memo_transfer.rs +++ b/transaction-status/src/parse_token/extension/memo_transfer.rs @@ -31,7 +31,7 @@ pub(in crate::parse_token) fn parse_memo_transfer_instruction( "multisigOwner", ); Ok(ParsedInstructionEnum { - instruction_type: format!("{}RequiredMemoTransfers", instruction_type_str), + instruction_type: format!("{instruction_type_str}RequiredMemoTransfers"), info: value, }) } diff --git a/upload-perf/src/upload-perf.rs b/upload-perf/src/upload-perf.rs index 16f8a433d..8117e12ef 100644 --- a/upload-perf/src/upload-perf.rs +++ b/upload-perf/src/upload-perf.rs @@ -11,8 +11,7 @@ use { fn get_last_metrics(metric: &str, db: &str, name: &str, branch: &str) -> Result { let query = format!( - r#"SELECT last("{}") FROM "{}"."autogen"."{}" WHERE "branch"='{}'"#, - metric, db, name, branch + r#"SELECT last("{metric}") FROM "{db}"."autogen"."{name}" WHERE "branch"='{branch}'"# ); let response = solana_metrics::query(&query)?; @@ -35,7 +34,7 @@ fn main() { // Open the path in read-only mode, returns `io::Result` let fname = &args[1]; let file = match File::open(fname) { - Err(why) => panic!("couldn't open {}: {:?}", fname, why), + Err(why) => panic!("couldn't open {fname}: {why:?}"), Ok(file) => file, }; @@ -90,8 +89,7 @@ fn main() { if let Some(commit) = last_commit { println!( - "Comparing current commits: {} against baseline {} on {} branch", - trimmed_hash, commit, branch + "Comparing current commits: {trimmed_hash} against baseline {commit} on {branch} branch" ); println!("bench_name, median, last_median, deviation, last_deviation"); for (entry, values) in results { @@ -105,8 +103,8 @@ fn main() { ); } } else { - println!("No previous results found for {} branch", branch); - println!("hash: {}", trimmed_hash); + println!("No previous results found for {branch} branch"); + println!("hash: {trimmed_hash}"); println!("bench_name, median, deviation"); for (entry, values) in results { println!("{}, {:10?}, {:10?}", entry, values.0, values.1); diff --git a/validator/src/admin_rpc_service.rs b/validator/src/admin_rpc_service.rs index 75a3971c7..eb2996fc1 100644 --- a/validator/src/admin_rpc_service.rs +++ b/validator/src/admin_rpc_service.rs @@ -239,7 +239,7 @@ impl AdminRpc for AdminRpcImpl { debug!("add_authorized_voter request received"); let authorized_voter = read_keypair_file(keypair_file) - .map_err(|err| jsonrpc_core::error::Error::invalid_params(format!("{}", err)))?; + .map_err(|err| jsonrpc_core::error::Error::invalid_params(format!("{err}")))?; AdminRpcImpl::add_authorized_voter_keypair(meta, authorized_voter) } @@ -253,8 +253,7 @@ impl AdminRpc for AdminRpcImpl { let authorized_voter = Keypair::from_bytes(&keypair).map_err(|err| { jsonrpc_core::error::Error::invalid_params(format!( - "Failed to read authorized voter keypair from provided byte array: {}", - err + "Failed to read authorized voter keypair from provided byte array: {err}" )) })?; @@ -277,8 +276,7 @@ impl AdminRpc for AdminRpcImpl { let identity_keypair = read_keypair_file(&keypair_file).map_err(|err| { jsonrpc_core::error::Error::invalid_params(format!( - "Failed to read identity keypair from {}: {}", - keypair_file, err + "Failed to read identity keypair from {keypair_file}: {err}" )) })?; @@ -295,8 +293,7 @@ impl AdminRpc for AdminRpcImpl { let identity_keypair = Keypair::from_bytes(&identity_keypair).map_err(|err| { jsonrpc_core::error::Error::invalid_params(format!( - "Failed to read identity keypair from provided byte array: {}", - err + "Failed to read identity keypair from provided byte array: {err}" )) })?; @@ -482,10 +479,6 @@ pub fn load_staked_nodes_overrides( let file = std::fs::File::open(path)?; Ok(serde_yaml::from_reader(file)?) } else { - Err(format!( - "Staked nodes overrides provided '{}' a non-existing file path.", - path - ) - .into()) + Err(format!("Staked nodes overrides provided '{path}' a non-existing file path.").into()) } } diff --git a/validator/src/bin/solana-test-validator.rs b/validator/src/bin/solana-test-validator.rs index 2df0b66db..a107d7a76 100644 --- a/validator/src/bin/solana-test-validator.rs +++ b/validator/src/bin/solana-test-validator.rs @@ -158,7 +158,7 @@ fn main() { let slots_per_epoch = value_t!(matches, "slots_per_epoch", Slot).ok(); let gossip_host = matches.value_of("gossip_host").map(|gossip_host| { solana_net_utils::parse_host(gossip_host).unwrap_or_else(|err| { - eprintln!("Failed to parse --gossip-host: {}", err); + eprintln!("Failed to parse --gossip-host: {err}"); exit(1); }) }); @@ -171,7 +171,7 @@ fn main() { }); let bind_address = matches.value_of("bind_address").map(|bind_address| { solana_net_utils::parse_host(bind_address).unwrap_or_else(|err| { - eprintln!("Failed to parse --bind-address: {}", err); + eprintln!("Failed to parse --bind-address: {err}"); exit(1); }) }); @@ -192,7 +192,7 @@ fn main() { .parse::() .or_else(|_| read_keypair_file(address).map(|keypair| keypair.pubkey())) .unwrap_or_else(|err| { - println!("Error: invalid address {}: {}", address, err); + println!("Error: invalid address {address}: {err}"); exit(1); }); @@ -226,7 +226,7 @@ fn main() { None } else { Some(address.parse::().unwrap_or_else(|err| { - println!("Error: invalid address {}: {}", address, err); + println!("Error: invalid address {address}: {err}"); exit(1); })) }; @@ -261,7 +261,7 @@ fn main() { }).get_slot() .unwrap_or_else(|err| { - println!("Unable to get current cluster slot: {}", err); + println!("Unable to get current cluster slot: {err}"); exit(1); }) } @@ -300,7 +300,7 @@ fn main() { let (sender, receiver) = unbounded(); run_local_faucet_with_port(faucet_keypair, sender, None, faucet_addr.port()); let _ = receiver.recv().expect("run faucet").unwrap_or_else(|err| { - println!("Error: failed to start faucet: {}", err); + println!("Error: failed to start faucet: {err}"); exit(1); }); } @@ -319,7 +319,7 @@ fn main() { ("deactivate_feature", "--deactivate-feature"), ] { if matches.is_present(name) { - println!("{} argument ignored, ledger already exists", long); + println!("{long} argument ignored, ledger already exists"); } } } else if random_mint { @@ -400,12 +400,12 @@ fn main() { .add_programs_with_path(&programs_to_load) .add_accounts_from_json_files(&accounts_to_load) .unwrap_or_else(|e| { - println!("Error: add_accounts_from_json_files failed: {}", e); + println!("Error: add_accounts_from_json_files failed: {e}"); exit(1); }) .add_accounts_from_directories(&accounts_from_dirs) .unwrap_or_else(|e| { - println!("Error: add_accounts_from_directories failed: {}", e); + println!("Error: add_accounts_from_directories failed: {e}"); exit(1); }) .deactivate_features(&features_to_deactivate); @@ -427,7 +427,7 @@ fn main() { .expect("bug: --url argument missing?"), false, ) { - println!("Error: clone_accounts failed: {}", e); + println!("Error: clone_accounts failed: {e}"); exit(1); } } @@ -440,7 +440,7 @@ fn main() { .expect("bug: --url argument missing?"), true, ) { - println!("Error: clone_accounts failed: {}", e); + println!("Error: clone_accounts failed: {e}"); exit(1); } } @@ -507,7 +507,7 @@ fn main() { } Err(err) => { drop(dashboard); - println!("Error: failed to start validator: {}", err); + println!("Error: failed to start validator: {err}"); exit(1); } } diff --git a/validator/src/bootstrap.rs b/validator/src/bootstrap.rs index 0b8cd989b..852c62928 100644 --- a/validator/src/bootstrap.rs +++ b/validator/src/bootstrap.rs @@ -195,7 +195,7 @@ fn get_rpc_peers( shred_version, retry_reason .as_ref() - .map(|s| format!(" (Retrying: {})", s)) + .map(|s| format!(" (Retrying: {s})")) .unwrap_or_default() ); @@ -253,9 +253,9 @@ fn check_vote_account( ) -> Result<(), String> { let vote_account = rpc_client .get_account_with_commitment(vote_account_address, CommitmentConfig::confirmed()) - .map_err(|err| format!("failed to fetch vote account: {}", err))? + .map_err(|err| format!("failed to fetch vote account: {err}"))? .value - .ok_or_else(|| format!("vote account does not exist: {}", vote_account_address))?; + .ok_or_else(|| format!("vote account does not exist: {vote_account_address}"))?; if vote_account.owner != solana_vote_program::id() { return Err(format!( @@ -266,9 +266,9 @@ fn check_vote_account( let identity_account = rpc_client .get_account_with_commitment(identity_pubkey, CommitmentConfig::confirmed()) - .map_err(|err| format!("failed to fetch identity account: {}", err))? + .map_err(|err| format!("failed to fetch identity account: {err}"))? .value - .ok_or_else(|| format!("identity account does not exist: {}", identity_pubkey))?; + .ok_or_else(|| format!("identity account does not exist: {identity_pubkey}"))?; let vote_state = solana_vote_program::vote_state::from(&vote_account); if let Some(vote_state) = vote_state { @@ -286,15 +286,13 @@ fn check_vote_account( for (_, vote_account_authorized_voter_pubkey) in vote_state.authorized_voters().iter() { if !authorized_voter_pubkeys.contains(vote_account_authorized_voter_pubkey) { return Err(format!( - "authorized voter {} not available", - vote_account_authorized_voter_pubkey + "authorized voter {vote_account_authorized_voter_pubkey} not available" )); } } } else { return Err(format!( - "invalid vote account data for {}", - vote_account_address + "invalid vote account data for {vote_account_address}" )); } @@ -393,12 +391,11 @@ pub fn attempt_download_genesis_and_snapshot( // downloading a snapshot from it let rpc_genesis_hash = rpc_client .get_genesis_hash() - .map_err(|err| format!("Failed to get genesis hash: {}", err))?; + .map_err(|err| format!("Failed to get genesis hash: {err}"))?; if expected_genesis_hash != rpc_genesis_hash { return Err(format!( - "Genesis hash mismatch: expected {} but RPC node genesis hash is {}", - expected_genesis_hash, rpc_genesis_hash + "Genesis hash mismatch: expected {expected_genesis_hash} but RPC node genesis hash is {rpc_genesis_hash}" )); } } @@ -410,7 +407,7 @@ pub fn attempt_download_genesis_and_snapshot( let rpc_client_slot = rpc_client .get_slot_with_commitment(CommitmentConfig::finalized()) - .map_err(|err| format!("Failed to get RPC node slot: {}", err))?; + .map_err(|err| format!("Failed to get RPC node slot: {err}"))?; info!("RPC node root slot: {}", rpc_client_slot); download_snapshots( @@ -555,7 +552,7 @@ pub fn rpc_bootstrap( } Err(err) => { fail_rpc_node( - format!("Failed to get RPC node version: {}", err), + format!("Failed to get RPC node version: {err}"), &validator_config.known_validators, &rpc_contact_info.id, &mut blacklisted_rpc_nodes.write().unwrap(), diff --git a/validator/src/cli.rs b/validator/src/cli.rs index e2fcc4a98..4b9c260a9 100644 --- a/validator/src/cli.rs +++ b/validator/src/cli.rs @@ -1114,7 +1114,7 @@ pub fn app<'a>(version: &'a str, default_args: &'a DefaultArgs) -> App<'a, 'a> { let core_index = usize::from_str(&s).map_err(|e| e.to_string())?; let max_index = core_affinity::get_core_ids().map(|cids| cids.len() - 1).unwrap_or(0); if core_index > max_index { - return Err(format!("core index must be in the range [0, {}]", max_index)); + return Err(format!("core index must be in the range [0, {max_index}]")); } Ok(()) }) @@ -1582,7 +1582,7 @@ pub fn warn_for_deprecated_arguments(matches: &ArgMatches) { if matches.is_present(arg) { warn!( "{}", - format!("--{} is deprecated. {}", arg, help).replace('_', "-") + format!("--{arg} is deprecated. {help}").replace('_', "-") ); } } @@ -1741,7 +1741,7 @@ impl Default for DefaultArgs { pub fn port_validator(port: String) -> Result<(), String> { port.parse::() .map(|_| ()) - .map_err(|e| format!("{:?}", e)) + .map_err(|e| format!("{e:?}")) } pub fn port_range_validator(port_range: String) -> Result<(), String> { @@ -1765,7 +1765,7 @@ pub fn port_range_validator(port_range: String) -> Result<(), String> { fn hash_validator(hash: String) -> Result<(), String> { Hash::from_str(&hash) .map(|_| ()) - .map_err(|e| format!("{:?}", e)) + .map_err(|e| format!("{e:?}")) } lazy_static! { @@ -1976,12 +1976,12 @@ pub fn test_app<'a>(version: &'a str, default_args: &'a DefaultTestArgs) -> App< .validator(|value| { value .parse::() - .map_err(|err| format!("error parsing '{}': {}", value, err)) + .map_err(|err| format!("error parsing '{value}': {err}")) .and_then(|path| { if path.exists() && path.is_dir() { Ok(()) } else { - Err(format!("path does not exist or is not a directory: {}", value)) + Err(format!("path does not exist or is not a directory: {value}")) } }) }) @@ -2014,10 +2014,10 @@ pub fn test_app<'a>(version: &'a str, default_args: &'a DefaultTestArgs) -> App< .validator(|value| { value .parse::() - .map_err(|err| format!("error parsing '{}': {}", value, err)) + .map_err(|err| format!("error parsing '{value}': {err}")) .and_then(|slot| { if slot < MINIMUM_SLOTS_PER_EPOCH { - Err(format!("value must be >= {}", MINIMUM_SLOTS_PER_EPOCH)) + Err(format!("value must be >= {MINIMUM_SLOTS_PER_EPOCH}")) } else { Ok(()) } diff --git a/validator/src/dashboard.rs b/validator/src/dashboard.rs index 09a6ae0e5..56df307d2 100644 --- a/validator/src/dashboard.rs +++ b/validator/src/dashboard.rs @@ -85,7 +85,7 @@ impl Dashboard { let mut identity = match rpc_client.get_identity() { Ok(identity) => identity, Err(err) => { - println!("Failed to get validator identity over RPC: {}", err); + println!("Failed to get validator identity over RPC: {err}"); continue; } }; @@ -110,7 +110,7 @@ impl Dashboard { println_name_value("TPU Address:", &tpu.to_string()); } if let Some(rpc) = contact_info.rpc { - println_name_value("JSON RPC URL:", &format!("http://{}", rpc)); + println_name_value("JSON RPC URL:", &format!("http://{rpc}")); } } @@ -181,8 +181,7 @@ impl Dashboard { thread::sleep(refresh_interval); } Err(err) => { - progress_bar - .abandon_with_message(format!("RPC connection failure: {}", err)); + progress_bar.abandon_with_message(format!("RPC connection failure: {err}")); break; } } @@ -207,7 +206,7 @@ async fn wait_for_validator_startup( match admin_rpc_service::connect(ledger_path).await { Ok(new_admin_client) => admin_client = Some(new_admin_client), Err(err) => { - progress_bar.set_message(format!("Unable to connect to validator: {}", err)); + progress_bar.set_message(format!("Unable to connect to validator: {err}")); thread::sleep(refresh_interval); continue; } @@ -230,17 +229,16 @@ async fn wait_for_validator_startup( Ok((Some(rpc_addr), start_time)) => return Some((rpc_addr, start_time)), Err(err) => { progress_bar - .set_message(format!("Failed to get validator info: {}", err)); + .set_message(format!("Failed to get validator info: {err}")); } } } else { - progress_bar.set_message(format!("Validator startup: {:?}...", start_progress)); + progress_bar.set_message(format!("Validator startup: {start_progress:?}...")); } } Err(err) => { admin_client = None; - progress_bar - .set_message(format!("Failed to get validator start progress: {}", err)); + progress_bar.set_message(format!("Failed to get validator start progress: {err}")); } } thread::sleep(refresh_interval); @@ -281,7 +279,7 @@ fn get_validator_stats( }, }) = &err.kind { - format!("{} slots behind", num_slots_behind) + format!("{num_slots_behind} slots behind") } else { "health unknown".to_string() } diff --git a/validator/src/lib.rs b/validator/src/lib.rs index 4b36c6ddb..4954331e1 100644 --- a/validator/src/lib.rs +++ b/validator/src/lib.rs @@ -33,7 +33,7 @@ fn redirect_stderr(filename: &str) { Ok(file) => unsafe { libc::dup2(file.as_raw_fd(), libc::STDERR_FILENO); }, - Err(err) => eprintln!("Unable to open {}: {}", filename, err), + Err(err) => eprintln!("Unable to open {filename}: {err}"), } } @@ -59,7 +59,7 @@ pub fn redirect_stderr_to_file(logfile: Option) -> Option let mut signals = signal_hook::iterator::Signals::new([signal_hook::consts::SIGUSR1]) .unwrap_or_else(|err| { - eprintln!("Unable to register SIGUSR1 handler: {:?}", err); + eprintln!("Unable to register SIGUSR1 handler: {err:?}"); exit(1); }); @@ -125,7 +125,7 @@ impl ProgressBar { if self.is_term { self.progress_bar.set_message(msg); } else { - println!("{}", msg); + println!("{msg}"); } } @@ -137,7 +137,7 @@ impl ProgressBar { if self.is_term { self.progress_bar.abandon_with_message(msg); } else { - println!("{}", msg); + println!("{msg}"); } } } diff --git a/validator/src/main.rs b/validator/src/main.rs index be3d77ef4..3971f80c6 100644 --- a/validator/src/main.rs +++ b/validator/src/main.rs @@ -106,7 +106,7 @@ fn wait_for_restart_window( let admin_client = admin_rpc_service::connect(ledger_path); let rpc_addr = admin_rpc_service::runtime() .block_on(async move { admin_client.await?.rpc_addr().await }) - .map_err(|err| format!("Unable to get validator RPC address: {}", err))?; + .map_err(|err| format!("Unable to get validator RPC address: {err}"))?; let rpc_client = match rpc_addr { None => return Err("RPC not available".into()), @@ -119,16 +119,10 @@ fn wait_for_restart_window( println_name_value("Identity:", &identity.to_string()); println_name_value( "Minimum Idle Time:", - &format!( - "{} slots (~{} minutes)", - min_idle_slots, min_idle_time_in_minutes - ), + &format!("{min_idle_slots} slots (~{min_idle_time_in_minutes} minutes)"), ); - println!( - "Maximum permitted delinquency: {}%", - max_delinquency_percentage - ); + println!("Maximum permitted delinquency: {max_delinquency_percentage}%"); let mut current_epoch = None; let mut leader_schedule = VecDeque::new(); @@ -183,10 +177,7 @@ fn wait_for_restart_window( }, )? .ok_or_else(|| { - format!( - "Unable to get leader schedule from slot {}", - first_slot_in_epoch - ) + format!("Unable to get leader schedule from slot {first_slot_in_epoch}") })? .get(&identity.to_string()) .cloned() @@ -266,8 +257,7 @@ fn wait_for_restart_window( ) } None => format!( - "Validator will be leader soon. Next leader slot is {}", - next_leader_slot + "Validator will be leader soon. Next leader slot is {next_leader_slot}" ), }) } @@ -388,10 +378,7 @@ fn validators_set( .into_iter() .collect(); if validators_set.contains(identity_pubkey) { - eprintln!( - "The validator's identity pubkey cannot be a {}: {}", - arg_name, identity_pubkey - ); + eprintln!("The validator's identity pubkey cannot be a {arg_name}: {identity_pubkey}"); exit(1); } Some(validators_set) @@ -408,8 +395,8 @@ fn get_cluster_shred_version(entrypoints: &[SocketAddr]) -> Option { }; for entrypoint in entrypoints { match solana_net_utils::get_cluster_shred_version(entrypoint) { - Err(err) => eprintln!("get_cluster_shred_version failed: {}, {}", entrypoint, err), - Ok(0) => eprintln!("zero shred-version from entrypoint: {}", entrypoint), + Err(err) => eprintln!("get_cluster_shred_version failed: {entrypoint}, {err}"), + Ok(0) => eprintln!("zero shred-version from entrypoint: {entrypoint}"), Ok(shred_version) => { info!( "obtained shred-version {} from {}", @@ -443,8 +430,7 @@ pub fn main() { let authorized_voter_keypair = fs::canonicalize(&authorized_voter_keypair) .unwrap_or_else(|err| { println!( - "Unable to access path: {}: {:?}", - authorized_voter_keypair, err + "Unable to access path: {authorized_voter_keypair}: {err:?}" ); exit(1); }); @@ -464,14 +450,14 @@ pub fn main() { .await }) .unwrap_or_else(|err| { - println!("addAuthorizedVoter request failed: {}", err); + println!("addAuthorizedVoter request failed: {err}"); exit(1); }); } else { let mut stdin = std::io::stdin(); let authorized_voter_keypair = read_keypair(&mut stdin).unwrap_or_else(|err| { - println!("Unable to read JSON keypair from stdin: {:?}", err); + println!("Unable to read JSON keypair from stdin: {err:?}"); exit(1); }); println!( @@ -490,7 +476,7 @@ pub fn main() { .await }) .unwrap_or_else(|err| { - println!("addAuthorizedVoterFromBytes request failed: {}", err); + println!("addAuthorizedVoterFromBytes request failed: {err}"); exit(1); }); } @@ -504,7 +490,7 @@ pub fn main() { admin_client.await?.remove_all_authorized_voters().await }) .unwrap_or_else(|err| { - println!("removeAllAuthorizedVoters request failed: {}", err); + println!("removeAllAuthorizedVoters request failed: {err}"); exit(1); }); println!("All authorized voters removed"); @@ -519,7 +505,7 @@ pub fn main() { let contact_info = admin_rpc_service::runtime() .block_on(async move { admin_client.await?.contact_info().await }) .unwrap_or_else(|err| { - eprintln!("Contact info query failed: {}", err); + eprintln!("Contact info query failed: {err}"); exit(1); }); if let Some(mode) = output_mode { @@ -529,7 +515,7 @@ pub fn main() { _ => unreachable!(), } } else { - print!("{}", contact_info); + print!("{contact_info}"); } return; } @@ -551,7 +537,7 @@ pub fn main() { skip_new_snapshot_check, ) .unwrap_or_else(|err| { - println!("{}", err); + println!("{err}"); exit(1); }); } @@ -560,7 +546,7 @@ pub fn main() { admin_rpc_service::runtime() .block_on(async move { admin_client.await?.exit().await }) .unwrap_or_else(|err| { - println!("exit request failed: {}", err); + println!("exit request failed: {err}"); exit(1); }); println!("Exit request sent"); @@ -593,7 +579,7 @@ pub fn main() { .await }) .unwrap_or_else(|err| { - println!("setStakedNodesOverrides request failed: {}", err); + println!("setStakedNodesOverrides request failed: {err}"); exit(1); }); return; @@ -603,7 +589,7 @@ pub fn main() { if let Some(identity_keypair) = value_t!(subcommand_matches, "identity", String).ok() { let identity_keypair = fs::canonicalize(&identity_keypair).unwrap_or_else(|err| { - println!("Unable to access path: {}: {:?}", identity_keypair, err); + println!("Unable to access path: {identity_keypair}: {err:?}"); exit(1); }); println!( @@ -620,13 +606,13 @@ pub fn main() { .await }) .unwrap_or_else(|err| { - println!("setIdentity request failed: {}", err); + println!("setIdentity request failed: {err}"); exit(1); }); } else { let mut stdin = std::io::stdin(); let identity_keypair = read_keypair(&mut stdin).unwrap_or_else(|err| { - println!("Unable to read JSON keypair from stdin: {:?}", err); + println!("Unable to read JSON keypair from stdin: {err:?}"); exit(1); }); println!("New validator identity: {}", identity_keypair.pubkey()); @@ -643,7 +629,7 @@ pub fn main() { .await }) .unwrap_or_else(|err| { - println!("setIdentityFromBytes request failed: {}", err); + println!("setIdentityFromBytes request failed: {err}"); exit(1); }); }; @@ -656,7 +642,7 @@ pub fn main() { admin_rpc_service::runtime() .block_on(async move { admin_client.await?.set_log_filter(filter).await }) .unwrap_or_else(|err| { - println!("set log filter failed: {}", err); + println!("set log filter failed: {err}"); exit(1); }); return; @@ -676,7 +662,7 @@ pub fn main() { skip_new_snapshot_check, ) .unwrap_or_else(|err| { - println!("{}", err); + println!("{err}"); exit(1); }); return; @@ -701,7 +687,7 @@ pub fn main() { if logfile == "-" { None } else { - println!("log file: {}", logfile); + println!("log file: {logfile}"); Some(logfile) } }; @@ -774,7 +760,7 @@ pub fn main() { // Canonicalize ledger path to avoid issues with symlink creation let _ = fs::create_dir_all(&ledger_path); let ledger_path = fs::canonicalize(&ledger_path).unwrap_or_else(|err| { - eprintln!("Unable to access ledger path: {:?}", err); + eprintln!("Unable to access ledger path: {err:?}"); exit(1); }); @@ -837,8 +823,7 @@ pub fn main() { let shrink_ratio = value_t_or_exit!(matches, "accounts_shrink_ratio", f64); if !(0.0..=1.0).contains(&shrink_ratio) { eprintln!( - "The specified account-shrink-ratio is invalid, it must be between 0. and 1.0 inclusive: {}", - shrink_ratio + "The specified account-shrink-ratio is invalid, it must be between 0. and 1.0 inclusive: {shrink_ratio}" ); exit(1); } @@ -853,7 +838,7 @@ pub fn main() { .into_iter() .map(|entrypoint| { solana_net_utils::parse_host_port(&entrypoint).unwrap_or_else(|e| { - eprintln!("failed to parse entrypoint address: {}", e); + eprintln!("failed to parse entrypoint address: {e}"); exit(1); }) }) @@ -862,7 +847,7 @@ pub fn main() { .collect::>(); for addr in &entrypoint_addrs { if !socket_addr_space.check(addr) { - eprintln!("invalid entrypoint address: {}", addr); + eprintln!("invalid entrypoint address: {addr}"); exit(1); } } @@ -892,7 +877,7 @@ pub fn main() { let read = |file| { fs::read(&file).unwrap_or_else(|err| { - eprintln!("Unable to read {}: {}", file, err); + eprintln!("Unable to read {file}: {err}"); exit(1) }) }; @@ -907,7 +892,7 @@ pub fn main() { Arc::new( tower_storage::EtcdTowerStorage::new(endpoints, Some(tls_config)) .unwrap_or_else(|err| { - eprintln!("Failed to connect to etcd: {}", err); + eprintln!("Failed to connect to etcd: {err}"); exit(1); }), ) @@ -1010,8 +995,7 @@ pub fn main() { if rpc_send_batch_send_rate_ms > rpc_send_retry_rate_ms { eprintln!( - "The specified rpc-send-batch-ms ({}) is invalid, it must be <= rpc-send-retry-ms ({})", - rpc_send_batch_send_rate_ms, rpc_send_retry_rate_ms + "The specified rpc-send-batch-ms ({rpc_send_batch_send_rate_ms}) is invalid, it must be <= rpc-send-retry-ms ({rpc_send_retry_rate_ms})" ); exit(1); } @@ -1199,10 +1183,7 @@ pub fn main() { match fs::create_dir_all(&account_path).and_then(|_| fs::canonicalize(&account_path)) { Ok(account_path) => account_path, Err(err) => { - eprintln!( - "Unable to access account path: {:?}, err: {:?}", - account_path, err - ); + eprintln!("Unable to access account path: {account_path:?}, err: {err:?}"); exit(1); } } @@ -1218,10 +1199,7 @@ pub fn main() { { Ok(account_path) => account_path, Err(err) => { - eprintln!( - "Unable to access account path: {:?}, err: {:?}", - account_path, err - ); + eprintln!("Unable to access account path: {account_path:?}, err: {err:?}"); exit(1); } } @@ -1278,7 +1256,7 @@ pub fn main() { let archive_format = { let archive_format_str = value_t_or_exit!(matches, "snapshot_archive_format", String); ArchiveFormat::from_cli_arg(&archive_format_str) - .unwrap_or_else(|| panic!("Archive format not recognized: {}", archive_format_str)) + .unwrap_or_else(|| panic!("Archive format not recognized: {archive_format_str}")) }; let snapshot_version = @@ -1286,7 +1264,7 @@ pub fn main() { .value_of("snapshot_version") .map_or(SnapshotVersion::default(), |s| { s.parse::().unwrap_or_else(|err| { - eprintln!("Error: {}", err); + eprintln!("Error: {err}"); exit(1) }) }); @@ -1356,8 +1334,7 @@ pub fn main() { }; if limit_ledger_size < DEFAULT_MIN_MAX_LEDGER_SHREDS { eprintln!( - "The provided --limit-ledger-size value was too small, the minimum value is {}", - DEFAULT_MIN_MAX_LEDGER_SHREDS + "The provided --limit-ledger-size value was too small, the minimum value is {DEFAULT_MIN_MAX_LEDGER_SHREDS}" ); exit(1); } @@ -1372,10 +1349,7 @@ pub fn main() { "snappy" => BlockstoreCompressionType::Snappy, "lz4" => BlockstoreCompressionType::Lz4, "zlib" => BlockstoreCompressionType::Zlib, - _ => panic!( - "Unsupported ledger_compression: {}", - ledger_compression_string - ), + _ => panic!("Unsupported ledger_compression: {ledger_compression_string}"), }, }, shred_storage_type: match matches.value_of("rocksdb_shred_compaction") { @@ -1392,10 +1366,7 @@ pub fn main() { u64 ))), }, - _ => panic!( - "Unrecognized rocksdb-shred-compaction: {}", - shred_compaction_string - ), + _ => panic!("Unrecognized rocksdb-shred-compaction: {shred_compaction_string}"), }, }, rocks_perf_sample_interval: value_t_or_exit!( @@ -1411,7 +1382,7 @@ pub fn main() { let public_rpc_addr = matches.value_of("public_rpc_addr").map(|addr| { solana_net_utils::parse_host_port(addr).unwrap_or_else(|e| { - eprintln!("failed to parse public rpc address: {}", e); + eprintln!("failed to parse public rpc address: {e}"); exit(1); }) }); @@ -1448,7 +1419,7 @@ pub fn main() { .value_of("gossip_host") .map(|gossip_host| { solana_net_utils::parse_host(gossip_host).unwrap_or_else(|err| { - eprintln!("Failed to parse --gossip-host: {}", err); + eprintln!("Failed to parse --gossip-host: {err}"); exit(1); }) }) @@ -1466,8 +1437,7 @@ pub fn main() { solana_net_utils::get_public_ip_addr(entrypoint_addr).map_or_else( |err| { eprintln!( - "Failed to contact cluster entrypoint {}: {}", - entrypoint_addr, err + "Failed to contact cluster entrypoint {entrypoint_addr}: {err}" ); None }, @@ -1489,7 +1459,7 @@ pub fn main() { value_t!(matches, "gossip_port", u16).unwrap_or_else(|_| { solana_net_utils::find_available_port_in_range(bind_address, (0, 1)).unwrap_or_else( |err| { - eprintln!("Unable to find an available gossip port: {}", err); + eprintln!("Unable to find an available gossip port: {err}"); exit(1); }, ) @@ -1498,7 +1468,7 @@ pub fn main() { let overwrite_tpu_addr = matches.value_of("tpu_host_addr").map(|tpu_addr| { solana_net_utils::parse_host_port(tpu_addr).unwrap_or_else(|err| { - eprintln!("Failed to parse --overwrite-tpu-addr: {}", err); + eprintln!("Failed to parse --overwrite-tpu-addr: {err}"); exit(1); }) }); @@ -1543,7 +1513,7 @@ pub fn main() { solana_metrics::set_host_id(identity_keypair.pubkey().to_string()); solana_metrics::set_panic_hook("validator", { - let version = format!("{:?}", solana_version); + let version = format!("{solana_version:?}"); Some(version) }); solana_entry::entry::init_poh(); diff --git a/version/src/lib.rs b/version/src/lib.rs index 6aeb1d798..0c862d886 100644 --- a/version/src/lib.rs +++ b/version/src/lib.rs @@ -89,7 +89,7 @@ impl fmt::Debug for Version { self.patch, match self.commit { None => "devbuild".to_string(), - Some(commit) => format!("{:08x}", commit), + Some(commit) => format!("{commit:08x}"), }, self.feature_set, ) diff --git a/watchtower/src/main.rs b/watchtower/src/main.rs index 0ee297925..cace26460 100644 --- a/watchtower/src/main.rs +++ b/watchtower/src/main.rs @@ -286,8 +286,7 @@ fn main() -> Result<(), Box> { failures.push(( "transaction-count", format!( - "Transaction count is not advancing: {} <= {}", - transaction_count, last_transaction_count + "Transaction count is not advancing: {transaction_count} <= {last_transaction_count}" ), )); } @@ -297,14 +296,14 @@ fn main() -> Result<(), Box> { } else { failures.push(( "recent-blockhash", - format!("Unable to get new blockhash: {}", recent_blockhash), + format!("Unable to get new blockhash: {recent_blockhash}"), )); } if config.monitor_active_stake && current_stake_percent < 80. { failures.push(( "current-stake", - format!("Current stake is {:.2}%", current_stake_percent), + format!("Current stake is {current_stake_percent:.2}%"), )); } @@ -319,14 +318,13 @@ fn main() -> Result<(), Box> { .iter() .any(|vai| vai.node_pubkey == *validator_identity.to_string()) { - validator_errors - .push(format!("{} delinquent", formatted_validator_identity)); + validator_errors.push(format!("{formatted_validator_identity} delinquent")); } else if !vote_accounts .current .iter() .any(|vai| vai.node_pubkey == *validator_identity.to_string()) { - validator_errors.push(format!("{} missing", formatted_validator_identity)); + validator_errors.push(format!("{formatted_validator_identity} missing")); } if let Some(balance) = validator_balances.get(validator_identity) { diff --git a/zk-token-sdk/src/encryption/discrete_log.rs b/zk-token-sdk/src/encryption/discrete_log.rs index 229517455..24e9ada47 100644 --- a/zk-token-sdk/src/encryption/discrete_log.rs +++ b/zk-token-sdk/src/encryption/discrete_log.rs @@ -260,10 +260,7 @@ mod tests { assert_eq!(amount, decoded.unwrap()); - println!( - "single thread discrete log computation secs: {:?} sec", - computation_secs - ); + println!("single thread discrete log computation secs: {computation_secs:?} sec"); } #[test] @@ -281,10 +278,7 @@ mod tests { assert_eq!(amount, decoded.unwrap()); - println!( - "4 thread discrete log computation: {:?} sec", - computation_secs - ); + println!("4 thread discrete log computation: {computation_secs:?} sec"); // amount 0 let amount: u64 = 0;