From b8837c04ec3976c9c16d028fbee86f87823fb97f Mon Sep 17 00:00:00 2001 From: Michael Vines Date: Fri, 3 Dec 2021 09:00:31 -0800 Subject: [PATCH] Reformat imports to a consistent style for imports rustfmt.toml configuration: imports_granularity = "One" group_imports = "One" --- account-decoder/src/lib.rs | 12 +- account-decoder/src/parse_account_data.rs | 40 ++- account-decoder/src/parse_bpf_loader.rs | 16 +- account-decoder/src/parse_config.rs | 29 +- account-decoder/src/parse_nonce.rs | 26 +- account-decoder/src/parse_stake.rs | 19 +- account-decoder/src/parse_sysvar.rs | 38 ++- account-decoder/src/parse_token.rs | 22 +- account-decoder/src/parse_vote.rs | 15 +- accounts-bench/src/main.rs | 22 +- accounts-cluster-bench/src/main.rs | 78 ++--- .../src/accountsdb_plugin_postgres.rs | 1 - banking-bench/src/main.rs | 65 ++-- banks-client/src/lib.rs | 20 +- banks-interface/src/lib.rs | 6 +- banks-server/src/banks_server.rs | 3 +- banks-server/src/rpc_banks_service.rs | 3 +- bench-streamer/src/main.rs | 30 +- bench-tps/src/bench.rs | 76 +++-- bench-tps/src/cli.rs | 16 +- bench-tps/src/main.rs | 26 +- bench-tps/tests/bench_tps.rs | 38 ++- bucket_map/benches/bucket_map.rs | 13 +- bucket_map/src/bucket.rs | 42 ++- bucket_map/src/bucket_api.rs | 27 +- bucket_map/src/bucket_item.rs | 3 +- bucket_map/src/bucket_map.rs | 26 +- bucket_map/src/bucket_stats.rs | 3 +- bucket_map/src/bucket_storage.rs | 27 +- bucket_map/src/index_entry.rs | 21 +- bucket_map/tests/bucket_map.rs | 12 +- clap-utils/src/input_parsers.rs | 10 +- clap-utils/src/input_validators.rs | 3 +- clap-utils/src/keypair.rs | 16 +- cli-config/src/config.rs | 8 +- cli-config/src/lib.rs | 1 - cli-output/src/cli_output.rs | 18 +- cli-output/src/display.rs | 6 +- cli/src/checks.rs | 34 +- cli/src/clap_app.rs | 14 +- cli/src/cli.rs | 104 +++--- cli/src/cluster_query.rs | 150 ++++----- cli/src/feature.rs | 52 +-- cli/src/inflation.rs | 28 +- cli/src/main.rs | 32 +- cli/src/memo.rs | 7 +- cli/src/nonce.rs | 96 +++--- cli/src/program.rs | 121 +++---- cli/src/spend_utils.rs | 22 +- cli/src/stake.rs | 114 +++---- cli/src/test_utils.rs | 8 +- cli/src/validator_info.rs | 66 ++-- cli/src/vote.rs | 68 ++-- cli/src/wallet.rs | 82 ++--- cli/tests/nonce.rs | 42 +-- cli/tests/program.rs | 38 ++- cli/tests/request_airdrop.rs | 18 +- cli/tests/stake.rs | 52 +-- cli/tests/transfer.rs | 42 +-- cli/tests/vote.rs | 36 +- client-test/tests/client.rs | 80 ++--- client/src/blockhash_query.rs | 22 +- client/src/client_error.rs | 5 +- client/src/rpc_client.rs | 29 +- client/src/rpc_custom_error.rs | 2 +- client/src/rpc_request.rs | 8 +- client/src/thin_client.rs | 3 +- client/src/tpu_client.rs | 60 ++-- client/src/transaction_executor.rs | 30 +- core/benches/banking_stage.rs | 73 +++-- core/benches/consensus.rs | 3 +- core/benches/gen_keys.rs | 3 +- core/benches/shredder.rs | 23 +- core/benches/sigverify_stage.rs | 32 +- core/src/accounts_hash_verifier.rs | 73 +++-- core/src/ancestor_hashes_service.rs | 110 ++++--- core/src/banking_stage.rs | 187 +++++------ core/src/broadcast_stage.rs | 44 +-- .../broadcast_fake_shreds_run.rs | 21 +- core/src/broadcast_stage/broadcast_utils.rs | 37 ++- .../broadcast_stage/standard_broadcast_run.rs | 30 +- core/src/cluster_info_vote_listener.rs | 140 ++++---- core/src/cluster_slot_state_verifier.rs | 34 +- core/src/cluster_slots.rs | 3 +- core/src/cluster_slots_service.rs | 28 +- core/src/commitment_service.rs | 66 ++-- core/src/completed_data_sets_service.rs | 36 +- core/src/cost_update_service.rs | 31 +- core/src/drop_bank_service.rs | 12 +- core/src/duplicate_repair_status.rs | 20 +- core/src/fetch_stage.rs | 33 +- core/src/fork_choice.rs | 22 +- core/src/gen_keys.rs | 14 +- core/src/heaviest_subtree_fork_choice.rs | 54 +-- ...latest_validator_votes_for_frozen_banks.rs | 8 +- core/src/ledger_cleanup_service.rs | 40 ++- core/src/optimistic_confirmation_verifier.rs | 24 +- core/src/outstanding_requests.rs | 18 +- core/src/progress_map.rs | 2 +- core/src/repair_generic_traversal.rs | 30 +- core/src/repair_response.rs | 34 +- core/src/repair_service.rs | 90 ++--- core/src/repair_weight.rs | 52 +-- core/src/repair_weighted_traversal.rs | 28 +- core/src/replay_stage.rs | 115 +++---- core/src/result.rs | 23 +- core/src/retransmit_stage.rs | 3 +- core/src/rewards_recorder_service.rs | 24 +- core/src/sample_performance_service.rs | 18 +- core/src/serve_repair.rs | 104 +++--- core/src/serve_repair_service.rs | 20 +- core/src/shred_fetch_stage.rs | 42 +-- core/src/sigverify.rs | 9 +- core/src/sigverify_shreds.rs | 38 ++- core/src/sigverify_stage.rs | 29 +- core/src/snapshot_packager_service.rs | 76 +++-- core/src/system_monitor_service.rs | 25 +- core/src/tpu.rs | 62 ++-- core/src/tvu.rs | 140 ++++---- .../unfrozen_gossip_verified_vote_hashes.rs | 8 +- core/src/validator.rs | 17 +- core/src/verified_vote_packets.rs | 40 ++- core/src/vote_simulator.rs | 54 +-- core/src/vote_stake_tracker.rs | 6 +- core/src/voting_service.rs | 20 +- core/src/window_service.rs | 9 +- core/tests/fork-selection.rs | 6 +- core/tests/ledger_cleanup.rs | 36 +- core/tests/snapshots.rs | 95 +++--- dos/src/main.rs | 31 +- download-utils/src/lib.rs | 29 +- entry/benches/entry_sigverify.rs | 24 +- entry/src/entry.rs | 93 +++--- entry/src/poh.rs | 18 +- faucet/src/faucet.rs | 4 +- faucet/tests/local-faucet.rs | 16 +- frozen-abi/src/abi_digester.rs | 25 +- frozen-abi/src/abi_example.rs | 12 +- frozen-abi/src/hash.rs | 6 +- genesis-utils/src/lib.rs | 14 +- genesis/src/genesis_accounts.rs | 10 +- genesis/src/main.rs | 87 ++--- genesis/src/stakes.rs | 3 +- genesis/src/unlocks.rs | 6 +- gossip/src/cluster_info.rs | 12 +- gossip/src/crds_value.rs | 4 +- gossip/src/duplicate_shred.rs | 18 +- gossip/src/gossip_service.rs | 5 +- gossip/src/weighted_shuffle.rs | 6 +- gossip/tests/gossip.rs | 12 +- install/src/command.rs | 33 +- install/src/config.rs | 8 +- keygen/src/keygen.rs | 64 ++-- ledger-tool/tests/basic.rs | 10 +- ledger/benches/blockstore.rs | 18 +- ledger/benches/protobuf.rs | 22 +- ledger/benches/sigverify_shreds.rs | 21 +- ledger/src/ancestor_iterator.rs | 16 +- ledger/src/bank_forks_utils.rs | 41 +-- ledger/src/bigtable_upload.rs | 24 +- ledger/src/blockstore.rs | 48 +-- ledger/src/blockstore/blockstore_purge.rs | 25 +- ledger/src/blockstore_db.rs | 67 ++-- ledger/src/blockstore_meta.rs | 8 +- ledger/src/blockstore_processor.rs | 180 +++++----- ledger/src/erasure.rs | 4 +- ledger/src/leader_schedule.rs | 19 +- ledger/src/leader_schedule_cache.rs | 73 +++-- ledger/src/leader_schedule_utils.rs | 23 +- ledger/src/next_slots_iterator.rs | 14 +- ledger/src/rooted_slot_iterator.rs | 16 +- ledger/src/shred.rs | 18 +- ledger/src/sigverify_shreds.rs | 55 ++-- ledger/tests/blockstore.rs | 15 +- ledger/tests/shred.rs | 32 +- local-cluster/src/cluster_tests.rs | 74 +++-- local-cluster/src/local_cluster.rs | 6 +- .../src/local_cluster_snapshot_utils.rs | 18 +- local-cluster/src/validator_configs.rs | 8 +- local-cluster/tests/local_cluster.rs | 9 +- log-analyzer/src/main.rs | 14 +- logger/src/lib.rs | 6 +- measure/src/measure.rs | 13 +- merkle-root-bench/src/main.rs | 10 +- metrics/src/counter.rs | 16 +- metrics/src/lib.rs | 1 - net-shaper/src/main.rs | 16 +- net-utils/src/bin/ip_address_server.rs | 6 +- net-utils/src/lib.rs | 13 +- notifier/src/lib.rs | 8 +- perf/benches/recycler.rs | 7 +- perf/benches/sigverify.rs | 9 +- perf/src/cuda_runtime.rs | 27 +- perf/src/packet.rs | 22 +- perf/src/perf_libs.rs | 26 +- perf/src/recycler.rs | 15 +- perf/src/recycler_cache.rs | 4 +- perf/src/sigverify.rs | 78 +++-- poh-bench/src/main.rs | 10 +- poh/src/poh_recorder.rs | 2 +- program-runtime/benches/pre_account.rs | 10 +- program-runtime/src/instruction_recorder.rs | 11 +- program-runtime/src/invoke_context.rs | 61 ++-- program-runtime/src/native_loader.rs | 40 +-- program-runtime/src/pre_account.rs | 34 +- program-runtime/src/stable_log.rs | 10 +- program-runtime/src/timings.rs | 3 +- program-test/src/lib.rs | 12 +- program-test/tests/builtins.rs | 13 +- program-test/tests/fuzz.rs | 11 +- programs/bpf_loader/benches/serialization.rs | 21 +- programs/bpf_loader/build.rs | 16 +- programs/bpf_loader/src/allocator_bump.rs | 11 +- programs/bpf_loader/src/lib.rs | 134 ++++---- programs/bpf_loader/src/serialization.rs | 51 +-- programs/bpf_loader/src/syscalls.rs | 112 ++++--- programs/compute-budget/src/lib.rs | 6 +- programs/config/src/config_instruction.rs | 13 +- programs/config/src/config_processor.rs | 48 +-- programs/config/src/date_instruction.rs | 14 +- programs/config/src/lib.rs | 19 +- programs/stake/src/config.rs | 25 +- programs/stake/src/lib.rs | 1 - programs/stake/src/stake_instruction.rs | 47 +-- programs/stake/src/stake_state.rs | 35 +- programs/vote/src/authorized_voters.rs | 10 +- programs/vote/src/vote_instruction.rs | 61 ++-- programs/vote/src/vote_state/mod.rs | 61 ++-- .../src/vote_state/vote_state_versions.rs | 3 +- programs/vote/src/vote_transaction.rs | 30 +- rbpf-cli/src/main.rs | 40 ++- rpc-test/tests/rpc.rs | 77 ++--- rpc/src/rpc.rs | 6 +- rpc/src/rpc_health.rs | 6 +- rpc/src/rpc_pubsub_service.rs | 10 +- rpc/src/rpc_service.rs | 7 +- rpc/src/rpc_subscription_tracker.rs | 12 +- rpc/src/rpc_subscriptions.rs | 3 +- runtime/benches/accounts.rs | 48 +-- runtime/benches/accounts_index.rs | 16 +- runtime/benches/append_vec.rs | 25 +- runtime/benches/bank.rs | 31 +- runtime/benches/bloom.rs | 21 +- runtime/benches/status_cache.rs | 14 +- runtime/src/accounts.rs | 131 ++++---- runtime/src/accounts_background_service.rs | 58 ++-- runtime/src/accounts_cache.rs | 30 +- runtime/src/accounts_db.rs | 165 +++++----- runtime/src/accounts_hash.rs | 20 +- runtime/src/accounts_index.rs | 73 +++-- runtime/src/accounts_index_storage.rs | 24 +- runtime/src/ancestors.rs | 13 +- runtime/src/append_vec.rs | 67 ++-- runtime/src/bank.rs | 308 +++++++++--------- runtime/src/bank_client.rs | 58 ++-- runtime/src/bank_forks.rs | 56 ++-- runtime/src/bank_utils.rs | 14 +- runtime/src/block_cost_limits.rs | 10 +- runtime/src/blockhash_queue.rs | 16 +- runtime/src/bloom.rs | 29 +- runtime/src/bucket_map_holder.rs | 43 ++- runtime/src/bucket_map_holder_stats.rs | 13 +- runtime/src/builtins.rs | 21 +- runtime/src/cache_hash_data.rs | 34 +- runtime/src/commitment.rs | 8 +- runtime/src/cost_model.rs | 55 ++-- runtime/src/cost_tracker.rs | 32 +- runtime/src/epoch_stakes.rs | 8 +- runtime/src/execute_cost_table.rs | 3 +- runtime/src/genesis_utils.rs | 31 +- runtime/src/hardened_unpack.rs | 11 +- runtime/src/in_mem_accounts_index.rs | 50 +-- runtime/src/loader_utils.rs | 22 +- runtime/src/message_processor.rs | 64 ++-- runtime/src/non_circulating_supply.rs | 17 +- runtime/src/nonce_keyed_account.rs | 48 +-- runtime/src/read_only_accounts_cache.rs | 33 +- runtime/src/rent_collector.rs | 3 +- runtime/src/secondary_index.rs | 18 +- runtime/src/serde_snapshot.rs | 16 +- runtime/src/serde_snapshot/common.rs | 3 +- runtime/src/serde_snapshot/future.rs | 10 +- runtime/src/shared_buffer_reader.rs | 8 +- runtime/src/snapshot_archive_info.rs | 8 +- runtime/src/snapshot_config.rs | 8 +- runtime/src/snapshot_package.rs | 39 ++- runtime/src/snapshot_utils.rs | 22 +- runtime/src/sorted_storages.rs | 9 +- runtime/src/stake_weighted_timestamp.rs | 6 +- runtime/src/stakes.rs | 12 +- runtime/src/status_cache.rs | 31 +- runtime/src/system_instruction_processor.rs | 49 +-- runtime/src/transaction_batch.rs | 8 +- runtime/src/vote_account.rs | 24 +- runtime/src/vote_sender_types.rs | 8 +- runtime/src/waitable_condvar.rs | 14 +- runtime/store-tool/src/main.rs | 8 +- runtime/tests/accounts.rs | 38 ++- runtime/tests/bank.rs | 8 +- runtime/tests/stake.rs | 46 +-- sdk/benches/serialize_instructions.rs | 18 +- sdk/benches/short_vec.rs | 4 +- sdk/benches/slot_hashes.rs | 12 +- sdk/benches/slot_history.rs | 10 +- sdk/cargo-build-bpf/src/main.rs | 3 +- sdk/cargo-test-bpf/src/main.rs | 23 +- sdk/macro/src/lib.rs | 24 +- sdk/program/src/account_info.rs | 16 +- sdk/program/src/blake3.rs | 10 +- sdk/program/src/bpf_loader_upgradeable.rs | 14 +- sdk/program/src/decode_error.rs | 3 +- sdk/program/src/entrypoint.rs | 26 +- sdk/program/src/entrypoint_deprecated.rs | 19 +- sdk/program/src/feature.rs | 3 +- sdk/program/src/fee_calculator.rs | 15 +- sdk/program/src/hash.rs | 12 +- sdk/program/src/instruction.rs | 13 +- sdk/program/src/keccak.rs | 12 +- sdk/program/src/lamports.rs | 3 +- sdk/program/src/message/legacy.rs | 38 ++- sdk/program/src/message/mapped.rs | 23 +- sdk/program/src/message/mod.rs | 5 +- sdk/program/src/message/sanitized.rs | 10 +- sdk/program/src/message/v0.rs | 3 +- sdk/program/src/message/versions.rs | 12 +- sdk/program/src/nonce/state/current.rs | 8 +- sdk/program/src/nonce/state/mod.rs | 1 - sdk/program/src/program_error.rs | 12 +- sdk/program/src/program_stubs.rs | 12 +- sdk/program/src/pubkey.rs | 3 +- sdk/program/src/secp256k1_recover.rs | 8 +- sdk/program/src/serialize_utils.rs | 3 +- sdk/program/src/short_vec.rs | 20 +- sdk/program/src/slot_hashes.rs | 9 +- sdk/program/src/slot_history.rs | 6 +- sdk/program/src/stake/instruction.rs | 13 +- sdk/program/src/stake_history.rs | 1 - sdk/program/src/system_instruction.rs | 28 +- sdk/program/src/sysvar/clock.rs | 1 - sdk/program/src/sysvar/epoch_schedule.rs | 1 - sdk/program/src/sysvar/instructions.rs | 8 +- sdk/program/src/sysvar/mod.rs | 14 +- sdk/program/src/sysvar/recent_blockhashes.rs | 17 +- sdk/program/src/sysvar/rent.rs | 1 - sdk/program/src/sysvar/slot_hashes.rs | 7 +- sdk/program/src/sysvar/slot_history.rs | 3 +- sdk/program/src/sysvar/stake_history.rs | 4 +- sdk/src/account.rs | 19 +- sdk/src/account_utils.rs | 17 +- sdk/src/commitment_config.rs | 3 +- sdk/src/compute_budget.rs | 10 +- sdk/src/derivation_path.rs | 3 +- sdk/src/deserialize_utils.rs | 3 +- sdk/src/ed25519_instruction.rs | 30 +- sdk/src/feature_set.rs | 14 +- sdk/src/genesis_config.rs | 65 ++-- sdk/src/hard_forks.rs | 6 +- sdk/src/keyed_account.rs | 32 +- sdk/src/native_loader.rs | 8 +- sdk/src/nonce_account.rs | 17 +- sdk/src/packet.rs | 14 +- sdk/src/poh_config.rs | 6 +- sdk/src/program_utils.rs | 3 +- sdk/src/pubkey.rs | 3 +- sdk/src/recent_blockhashes_account.rs | 30 +- sdk/src/secp256k1_instruction.rs | 40 ++- sdk/src/signature.rs | 21 +- sdk/src/signer/mod.rs | 3 +- sdk/src/signer/presigner.rs | 3 +- sdk/src/timing.rs | 10 +- sdk/src/transaction/mod.rs | 24 +- sdk/src/transport.rs | 4 +- stake-accounts/src/arg_parser.rs | 25 +- stake-accounts/src/args.rs | 19 +- stake-accounts/src/main.rs | 38 ++- stake-accounts/src/stake_accounts.rs | 20 +- storage-bigtable/src/access_token.rs | 3 +- storage-bigtable/src/bigtable.rs | 18 +- storage-proto/src/convert.rs | 6 +- streamer/src/packet.rs | 35 +- streamer/src/recvmmsg.rs | 11 +- streamer/src/sendmmsg.rs | 18 +- streamer/src/streamer.rs | 60 ++-- streamer/tests/recvmmsg.rs | 12 +- sys-tuner/src/main.rs | 6 +- tokens/src/arg_parser.rs | 32 +- tokens/src/commands.rs | 122 +++---- tokens/src/db.rs | 26 +- tokens/src/main.rs | 24 +- tokens/src/spl_token.rs | 32 +- tokens/src/token_display.rs | 12 +- tokens/tests/commands.rs | 12 +- transaction-dos/src/main.rs | 16 +- upload-perf/src/upload-perf.rs | 16 +- validator/src/lib.rs | 3 +- validator/src/main.rs | 9 +- version/src/lib.rs | 8 +- 397 files changed, 5990 insertions(+), 5175 deletions(-) diff --git a/account-decoder/src/lib.rs b/account-decoder/src/lib.rs index c2e2b3d46631b4..00f0b47543fa4a 100644 --- a/account-decoder/src/lib.rs +++ b/account-decoder/src/lib.rs @@ -17,8 +17,10 @@ pub mod validator_info; use { crate::parse_account_data::{parse_account_data, AccountAdditionalData, ParsedAccount}, solana_sdk::{ - account::ReadableAccount, account::WritableAccount, clock::Epoch, - fee_calculator::FeeCalculator, pubkey::Pubkey, + account::{ReadableAccount, WritableAccount}, + clock::Epoch, + fee_calculator::FeeCalculator, + pubkey::Pubkey, }, std::{ io::{Read, Write}, @@ -202,8 +204,10 @@ fn slice_data(data: &[u8], data_slice_config: Option) -> &[u8 #[cfg(test)] mod test { - use super::*; - use solana_sdk::account::{Account, AccountSharedData}; + use { + super::*, + solana_sdk::account::{Account, AccountSharedData}, + }; #[test] fn test_slice_data() { diff --git a/account-decoder/src/parse_account_data.rs b/account-decoder/src/parse_account_data.rs index 40993ee59dcade..35fff127e0ca58 100644 --- a/account-decoder/src/parse_account_data.rs +++ b/account-decoder/src/parse_account_data.rs @@ -1,17 +1,19 @@ -use crate::{ - parse_bpf_loader::parse_bpf_upgradeable_loader, - parse_config::parse_config, - parse_nonce::parse_nonce, - parse_stake::parse_stake, - parse_sysvar::parse_sysvar, - parse_token::{parse_token, spl_token_id}, - parse_vote::parse_vote, +use { + crate::{ + parse_bpf_loader::parse_bpf_upgradeable_loader, + parse_config::parse_config, + parse_nonce::parse_nonce, + parse_stake::parse_stake, + parse_sysvar::parse_sysvar, + parse_token::{parse_token, spl_token_id}, + parse_vote::parse_vote, + }, + inflector::Inflector, + serde_json::Value, + solana_sdk::{instruction::InstructionError, pubkey::Pubkey, stake, system_program, sysvar}, + std::collections::HashMap, + thiserror::Error, }; -use inflector::Inflector; -use serde_json::Value; -use solana_sdk::{instruction::InstructionError, pubkey::Pubkey, stake, system_program, sysvar}; -use std::collections::HashMap; -use thiserror::Error; lazy_static! { static ref BPF_UPGRADEABLE_LOADER_PROGRAM_ID: Pubkey = solana_sdk::bpf_loader_upgradeable::id(); @@ -112,12 +114,14 @@ pub fn parse_account_data( #[cfg(test)] mod test { - use super::*; - use solana_sdk::nonce::{ - state::{Data, Versions}, - State, + use { + super::*, + solana_sdk::nonce::{ + state::{Data, Versions}, + State, + }, + solana_vote_program::vote_state::{VoteState, VoteStateVersions}, }; - use solana_vote_program::vote_state::{VoteState, VoteStateVersions}; #[test] fn test_parse_account_data() { diff --git a/account-decoder/src/parse_bpf_loader.rs b/account-decoder/src/parse_bpf_loader.rs index d12753dcf73b55..8eb9ac698ca1d8 100644 --- a/account-decoder/src/parse_bpf_loader.rs +++ b/account-decoder/src/parse_bpf_loader.rs @@ -1,9 +1,11 @@ -use crate::{ - parse_account_data::{ParsableAccount, ParseAccountError}, - UiAccountData, UiAccountEncoding, +use { + crate::{ + parse_account_data::{ParsableAccount, ParseAccountError}, + UiAccountData, UiAccountEncoding, + }, + bincode::{deserialize, serialized_size}, + solana_sdk::{bpf_loader_upgradeable::UpgradeableLoaderState, pubkey::Pubkey}, }; -use bincode::{deserialize, serialized_size}; -use solana_sdk::{bpf_loader_upgradeable::UpgradeableLoaderState, pubkey::Pubkey}; pub fn parse_bpf_upgradeable_loader( data: &[u8], @@ -90,9 +92,7 @@ pub struct UiProgramData { #[cfg(test)] mod test { - use super::*; - use bincode::serialize; - use solana_sdk::pubkey::Pubkey; + use {super::*, bincode::serialize, solana_sdk::pubkey::Pubkey}; #[test] fn test_parse_bpf_upgradeable_loader_accounts() { diff --git a/account-decoder/src/parse_config.rs b/account-decoder/src/parse_config.rs index e4cdf2457ef0d4..ecdcdbf1e46fdc 100644 --- a/account-decoder/src/parse_config.rs +++ b/account-decoder/src/parse_config.rs @@ -1,12 +1,16 @@ -use crate::{ - parse_account_data::{ParsableAccount, ParseAccountError}, - validator_info, +use { + crate::{ + parse_account_data::{ParsableAccount, ParseAccountError}, + validator_info, + }, + bincode::deserialize, + serde_json::Value, + solana_config_program::{get_config_data, ConfigKeys}, + solana_sdk::{ + pubkey::Pubkey, + stake::config::{self as stake_config, Config as StakeConfig}, + }, }; -use bincode::deserialize; -use serde_json::Value; -use solana_config_program::{get_config_data, ConfigKeys}; -use solana_sdk::pubkey::Pubkey; -use solana_sdk::stake::config::{self as stake_config, Config as StakeConfig}; pub fn parse_config(data: &[u8], pubkey: &Pubkey) -> Result { let parsed_account = if pubkey == &stake_config::id() { @@ -87,11 +91,10 @@ pub struct UiConfig { #[cfg(test)] mod test { - use super::*; - use crate::validator_info::ValidatorInfo; - use serde_json::json; - use solana_config_program::create_config_account; - use solana_sdk::account::ReadableAccount; + use { + super::*, crate::validator_info::ValidatorInfo, serde_json::json, + solana_config_program::create_config_account, solana_sdk::account::ReadableAccount, + }; #[test] fn test_parse_config() { diff --git a/account-decoder/src/parse_nonce.rs b/account-decoder/src/parse_nonce.rs index aaa305f65825a2..d013a84f98cf92 100644 --- a/account-decoder/src/parse_nonce.rs +++ b/account-decoder/src/parse_nonce.rs @@ -1,7 +1,9 @@ -use crate::{parse_account_data::ParseAccountError, UiFeeCalculator}; -use solana_sdk::{ - instruction::InstructionError, - nonce::{state::Versions, State}, +use { + crate::{parse_account_data::ParseAccountError, UiFeeCalculator}, + solana_sdk::{ + instruction::InstructionError, + nonce::{state::Versions, State}, + }, }; pub fn parse_nonce(data: &[u8]) -> Result { @@ -42,14 +44,16 @@ pub struct UiNonceData { #[cfg(test)] mod test { - use super::*; - use solana_sdk::{ - hash::Hash, - nonce::{ - state::{Data, Versions}, - State, + use { + super::*, + solana_sdk::{ + hash::Hash, + nonce::{ + state::{Data, Versions}, + State, + }, + pubkey::Pubkey, }, - pubkey::Pubkey, }; #[test] diff --git a/account-decoder/src/parse_stake.rs b/account-decoder/src/parse_stake.rs index fa3d3def6a25da..daafdc44f4d8e2 100644 --- a/account-decoder/src/parse_stake.rs +++ b/account-decoder/src/parse_stake.rs @@ -1,10 +1,14 @@ -use crate::{ - parse_account_data::{ParsableAccount, ParseAccountError}, - StringAmount, +use { + crate::{ + parse_account_data::{ParsableAccount, ParseAccountError}, + StringAmount, + }, + bincode::deserialize, + solana_sdk::{ + clock::{Epoch, UnixTimestamp}, + stake::state::{Authorized, Delegation, Lockup, Meta, Stake, StakeState}, + }, }; -use bincode::deserialize; -use solana_sdk::clock::{Epoch, UnixTimestamp}; -use solana_sdk::stake::state::{Authorized, Delegation, Lockup, Meta, Stake, StakeState}; pub fn parse_stake(data: &[u8]) -> Result { let stake_state: StakeState = deserialize(data) @@ -132,8 +136,7 @@ impl From for UiDelegation { #[cfg(test)] mod test { - use super::*; - use bincode::serialize; + use {super::*, bincode::serialize}; #[test] fn test_parse_stake() { diff --git a/account-decoder/src/parse_sysvar.rs b/account-decoder/src/parse_sysvar.rs index 1fae39afce8df2..e5896f9977bf05 100644 --- a/account-decoder/src/parse_sysvar.rs +++ b/account-decoder/src/parse_sysvar.rs @@ -1,20 +1,22 @@ -use crate::{ - parse_account_data::{ParsableAccount, ParseAccountError}, - StringAmount, UiFeeCalculator, -}; -use bincode::deserialize; -use bv::BitVec; #[allow(deprecated)] use solana_sdk::sysvar::{fees::Fees, recent_blockhashes::RecentBlockhashes}; -use solana_sdk::{ - clock::{Clock, Epoch, Slot, UnixTimestamp}, - epoch_schedule::EpochSchedule, - pubkey::Pubkey, - rent::Rent, - slot_hashes::SlotHashes, - slot_history::{self, SlotHistory}, - stake_history::{StakeHistory, StakeHistoryEntry}, - sysvar::{self, rewards::Rewards}, +use { + crate::{ + parse_account_data::{ParsableAccount, ParseAccountError}, + StringAmount, UiFeeCalculator, + }, + bincode::deserialize, + bv::BitVec, + solana_sdk::{ + clock::{Clock, Epoch, Slot, UnixTimestamp}, + epoch_schedule::EpochSchedule, + pubkey::Pubkey, + rent::Rent, + slot_hashes::SlotHashes, + slot_history::{self, SlotHistory}, + stake_history::{StakeHistory, StakeHistoryEntry}, + sysvar::{self, rewards::Rewards}, + }, }; pub fn parse_sysvar(data: &[u8], pubkey: &Pubkey) -> Result { @@ -218,10 +220,12 @@ pub struct UiStakeHistoryEntry { #[cfg(test)] mod test { - use super::*; #[allow(deprecated)] use solana_sdk::sysvar::recent_blockhashes::IterItem; - use solana_sdk::{account::create_account_for_test, fee_calculator::FeeCalculator, hash::Hash}; + use { + super::*, + solana_sdk::{account::create_account_for_test, fee_calculator::FeeCalculator, hash::Hash}, + }; #[test] fn test_parse_sysvars() { diff --git a/account-decoder/src/parse_token.rs b/account-decoder/src/parse_token.rs index b89df025c10f52..b733f5746edbdd 100644 --- a/account-decoder/src/parse_token.rs +++ b/account-decoder/src/parse_token.rs @@ -1,15 +1,17 @@ -use crate::{ - parse_account_data::{ParsableAccount, ParseAccountError}, - StringAmount, StringDecimals, -}; -use solana_sdk::pubkey::Pubkey; -use spl_token::{ - solana_program::{ - program_option::COption, program_pack::Pack, pubkey::Pubkey as SplTokenPubkey, +use { + crate::{ + parse_account_data::{ParsableAccount, ParseAccountError}, + StringAmount, StringDecimals, + }, + solana_sdk::pubkey::Pubkey, + spl_token::{ + solana_program::{ + program_option::COption, program_pack::Pack, pubkey::Pubkey as SplTokenPubkey, + }, + state::{Account, AccountState, Mint, Multisig}, }, - state::{Account, AccountState, Mint, Multisig}, + std::str::FromStr, }; -use std::str::FromStr; // A helper function to convert spl_token::id() as spl_sdk::pubkey::Pubkey to // solana_sdk::pubkey::Pubkey diff --git a/account-decoder/src/parse_vote.rs b/account-decoder/src/parse_vote.rs index a1aca278ee8b6a..b383b283900c4e 100644 --- a/account-decoder/src/parse_vote.rs +++ b/account-decoder/src/parse_vote.rs @@ -1,9 +1,11 @@ -use crate::{parse_account_data::ParseAccountError, StringAmount}; -use solana_sdk::{ - clock::{Epoch, Slot}, - pubkey::Pubkey, +use { + crate::{parse_account_data::ParseAccountError, StringAmount}, + solana_sdk::{ + clock::{Epoch, Slot}, + pubkey::Pubkey, + }, + solana_vote_program::vote_state::{BlockTimestamp, Lockout, VoteState}, }; -use solana_vote_program::vote_state::{BlockTimestamp, Lockout, VoteState}; pub fn parse_vote(data: &[u8]) -> Result { let mut vote_state = VoteState::deserialize(data).map_err(ParseAccountError::from)?; @@ -121,8 +123,7 @@ struct UiEpochCredits { #[cfg(test)] mod test { - use super::*; - use solana_vote_program::vote_state::VoteStateVersions; + use {super::*, solana_vote_program::vote_state::VoteStateVersions}; #[test] fn test_parse_vote() { diff --git a/accounts-bench/src/main.rs b/accounts-bench/src/main.rs index a0b2dd411a84d3..6e0a92a2fa0a76 100644 --- a/accounts-bench/src/main.rs +++ b/accounts-bench/src/main.rs @@ -1,17 +1,19 @@ #![allow(clippy::integer_arithmetic)] #[macro_use] extern crate log; -use clap::{crate_description, crate_name, value_t, App, Arg}; -use rayon::prelude::*; -use solana_measure::measure::Measure; -use solana_runtime::{ - accounts::{create_test_accounts, update_accounts_bench, Accounts}, - accounts_db::AccountShrinkThreshold, - accounts_index::AccountSecondaryIndexes, - ancestors::Ancestors, +use { + clap::{crate_description, crate_name, value_t, App, Arg}, + rayon::prelude::*, + solana_measure::measure::Measure, + solana_runtime::{ + accounts::{create_test_accounts, update_accounts_bench, Accounts}, + accounts_db::AccountShrinkThreshold, + accounts_index::AccountSecondaryIndexes, + ancestors::Ancestors, + }, + solana_sdk::{genesis_config::ClusterType, pubkey::Pubkey}, + std::{env, fs, path::PathBuf}, }; -use solana_sdk::{genesis_config::ClusterType, pubkey::Pubkey}; -use std::{env, fs, path::PathBuf}; fn main() { solana_logger::setup(); diff --git a/accounts-cluster-bench/src/main.rs b/accounts-cluster-bench/src/main.rs index a75e9024b18fb4..4d6d029f64dda9 100644 --- a/accounts-cluster-bench/src/main.rs +++ b/accounts-cluster-bench/src/main.rs @@ -1,35 +1,37 @@ #![allow(clippy::integer_arithmetic)] -use clap::{crate_description, crate_name, value_t, values_t_or_exit, App, Arg}; -use log::*; -use rand::{thread_rng, Rng}; -use rayon::prelude::*; -use solana_account_decoder::parse_token::spl_token_pubkey; -use solana_clap_utils::input_parsers::pubkey_of; -use solana_client::{rpc_client::RpcClient, transaction_executor::TransactionExecutor}; -use solana_faucet::faucet::{request_airdrop_transaction, FAUCET_PORT}; -use solana_gossip::gossip_service::discover; -use solana_runtime::inline_spl_token; -use solana_sdk::{ - commitment_config::CommitmentConfig, - instruction::{AccountMeta, Instruction}, - message::Message, - pubkey::Pubkey, - rpc_port::DEFAULT_RPC_PORT, - signature::{read_keypair_file, Keypair, Signer}, - system_instruction, system_program, - transaction::Transaction, -}; -use solana_streamer::socket::SocketAddrSpace; -use solana_transaction_status::parse_token::spl_token_instruction; -use std::{ - net::SocketAddr, - process::exit, - sync::{ - atomic::{AtomicU64, Ordering}, - Arc, +use { + clap::{crate_description, crate_name, value_t, values_t_or_exit, App, Arg}, + log::*, + rand::{thread_rng, Rng}, + rayon::prelude::*, + solana_account_decoder::parse_token::spl_token_pubkey, + solana_clap_utils::input_parsers::pubkey_of, + solana_client::{rpc_client::RpcClient, transaction_executor::TransactionExecutor}, + solana_faucet::faucet::{request_airdrop_transaction, FAUCET_PORT}, + solana_gossip::gossip_service::discover, + solana_runtime::inline_spl_token, + solana_sdk::{ + commitment_config::CommitmentConfig, + instruction::{AccountMeta, Instruction}, + message::Message, + pubkey::Pubkey, + rpc_port::DEFAULT_RPC_PORT, + signature::{read_keypair_file, Keypair, Signer}, + system_instruction, system_program, + transaction::Transaction, + }, + solana_streamer::socket::SocketAddrSpace, + solana_transaction_status::parse_token::spl_token_instruction, + std::{ + net::SocketAddr, + process::exit, + sync::{ + atomic::{AtomicU64, Ordering}, + Arc, + }, + thread::sleep, + time::{Duration, Instant}, }, - thread::sleep, - time::{Duration, Instant}, }; pub fn airdrop_lamports( @@ -559,14 +561,16 @@ fn main() { #[cfg(test)] pub mod test { - use super::*; - use solana_core::validator::ValidatorConfig; - use solana_local_cluster::{ - local_cluster::{ClusterConfig, LocalCluster}, - validator_configs::make_identical_validator_configs, + use { + super::*, + solana_core::validator::ValidatorConfig, + solana_local_cluster::{ + local_cluster::{ClusterConfig, LocalCluster}, + validator_configs::make_identical_validator_configs, + }, + solana_measure::measure::Measure, + solana_sdk::poh_config::PohConfig, }; - use solana_measure::measure::Measure; - use solana_sdk::poh_config::PohConfig; #[test] fn test_accounts_cluster_bench() { diff --git a/accountsdb-plugin-postgres/src/accountsdb_plugin_postgres.rs b/accountsdb-plugin-postgres/src/accountsdb_plugin_postgres.rs index 698a0512a5486d..cecdbb6fa51829 100644 --- a/accountsdb-plugin-postgres/src/accountsdb_plugin_postgres.rs +++ b/accountsdb-plugin-postgres/src/accountsdb_plugin_postgres.rs @@ -1,5 +1,4 @@ use solana_measure::measure::Measure; - /// Main entry for the PostgreSQL plugin use { crate::{ diff --git a/banking-bench/src/main.rs b/banking-bench/src/main.rs index 27e8dde3261bff..24ba546676bb56 100644 --- a/banking-bench/src/main.rs +++ b/banking-bench/src/main.rs @@ -1,36 +1,37 @@ #![allow(clippy::integer_arithmetic)] -use clap::{crate_description, crate_name, value_t, App, Arg}; -use crossbeam_channel::unbounded; -use log::*; -use rand::{thread_rng, Rng}; -use rayon::prelude::*; -use solana_core::banking_stage::BankingStage; -use solana_gossip::{cluster_info::ClusterInfo, cluster_info::Node}; -use solana_ledger::{ - blockstore::Blockstore, - genesis_utils::{create_genesis_config, GenesisConfigInfo}, - get_tmp_ledger_path, -}; -use solana_measure::measure::Measure; -use solana_perf::packet::to_packets_chunked; -use solana_poh::poh_recorder::{create_test_recorder, PohRecorder, WorkingBankEntry}; -use solana_runtime::{ - accounts_background_service::AbsRequestSender, bank::Bank, bank_forks::BankForks, - cost_model::CostModel, -}; -use solana_sdk::{ - hash::Hash, - signature::Keypair, - signature::Signature, - system_transaction, - timing::{duration_as_us, timestamp}, - transaction::Transaction, -}; -use solana_streamer::socket::SocketAddrSpace; -use std::{ - sync::{atomic::Ordering, mpsc::Receiver, Arc, Mutex, RwLock}, - thread::sleep, - time::{Duration, Instant}, +use { + clap::{crate_description, crate_name, value_t, App, Arg}, + crossbeam_channel::unbounded, + log::*, + rand::{thread_rng, Rng}, + rayon::prelude::*, + solana_core::banking_stage::BankingStage, + solana_gossip::cluster_info::{ClusterInfo, Node}, + solana_ledger::{ + blockstore::Blockstore, + genesis_utils::{create_genesis_config, GenesisConfigInfo}, + get_tmp_ledger_path, + }, + solana_measure::measure::Measure, + solana_perf::packet::to_packets_chunked, + solana_poh::poh_recorder::{create_test_recorder, PohRecorder, WorkingBankEntry}, + solana_runtime::{ + accounts_background_service::AbsRequestSender, bank::Bank, bank_forks::BankForks, + cost_model::CostModel, + }, + solana_sdk::{ + hash::Hash, + signature::{Keypair, Signature}, + system_transaction, + timing::{duration_as_us, timestamp}, + transaction::Transaction, + }, + solana_streamer::socket::SocketAddrSpace, + std::{ + sync::{atomic::Ordering, mpsc::Receiver, Arc, Mutex, RwLock}, + thread::sleep, + time::{Duration, Instant}, + }, }; fn check_txs( diff --git a/banks-client/src/lib.rs b/banks-client/src/lib.rs index 59ca0dbfa3321c..1623705176ed00 100644 --- a/banks-client/src/lib.rs +++ b/banks-client/src/lib.rs @@ -379,16 +379,18 @@ pub async fn start_tcp_client(addr: T) -> io::Result) -> JoinHandle<()> { let send = UdpSocket::bind("0.0.0.0:0").unwrap(); diff --git a/bench-tps/src/bench.rs b/bench-tps/src/bench.rs index 9c966d24daeaca..fe7c4f79157ae0 100644 --- a/bench-tps/src/bench.rs +++ b/bench-tps/src/bench.rs @@ -1,34 +1,36 @@ -use crate::cli::Config; -use log::*; -use rayon::prelude::*; -use solana_client::perf_utils::{sample_txs, SampleStats}; -use solana_core::gen_keys::GenKeys; -use solana_faucet::faucet::request_airdrop_transaction; -use solana_measure::measure::Measure; -use solana_metrics::{self, datapoint_info}; -use solana_sdk::{ - client::Client, - clock::{DEFAULT_MS_PER_SLOT, DEFAULT_S_PER_SLOT, MAX_PROCESSING_AGE}, - commitment_config::CommitmentConfig, - hash::Hash, - instruction::{AccountMeta, Instruction}, - message::Message, - pubkey::Pubkey, - signature::{Keypair, Signer}, - system_instruction, system_transaction, - timing::{duration_as_ms, duration_as_s, duration_as_us, timestamp}, - transaction::Transaction, -}; -use std::{ - collections::{HashSet, VecDeque}, - net::SocketAddr, - process::exit, - sync::{ - atomic::{AtomicBool, AtomicIsize, AtomicUsize, Ordering}, - Arc, Mutex, RwLock, +use { + crate::cli::Config, + log::*, + rayon::prelude::*, + solana_client::perf_utils::{sample_txs, SampleStats}, + solana_core::gen_keys::GenKeys, + solana_faucet::faucet::request_airdrop_transaction, + solana_measure::measure::Measure, + solana_metrics::{self, datapoint_info}, + solana_sdk::{ + client::Client, + clock::{DEFAULT_MS_PER_SLOT, DEFAULT_S_PER_SLOT, MAX_PROCESSING_AGE}, + commitment_config::CommitmentConfig, + hash::Hash, + instruction::{AccountMeta, Instruction}, + message::Message, + pubkey::Pubkey, + signature::{Keypair, Signer}, + system_instruction, system_transaction, + timing::{duration_as_ms, duration_as_s, duration_as_us, timestamp}, + transaction::Transaction, + }, + std::{ + collections::{HashSet, VecDeque}, + net::SocketAddr, + process::exit, + sync::{ + atomic::{AtomicBool, AtomicIsize, AtomicUsize, Ordering}, + Arc, Mutex, RwLock, + }, + thread::{sleep, Builder, JoinHandle}, + time::{Duration, Instant}, }, - thread::{sleep, Builder, JoinHandle}, - time::{Duration, Instant}, }; // The point at which transactions become "too old", in seconds. @@ -946,12 +948,14 @@ pub fn generate_and_fund_keypairs( #[cfg(test)] mod tests { - use super::*; - use solana_runtime::bank::Bank; - use solana_runtime::bank_client::BankClient; - use solana_sdk::client::SyncClient; - use solana_sdk::fee_calculator::FeeRateGovernor; - use solana_sdk::genesis_config::create_genesis_config; + use { + super::*, + solana_runtime::{bank::Bank, bank_client::BankClient}, + solana_sdk::{ + client::SyncClient, fee_calculator::FeeRateGovernor, + genesis_config::create_genesis_config, + }, + }; #[test] fn test_bench_tps_bank_client() { diff --git a/bench-tps/src/cli.rs b/bench-tps/src/cli.rs index 875490d1e0ca01..c711406a749ae8 100644 --- a/bench-tps/src/cli.rs +++ b/bench-tps/src/cli.rs @@ -1,11 +1,13 @@ -use clap::{crate_description, crate_name, App, Arg, ArgMatches}; -use solana_faucet::faucet::FAUCET_PORT; -use solana_sdk::fee_calculator::FeeRateGovernor; -use solana_sdk::{ - pubkey::Pubkey, - signature::{read_keypair_file, Keypair}, +use { + clap::{crate_description, crate_name, App, Arg, ArgMatches}, + solana_faucet::faucet::FAUCET_PORT, + solana_sdk::{ + fee_calculator::FeeRateGovernor, + pubkey::Pubkey, + signature::{read_keypair_file, Keypair}, + }, + std::{net::SocketAddr, process::exit, time::Duration}, }; -use std::{net::SocketAddr, process::exit, time::Duration}; const NUM_LAMPORTS_PER_ACCOUNT_DEFAULT: u64 = solana_sdk::native_token::LAMPORTS_PER_SOL; diff --git a/bench-tps/src/main.rs b/bench-tps/src/main.rs index 03ae9f7463d976..d1a2e379d2832b 100644 --- a/bench-tps/src/main.rs +++ b/bench-tps/src/main.rs @@ -1,14 +1,20 @@ #![allow(clippy::integer_arithmetic)] -use log::*; -use solana_bench_tps::bench::{do_bench_tps, generate_and_fund_keypairs, generate_keypairs}; -use solana_bench_tps::cli; -use solana_genesis::Base64Account; -use solana_gossip::gossip_service::{discover_cluster, get_client, get_multi_client}; -use solana_sdk::fee_calculator::FeeRateGovernor; -use solana_sdk::signature::{Keypair, Signer}; -use solana_sdk::system_program; -use solana_streamer::socket::SocketAddrSpace; -use std::{collections::HashMap, fs::File, io::prelude::*, path::Path, process::exit, sync::Arc}; +use { + log::*, + solana_bench_tps::{ + bench::{do_bench_tps, generate_and_fund_keypairs, generate_keypairs}, + cli, + }, + solana_genesis::Base64Account, + solana_gossip::gossip_service::{discover_cluster, get_client, get_multi_client}, + solana_sdk::{ + fee_calculator::FeeRateGovernor, + signature::{Keypair, Signer}, + system_program, + }, + solana_streamer::socket::SocketAddrSpace, + std::{collections::HashMap, fs::File, io::prelude::*, path::Path, process::exit, sync::Arc}, +}; /// Number of signatures for all transactions in ~1 week at ~100K TPS pub const NUM_SIGNATURES_FOR_TXS: u64 = 100_000 * 60 * 60 * 24 * 7; diff --git a/bench-tps/tests/bench_tps.rs b/bench-tps/tests/bench_tps.rs index 26e6a1f895afe4..8b40aab0a84171 100644 --- a/bench-tps/tests/bench_tps.rs +++ b/bench-tps/tests/bench_tps.rs @@ -1,22 +1,24 @@ #![allow(clippy::integer_arithmetic)] -use serial_test::serial; -use solana_bench_tps::{ - bench::{do_bench_tps, generate_and_fund_keypairs}, - cli::Config, -}; -use solana_client::thin_client::create_client; -use solana_core::validator::ValidatorConfig; -use solana_faucet::faucet::run_local_faucet_with_port; -use solana_gossip::cluster_info::VALIDATOR_PORT_RANGE; -use solana_local_cluster::{ - local_cluster::{ClusterConfig, LocalCluster}, - validator_configs::make_identical_validator_configs, -}; -use solana_sdk::signature::{Keypair, Signer}; -use solana_streamer::socket::SocketAddrSpace; -use std::{ - sync::{mpsc::channel, Arc}, - time::Duration, +use { + serial_test::serial, + solana_bench_tps::{ + bench::{do_bench_tps, generate_and_fund_keypairs}, + cli::Config, + }, + solana_client::thin_client::create_client, + solana_core::validator::ValidatorConfig, + solana_faucet::faucet::run_local_faucet_with_port, + solana_gossip::cluster_info::VALIDATOR_PORT_RANGE, + solana_local_cluster::{ + local_cluster::{ClusterConfig, LocalCluster}, + validator_configs::make_identical_validator_configs, + }, + solana_sdk::signature::{Keypair, Signer}, + solana_streamer::socket::SocketAddrSpace, + std::{ + sync::{mpsc::channel, Arc}, + time::Duration, + }, }; fn test_bench_tps_local_cluster(config: Config) { diff --git a/bucket_map/benches/bucket_map.rs b/bucket_map/benches/bucket_map.rs index 8176064b1a2665..053b5a7d05abea 100644 --- a/bucket_map/benches/bucket_map.rs +++ b/bucket_map/benches/bucket_map.rs @@ -19,12 +19,13 @@ macro_rules! DEFINE_NxM_BENCH { } extern crate test; -use rayon::prelude::*; -use solana_bucket_map::bucket_map::{BucketMap, BucketMapConfig}; -use solana_sdk::pubkey::Pubkey; -use std::collections::hash_map::HashMap; -use std::sync::RwLock; -use test::Bencher; +use { + rayon::prelude::*, + solana_bucket_map::bucket_map::{BucketMap, BucketMapConfig}, + solana_sdk::pubkey::Pubkey, + std::{collections::hash_map::HashMap, sync::RwLock}, + test::Bencher, +}; type IndexValue = u64; diff --git a/bucket_map/src/bucket.rs b/bucket_map/src/bucket.rs index 78e3bd72f90331..c191a54a12b103 100644 --- a/bucket_map/src/bucket.rs +++ b/bucket_map/src/bucket.rs @@ -1,21 +1,27 @@ -use crate::bucket_item::BucketItem; -use crate::bucket_map::BucketMapError; -use crate::bucket_stats::BucketMapStats; -use crate::bucket_storage::{BucketStorage, Uid, DEFAULT_CAPACITY_POW2, UID_UNLOCKED}; -use crate::index_entry::IndexEntry; -use crate::{MaxSearch, RefCount}; -use rand::thread_rng; -use rand::Rng; -use solana_measure::measure::Measure; -use solana_sdk::pubkey::Pubkey; -use std::collections::hash_map::DefaultHasher; -use std::hash::{Hash, Hasher}; -use std::marker::PhantomData; -use std::ops::RangeBounds; -use std::path::PathBuf; -use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::Arc; -use std::sync::Mutex; +use { + crate::{ + bucket_item::BucketItem, + bucket_map::BucketMapError, + bucket_stats::BucketMapStats, + bucket_storage::{BucketStorage, Uid, DEFAULT_CAPACITY_POW2, UID_UNLOCKED}, + index_entry::IndexEntry, + MaxSearch, RefCount, + }, + rand::{thread_rng, Rng}, + solana_measure::measure::Measure, + solana_sdk::pubkey::Pubkey, + std::{ + collections::hash_map::DefaultHasher, + hash::{Hash, Hasher}, + marker::PhantomData, + ops::RangeBounds, + path::PathBuf, + sync::{ + atomic::{AtomicUsize, Ordering}, + Arc, Mutex, + }, + }, +}; #[derive(Default)] pub struct ReallocatedItems { diff --git a/bucket_map/src/bucket_api.rs b/bucket_map/src/bucket_api.rs index 704467f296b1ca..aa0a6e3435f3f9 100644 --- a/bucket_map/src/bucket_api.rs +++ b/bucket_map/src/bucket_api.rs @@ -1,15 +1,18 @@ -use crate::bucket::Bucket; -use crate::bucket_item::BucketItem; -use crate::bucket_map::BucketMapError; -use crate::bucket_stats::BucketMapStats; -use crate::{MaxSearch, RefCount}; -use solana_sdk::pubkey::Pubkey; -use std::ops::RangeBounds; -use std::path::PathBuf; - -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::Arc; -use std::sync::{RwLock, RwLockWriteGuard}; +use { + crate::{ + bucket::Bucket, bucket_item::BucketItem, bucket_map::BucketMapError, + bucket_stats::BucketMapStats, MaxSearch, RefCount, + }, + solana_sdk::pubkey::Pubkey, + std::{ + ops::RangeBounds, + path::PathBuf, + sync::{ + atomic::{AtomicU64, Ordering}, + Arc, RwLock, RwLockWriteGuard, + }, + }, +}; type LockedBucket = RwLock>>; diff --git a/bucket_map/src/bucket_item.rs b/bucket_map/src/bucket_item.rs index 532ff92bd476d1..8f11c432060f08 100644 --- a/bucket_map/src/bucket_item.rs +++ b/bucket_map/src/bucket_item.rs @@ -1,5 +1,4 @@ -use crate::RefCount; -use solana_sdk::pubkey::Pubkey; +use {crate::RefCount, solana_sdk::pubkey::Pubkey}; #[derive(Debug, Default, Clone)] pub struct BucketItem { diff --git a/bucket_map/src/bucket_map.rs b/bucket_map/src/bucket_map.rs index e29bd551511e9e..7cc0dbdf8f4bdb 100644 --- a/bucket_map/src/bucket_map.rs +++ b/bucket_map/src/bucket_map.rs @@ -1,15 +1,11 @@ //! BucketMap is a mostly contention free concurrent map backed by MmapMut -use crate::bucket_api::BucketApi; -use crate::bucket_stats::BucketMapStats; -use crate::{MaxSearch, RefCount}; -use solana_sdk::pubkey::Pubkey; -use std::convert::TryInto; -use std::fmt::Debug; -use std::fs; -use std::path::PathBuf; -use std::sync::Arc; -use tempfile::TempDir; +use { + crate::{bucket_api::BucketApi, bucket_stats::BucketMapStats, MaxSearch, RefCount}, + solana_sdk::pubkey::Pubkey, + std::{convert::TryInto, fmt::Debug, fs, path::PathBuf, sync::Arc}, + tempfile::TempDir, +}; #[derive(Debug, Default, Clone)] pub struct BucketMapConfig { @@ -194,11 +190,11 @@ fn read_be_u64(input: &[u8]) -> u64 { #[cfg(test)] mod tests { - use super::*; - use rand::thread_rng; - use rand::Rng; - use std::collections::HashMap; - use std::sync::RwLock; + use { + super::*, + rand::{thread_rng, Rng}, + std::{collections::HashMap, sync::RwLock}, + }; #[test] fn bucket_map_test_insert() { diff --git a/bucket_map/src/bucket_stats.rs b/bucket_map/src/bucket_stats.rs index b6090de936bdaf..d71c7f7e164b77 100644 --- a/bucket_map/src/bucket_stats.rs +++ b/bucket_map/src/bucket_stats.rs @@ -1,5 +1,4 @@ -use std::sync::Arc; -use std::sync::{atomic::AtomicU64, Mutex}; +use std::sync::{atomic::AtomicU64, Arc, Mutex}; #[derive(Debug, Default)] pub struct BucketStats { diff --git a/bucket_map/src/bucket_storage.rs b/bucket_map/src/bucket_storage.rs index 38d0f3d974ac9e..d3415fa04fe14c 100644 --- a/bucket_map/src/bucket_storage.rs +++ b/bucket_map/src/bucket_storage.rs @@ -1,15 +1,18 @@ -use crate::bucket_stats::BucketStats; -use crate::MaxSearch; -use memmap2::MmapMut; -use rand::{thread_rng, Rng}; -use solana_measure::measure::Measure; -use std::fs::{remove_file, OpenOptions}; -use std::io::Seek; -use std::io::SeekFrom; -use std::io::Write; -use std::path::PathBuf; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::Arc; +use { + crate::{bucket_stats::BucketStats, MaxSearch}, + memmap2::MmapMut, + rand::{thread_rng, Rng}, + solana_measure::measure::Measure, + std::{ + fs::{remove_file, OpenOptions}, + io::{Seek, SeekFrom, Write}, + path::PathBuf, + sync::{ + atomic::{AtomicU64, Ordering}, + Arc, + }, + }, +}; /* 1 2 diff --git a/bucket_map/src/index_entry.rs b/bucket_map/src/index_entry.rs index 492eff100fb150..9fc540627a967d 100644 --- a/bucket_map/src/index_entry.rs +++ b/bucket_map/src/index_entry.rs @@ -1,11 +1,16 @@ -use crate::bucket::Bucket; -use crate::bucket_storage::{BucketStorage, Uid}; -use crate::RefCount; -use solana_sdk::clock::Slot; -use solana_sdk::pubkey::Pubkey; -use std::collections::hash_map::DefaultHasher; -use std::fmt::Debug; -use std::hash::{Hash, Hasher}; +use { + crate::{ + bucket::Bucket, + bucket_storage::{BucketStorage, Uid}, + RefCount, + }, + solana_sdk::{clock::Slot, pubkey::Pubkey}, + std::{ + collections::hash_map::DefaultHasher, + fmt::Debug, + hash::{Hash, Hasher}, + }, +}; #[repr(C)] #[derive(Debug, Copy, Clone, PartialEq)] diff --git a/bucket_map/tests/bucket_map.rs b/bucket_map/tests/bucket_map.rs index e7f29d551adc5c..31adcdb04c57b4 100644 --- a/bucket_map/tests/bucket_map.rs +++ b/bucket_map/tests/bucket_map.rs @@ -1,8 +1,10 @@ -use rayon::prelude::*; -use solana_bucket_map::bucket_map::{BucketMap, BucketMapConfig}; -use solana_measure::measure::Measure; -use solana_sdk::pubkey::Pubkey; -use std::path::PathBuf; +use { + rayon::prelude::*, + solana_bucket_map::bucket_map::{BucketMap, BucketMapConfig}, + solana_measure::measure::Measure, + solana_sdk::pubkey::Pubkey, + std::path::PathBuf, +}; #[test] #[ignore] fn bucket_map_test_mt() { diff --git a/clap-utils/src/input_parsers.rs b/clap-utils/src/input_parsers.rs index d2b77d69bf55a4..1965d6f7bc4ee5 100644 --- a/clap-utils/src/input_parsers.rs +++ b/clap-utils/src/input_parsers.rs @@ -196,10 +196,12 @@ pub fn commitment_of(matches: &ArgMatches<'_>, name: &str) -> Option() -> App<'ab, 'v> { App::new("test") diff --git a/clap-utils/src/input_validators.rs b/clap-utils/src/input_validators.rs index bbf904fe8663de..e96de1784e021a 100644 --- a/clap-utils/src/input_validators.rs +++ b/clap-utils/src/input_validators.rs @@ -7,8 +7,7 @@ use { pubkey::{Pubkey, MAX_SEED_LEN}, signature::{read_keypair_file, Signature}, }, - std::fmt::Display, - std::str::FromStr, + std::{fmt::Display, str::FromStr}, }; fn is_parsable_generic(string: T) -> Result<(), String> diff --git a/clap-utils/src/keypair.rs b/clap-utils/src/keypair.rs index c217cd046e43d4..927e455a83fe00 100644 --- a/clap-utils/src/keypair.rs +++ b/clap-utils/src/keypair.rs @@ -1123,14 +1123,14 @@ fn sanitize_seed_phrase(seed_phrase: &str) -> String { #[cfg(test)] mod tests { - use super::*; - use crate::offline::OfflineArgs; - use clap::{value_t_or_exit, App, Arg}; - use solana_remote_wallet::locator::Manufacturer; - use solana_remote_wallet::remote_wallet::initialize_wallet_manager; - use solana_sdk::signer::keypair::write_keypair_file; - use solana_sdk::system_instruction; - use tempfile::{NamedTempFile, TempDir}; + use { + super::*, + crate::offline::OfflineArgs, + clap::{value_t_or_exit, App, Arg}, + solana_remote_wallet::{locator::Manufacturer, remote_wallet::initialize_wallet_manager}, + solana_sdk::{signer::keypair::write_keypair_file, system_instruction}, + tempfile::{NamedTempFile, TempDir}, + }; #[test] fn test_sanitize_seed_phrase() { diff --git a/cli-config/src/config.rs b/cli-config/src/config.rs index 0f37e3455fd8f5..6bcc16eedb4a7e 100644 --- a/cli-config/src/config.rs +++ b/cli-config/src/config.rs @@ -1,7 +1,9 @@ // Wallet settings that can be configured for long-term use -use serde_derive::{Deserialize, Serialize}; -use std::{collections::HashMap, io, path::Path}; -use url::Url; +use { + serde_derive::{Deserialize, Serialize}, + std::{collections::HashMap, io, path::Path}, + url::Url, +}; lazy_static! { /// The default path to the CLI configuration file. diff --git a/cli-config/src/lib.rs b/cli-config/src/lib.rs index ea0f464049dc64..687a0a526f5514 100644 --- a/cli-config/src/lib.rs +++ b/cli-config/src/lib.rs @@ -56,7 +56,6 @@ extern crate lazy_static; mod config; pub use config::{Config, CONFIG_FILE}; - use std::{ fs::{create_dir_all, File}, io::{self, Write}, diff --git a/cli-output/src/cli_output.rs b/cli-output/src/cli_output.rs index f32b08b6f32505..16f7741756b242 100644 --- a/cli-output/src/cli_output.rs +++ b/cli-output/src/cli_output.rs @@ -2525,14 +2525,16 @@ impl VerboseDisplay for CliGossipNodes {} #[cfg(test)] mod tests { - use super::*; - use clap::{App, Arg}; - use solana_sdk::{ - message::Message, - pubkey::Pubkey, - signature::{keypair_from_seed, NullSigner, Signature, Signer, SignerError}, - system_instruction, - transaction::Transaction, + use { + super::*, + clap::{App, Arg}, + solana_sdk::{ + message::Message, + pubkey::Pubkey, + signature::{keypair_from_seed, NullSigner, Signature, Signer, SignerError}, + system_instruction, + transaction::Transaction, + }, }; #[test] diff --git a/cli-output/src/display.rs b/cli-output/src/display.rs index 4ae569a6ff6cce..88c99f50fab990 100644 --- a/cli-output/src/display.rs +++ b/cli-output/src/display.rs @@ -8,8 +8,7 @@ use { program_utils::limited_deserialize, pubkey::Pubkey, stake, transaction::Transaction, }, solana_transaction_status::UiTransactionStatusMeta, - spl_memo::id as spl_memo_id, - spl_memo::v1::id as spl_memo_v1_id, + spl_memo::{id as spl_memo_id, v1::id as spl_memo_v1_id}, std::{collections::HashMap, fmt, io}, }; @@ -428,8 +427,7 @@ pub fn unix_timestamp_to_string(unix_timestamp: UnixTimestamp) -> String { #[cfg(test)] mod test { - use super::*; - use solana_sdk::pubkey::Pubkey; + use {super::*, solana_sdk::pubkey::Pubkey}; #[test] fn test_format_labeled_address() { diff --git a/cli/src/checks.rs b/cli/src/checks.rs index dabee68df2c9ce..e60bed798551da 100644 --- a/cli/src/checks.rs +++ b/cli/src/checks.rs @@ -1,11 +1,13 @@ -use crate::cli::CliError; -use solana_client::{ - client_error::{ClientError, Result as ClientResult}, - rpc_client::RpcClient, -}; -use solana_sdk::{ - commitment_config::CommitmentConfig, message::Message, native_token::lamports_to_sol, - pubkey::Pubkey, +use { + crate::cli::CliError, + solana_client::{ + client_error::{ClientError, Result as ClientResult}, + rpc_client::RpcClient, + }, + solana_sdk::{ + commitment_config::CommitmentConfig, message::Message, native_token::lamports_to_sol, + pubkey::Pubkey, + }, }; pub fn check_account_for_fee( @@ -149,14 +151,16 @@ pub fn check_unique_pubkeys( #[cfg(test)] mod tests { - use super::*; - use serde_json::json; - use solana_client::{ - rpc_request::RpcRequest, - rpc_response::{Response, RpcResponseContext}, + use { + super::*, + serde_json::json, + solana_client::{ + rpc_request::RpcRequest, + rpc_response::{Response, RpcResponseContext}, + }, + solana_sdk::system_instruction, + std::collections::HashMap, }; - use solana_sdk::system_instruction; - use std::collections::HashMap; #[test] fn test_check_account_for_fees() { diff --git a/cli/src/clap_app.rs b/cli/src/clap_app.rs index cf15285c3d9c9b..3d48ed37160f93 100644 --- a/cli/src/clap_app.rs +++ b/cli/src/clap_app.rs @@ -1,10 +1,12 @@ -use crate::{ - cli::*, cluster_query::*, feature::*, inflation::*, nonce::*, program::*, stake::*, - validator_info::*, vote::*, wallet::*, +use { + crate::{ + cli::*, cluster_query::*, feature::*, inflation::*, nonce::*, program::*, stake::*, + validator_info::*, vote::*, wallet::*, + }, + clap::{App, AppSettings, Arg, ArgGroup, SubCommand}, + solana_clap_utils::{self, input_validators::*, keypair::*}, + solana_cli_config::CONFIG_FILE, }; -use clap::{App, AppSettings, Arg, ArgGroup, SubCommand}; -use solana_clap_utils::{self, input_validators::*, keypair::*}; -use solana_cli_config::CONFIG_FILE; pub fn get_clap_app<'ab, 'v>(name: &str, about: &'ab str, version: &'v str) -> App<'ab, 'v> { App::new(name) diff --git a/cli/src/cli.rs b/cli/src/cli.rs index fe4c362621af86..85f81bc999efe1 100644 --- a/cli/src/cli.rs +++ b/cli/src/cli.rs @@ -1,37 +1,41 @@ -use crate::{ - clap_app::*, cluster_query::*, feature::*, inflation::*, nonce::*, program::*, spend_utils::*, - stake::*, validator_info::*, vote::*, wallet::*, -}; -use clap::{crate_description, crate_name, value_t_or_exit, ArgMatches, Shell}; -use log::*; -use num_traits::FromPrimitive; -use serde_json::{self, Value}; -use solana_clap_utils::{self, input_parsers::*, input_validators::*, keypair::*}; -use solana_cli_output::{ - display::println_name_value, CliSignature, CliValidatorsSortOrder, OutputFormat, -}; -use solana_client::{ - blockhash_query::BlockhashQuery, - client_error::{ClientError, Result as ClientResult}, - nonce_utils, - rpc_client::RpcClient, - rpc_config::{RpcLargestAccountsFilter, RpcSendTransactionConfig, RpcTransactionLogsFilter}, -}; -use solana_remote_wallet::remote_wallet::RemoteWalletManager; -use solana_sdk::{ - clock::{Epoch, Slot}, - commitment_config::CommitmentConfig, - decode_error::DecodeError, - hash::Hash, - instruction::InstructionError, - pubkey::Pubkey, - signature::{Signature, Signer, SignerError}, - stake::{instruction::LockupArgs, state::Lockup}, - transaction::{Transaction, TransactionError}, +use { + crate::{ + clap_app::*, cluster_query::*, feature::*, inflation::*, nonce::*, program::*, + spend_utils::*, stake::*, validator_info::*, vote::*, wallet::*, + }, + clap::{crate_description, crate_name, value_t_or_exit, ArgMatches, Shell}, + log::*, + num_traits::FromPrimitive, + serde_json::{self, Value}, + solana_clap_utils::{self, input_parsers::*, input_validators::*, keypair::*}, + solana_cli_output::{ + display::println_name_value, CliSignature, CliValidatorsSortOrder, OutputFormat, + }, + solana_client::{ + blockhash_query::BlockhashQuery, + client_error::{ClientError, Result as ClientResult}, + nonce_utils, + rpc_client::RpcClient, + rpc_config::{ + RpcLargestAccountsFilter, RpcSendTransactionConfig, RpcTransactionLogsFilter, + }, + }, + solana_remote_wallet::remote_wallet::RemoteWalletManager, + solana_sdk::{ + clock::{Epoch, Slot}, + commitment_config::CommitmentConfig, + decode_error::DecodeError, + hash::Hash, + instruction::InstructionError, + pubkey::Pubkey, + signature::{Signature, Signer, SignerError}, + stake::{instruction::LockupArgs, state::Lockup}, + transaction::{Transaction, TransactionError}, + }, + solana_vote_program::vote_state::VoteAuthorize, + std::{collections::HashMap, error, io::stdout, str::FromStr, sync::Arc, time::Duration}, + thiserror::Error, }; -use solana_vote_program::vote_state::VoteAuthorize; -use std::{collections::HashMap, error, io::stdout, str::FromStr, sync::Arc, time::Duration}; -use thiserror::Error; pub const DEFAULT_RPC_TIMEOUT_SECONDS: &str = "30"; pub const DEFAULT_CONFIRM_TX_TIMEOUT_SECONDS: &str = "5"; @@ -1607,22 +1611,26 @@ where #[cfg(test)] mod tests { - use super::*; - use serde_json::{json, Value}; - use solana_client::{ - blockhash_query, - mock_sender::SIGNATURE, - rpc_request::RpcRequest, - rpc_response::{Response, RpcResponseContext}, - }; - use solana_sdk::{ - pubkey::Pubkey, - signature::{keypair_from_seed, read_keypair_file, write_keypair_file, Keypair, Presigner}, - stake, system_program, - transaction::TransactionError, + use { + super::*, + serde_json::{json, Value}, + solana_client::{ + blockhash_query, + mock_sender::SIGNATURE, + rpc_request::RpcRequest, + rpc_response::{Response, RpcResponseContext}, + }, + solana_sdk::{ + pubkey::Pubkey, + signature::{ + keypair_from_seed, read_keypair_file, write_keypair_file, Keypair, Presigner, + }, + stake, system_program, + transaction::TransactionError, + }, + solana_transaction_status::TransactionConfirmationStatus, + std::path::PathBuf, }; - use solana_transaction_status::TransactionConfirmationStatus; - use std::path::PathBuf; fn make_tmp_path(name: &str) -> String { let out_dir = std::env::var("FARF_DIR").unwrap_or_else(|_| "farf".to_string()); diff --git a/cli/src/cluster_query.rs b/cli/src/cluster_query.rs index 2886ec26cda370..66bc8e24a877af 100644 --- a/cli/src/cluster_query.rs +++ b/cli/src/cluster_query.rs @@ -1,76 +1,78 @@ -use crate::{ - cli::{CliCommand, CliCommandInfo, CliConfig, CliError, ProcessResult}, - spend_utils::{resolve_spend_tx_and_check_account_balance, SpendAmount}, -}; -use clap::{value_t, value_t_or_exit, App, AppSettings, Arg, ArgMatches, SubCommand}; -use console::{style, Emoji}; -use serde::{Deserialize, Serialize}; -use solana_clap_utils::{ - input_parsers::*, - input_validators::*, - keypair::DefaultSigner, - offline::{blockhash_arg, BLOCKHASH_ARG}, -}; -use solana_cli_output::{ - display::{ - build_balance_message, format_labeled_address, new_spinner_progress_bar, - println_name_value, println_transaction, unix_timestamp_to_string, writeln_name_value, +use { + crate::{ + cli::{CliCommand, CliCommandInfo, CliConfig, CliError, ProcessResult}, + spend_utils::{resolve_spend_tx_and_check_account_balance, SpendAmount}, }, - *, -}; -use solana_client::{ - client_error::ClientErrorKind, - pubsub_client::PubsubClient, - rpc_client::{GetConfirmedSignaturesForAddress2Config, RpcClient}, - rpc_config::{ - RpcAccountInfoConfig, RpcBlockConfig, RpcGetVoteAccountsConfig, RpcLargestAccountsConfig, - RpcLargestAccountsFilter, RpcProgramAccountsConfig, RpcTransactionConfig, - RpcTransactionLogsConfig, RpcTransactionLogsFilter, + clap::{value_t, value_t_or_exit, App, AppSettings, Arg, ArgMatches, SubCommand}, + console::{style, Emoji}, + serde::{Deserialize, Serialize}, + solana_clap_utils::{ + input_parsers::*, + input_validators::*, + keypair::DefaultSigner, + offline::{blockhash_arg, BLOCKHASH_ARG}, }, - rpc_filter, - rpc_request::DELINQUENT_VALIDATOR_SLOT_DISTANCE, - rpc_response::SlotInfo, -}; -use solana_remote_wallet::remote_wallet::RemoteWalletManager; -use solana_sdk::{ - account::from_account, - account_utils::StateMut, - clock::{self, Clock, Slot}, - commitment_config::CommitmentConfig, - epoch_schedule::Epoch, - hash::Hash, - message::Message, - native_token::lamports_to_sol, - nonce::State as NonceState, - pubkey::{self, Pubkey}, - rent::Rent, - rpc_port::DEFAULT_RPC_PORT_STR, - signature::Signature, - slot_history, - stake::{self, state::StakeState}, - system_instruction, system_program, - sysvar::{ - self, - slot_history::SlotHistory, - stake_history::{self}, + solana_cli_output::{ + display::{ + build_balance_message, format_labeled_address, new_spinner_progress_bar, + println_name_value, println_transaction, unix_timestamp_to_string, writeln_name_value, + }, + *, }, - timing, - transaction::Transaction, -}; -use solana_transaction_status::UiTransactionEncoding; -use solana_vote_program::vote_state::VoteState; -use std::{ - collections::{BTreeMap, HashMap, VecDeque}, - fmt, - str::FromStr, - sync::{ - atomic::{AtomicBool, Ordering}, - Arc, + solana_client::{ + client_error::ClientErrorKind, + pubsub_client::PubsubClient, + rpc_client::{GetConfirmedSignaturesForAddress2Config, RpcClient}, + rpc_config::{ + RpcAccountInfoConfig, RpcBlockConfig, RpcGetVoteAccountsConfig, + RpcLargestAccountsConfig, RpcLargestAccountsFilter, RpcProgramAccountsConfig, + RpcTransactionConfig, RpcTransactionLogsConfig, RpcTransactionLogsFilter, + }, + rpc_filter, + rpc_request::DELINQUENT_VALIDATOR_SLOT_DISTANCE, + rpc_response::SlotInfo, + }, + solana_remote_wallet::remote_wallet::RemoteWalletManager, + solana_sdk::{ + account::from_account, + account_utils::StateMut, + clock::{self, Clock, Slot}, + commitment_config::CommitmentConfig, + epoch_schedule::Epoch, + hash::Hash, + message::Message, + native_token::lamports_to_sol, + nonce::State as NonceState, + pubkey::{self, Pubkey}, + rent::Rent, + rpc_port::DEFAULT_RPC_PORT_STR, + signature::Signature, + slot_history, + stake::{self, state::StakeState}, + system_instruction, system_program, + sysvar::{ + self, + slot_history::SlotHistory, + stake_history::{self}, + }, + timing, + transaction::Transaction, }, - thread::sleep, - time::{Duration, Instant, SystemTime, UNIX_EPOCH}, + solana_transaction_status::UiTransactionEncoding, + solana_vote_program::vote_state::VoteState, + std::{ + collections::{BTreeMap, HashMap, VecDeque}, + fmt, + str::FromStr, + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, + }, + thread::sleep, + time::{Duration, Instant, SystemTime, UNIX_EPOCH}, + }, + thiserror::Error, }; -use thiserror::Error; static CHECK_MARK: Emoji = Emoji("✅ ", ""); static CROSS_MARK: Emoji = Emoji("❌ ", ""); @@ -2139,11 +2141,13 @@ pub fn process_calculate_rent( #[cfg(test)] mod tests { - use super::*; - use crate::{clap_app::get_clap_app, cli::parse_command}; - use solana_sdk::signature::{write_keypair, Keypair}; - use std::str::FromStr; - use tempfile::NamedTempFile; + use { + super::*, + crate::{clap_app::get_clap_app, cli::parse_command}, + solana_sdk::signature::{write_keypair, Keypair}, + std::str::FromStr, + tempfile::NamedTempFile, + }; fn make_tmp_file() -> (String, NamedTempFile) { let tmp_file = NamedTempFile::new().unwrap(); diff --git a/cli/src/feature.rs b/cli/src/feature.rs index 7ded7eb1b55db5..d2dd5b6f4458db 100644 --- a/cli/src/feature.rs +++ b/cli/src/feature.rs @@ -1,28 +1,30 @@ -use crate::{ - cli::{CliCommand, CliCommandInfo, CliConfig, CliError, ProcessResult}, - spend_utils::{resolve_spend_tx_and_check_account_balance, SpendAmount}, -}; -use clap::{App, AppSettings, Arg, ArgMatches, SubCommand}; -use console::style; -use serde::{Deserialize, Serialize}; -use solana_clap_utils::{input_parsers::*, input_validators::*, keypair::*}; -use solana_cli_output::{QuietDisplay, VerboseDisplay}; -use solana_client::{client_error::ClientError, rpc_client::RpcClient}; -use solana_remote_wallet::remote_wallet::RemoteWalletManager; -use solana_sdk::{ - account::Account, - clock::Slot, - feature::{self, Feature}, - feature_set::FEATURE_NAMES, - message::Message, - pubkey::Pubkey, - transaction::Transaction, -}; -use std::{ - cmp::Ordering, - collections::{HashMap, HashSet}, - fmt, - sync::Arc, +use { + crate::{ + cli::{CliCommand, CliCommandInfo, CliConfig, CliError, ProcessResult}, + spend_utils::{resolve_spend_tx_and_check_account_balance, SpendAmount}, + }, + clap::{App, AppSettings, Arg, ArgMatches, SubCommand}, + console::style, + serde::{Deserialize, Serialize}, + solana_clap_utils::{input_parsers::*, input_validators::*, keypair::*}, + solana_cli_output::{QuietDisplay, VerboseDisplay}, + solana_client::{client_error::ClientError, rpc_client::RpcClient}, + solana_remote_wallet::remote_wallet::RemoteWalletManager, + solana_sdk::{ + account::Account, + clock::Slot, + feature::{self, Feature}, + feature_set::FEATURE_NAMES, + message::Message, + pubkey::Pubkey, + transaction::Transaction, + }, + std::{ + cmp::Ordering, + collections::{HashMap, HashSet}, + fmt, + sync::Arc, + }, }; #[derive(Copy, Clone, Debug, PartialEq)] diff --git a/cli/src/inflation.rs b/cli/src/inflation.rs index 8ec8233db04291..6466899f55b990 100644 --- a/cli/src/inflation.rs +++ b/cli/src/inflation.rs @@ -1,17 +1,19 @@ -use crate::cli::{CliCommand, CliCommandInfo, CliConfig, CliError, ProcessResult}; -use clap::{App, Arg, ArgMatches, SubCommand}; -use solana_clap_utils::{ - input_parsers::{pubkeys_of, value_of}, - input_validators::is_valid_pubkey, - keypair::*, +use { + crate::cli::{CliCommand, CliCommandInfo, CliConfig, CliError, ProcessResult}, + clap::{App, Arg, ArgMatches, SubCommand}, + solana_clap_utils::{ + input_parsers::{pubkeys_of, value_of}, + input_validators::is_valid_pubkey, + keypair::*, + }, + solana_cli_output::{ + CliEpochRewardshMetadata, CliInflation, CliKeyedEpochReward, CliKeyedEpochRewards, + }, + solana_client::rpc_client::RpcClient, + solana_remote_wallet::remote_wallet::RemoteWalletManager, + solana_sdk::{clock::Epoch, pubkey::Pubkey}, + std::sync::Arc, }; -use solana_cli_output::{ - CliEpochRewardshMetadata, CliInflation, CliKeyedEpochReward, CliKeyedEpochRewards, -}; -use solana_client::rpc_client::RpcClient; -use solana_remote_wallet::remote_wallet::RemoteWalletManager; -use solana_sdk::{clock::Epoch, pubkey::Pubkey}; -use std::sync::Arc; #[derive(Debug, PartialEq)] pub enum InflationCliCommand { diff --git a/cli/src/main.rs b/cli/src/main.rs index b58980776953c7..e98c1761274e04 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -1,19 +1,21 @@ -use clap::{crate_description, crate_name, value_t_or_exit, ArgMatches}; -use console::style; -use solana_clap_utils::{ - input_validators::normalize_to_url_if_moniker, - keypair::{CliSigners, DefaultSigner}, - DisplayError, +use { + clap::{crate_description, crate_name, value_t_or_exit, ArgMatches}, + console::style, + solana_clap_utils::{ + input_validators::normalize_to_url_if_moniker, + keypair::{CliSigners, DefaultSigner}, + DisplayError, + }, + solana_cli::{ + clap_app::get_clap_app, + cli::{parse_command, process_command, CliCommandInfo, CliConfig, SettingType}, + }, + solana_cli_config::Config, + solana_cli_output::{display::println_name_value, OutputFormat}, + solana_client::rpc_config::RpcSendTransactionConfig, + solana_remote_wallet::remote_wallet::RemoteWalletManager, + std::{collections::HashMap, error, path::PathBuf, sync::Arc, time::Duration}, }; -use solana_cli::{ - clap_app::get_clap_app, - cli::{parse_command, process_command, CliCommandInfo, CliConfig, SettingType}, -}; -use solana_cli_config::Config; -use solana_cli_output::{display::println_name_value, OutputFormat}; -use solana_client::rpc_config::RpcSendTransactionConfig; -use solana_remote_wallet::remote_wallet::RemoteWalletManager; -use std::{collections::HashMap, error, path::PathBuf, sync::Arc, time::Duration}; pub fn println_name_value_or(name: &str, value: &str, setting_type: SettingType) { let description = match setting_type { diff --git a/cli/src/memo.rs b/cli/src/memo.rs index ccb02c3d9baf47..1043415357b338 100644 --- a/cli/src/memo.rs +++ b/cli/src/memo.rs @@ -1,6 +1,7 @@ -use solana_sdk::instruction::Instruction; -use solana_sdk::pubkey::Pubkey; -use spl_memo::id; +use { + solana_sdk::{instruction::Instruction, pubkey::Pubkey}, + spl_memo::id, +}; pub trait WithMemo { fn with_memo>(self, memo: Option) -> Self; diff --git a/cli/src/nonce.rs b/cli/src/nonce.rs index 8fa8940612c892..564e97084738ff 100644 --- a/cli/src/nonce.rs +++ b/cli/src/nonce.rs @@ -1,41 +1,43 @@ -use crate::{ - checks::{check_account_for_fee_with_commitment, check_unique_pubkeys}, - cli::{ - log_instruction_custom_error, log_instruction_custom_error_ex, CliCommand, CliCommandInfo, - CliConfig, CliError, ProcessResult, +use { + crate::{ + checks::{check_account_for_fee_with_commitment, check_unique_pubkeys}, + cli::{ + log_instruction_custom_error, log_instruction_custom_error_ex, CliCommand, + CliCommandInfo, CliConfig, CliError, ProcessResult, + }, + feature::get_feature_is_active, + memo::WithMemo, + spend_utils::{resolve_spend_tx_and_check_account_balance, SpendAmount}, }, - feature::get_feature_is_active, - memo::WithMemo, - spend_utils::{resolve_spend_tx_and_check_account_balance, SpendAmount}, -}; -use clap::{App, Arg, ArgMatches, SubCommand}; -use solana_clap_utils::{ - input_parsers::*, - input_validators::*, - keypair::{DefaultSigner, SignerIndex}, - memo::{memo_arg, MEMO_ARG}, - nonce::*, -}; -use solana_cli_output::CliNonceAccount; -use solana_client::{nonce_utils::*, rpc_client::RpcClient}; -use solana_remote_wallet::remote_wallet::RemoteWalletManager; -use solana_sdk::{ - account::Account, - feature_set::merge_nonce_error_into_system_error, - hash::Hash, - instruction::InstructionError, - message::Message, - nonce::{self, State}, - pubkey::Pubkey, - system_instruction::{ - advance_nonce_account, authorize_nonce_account, create_nonce_account, - create_nonce_account_with_seed, instruction_to_nonce_error, withdraw_nonce_account, - NonceError, SystemError, + clap::{App, Arg, ArgMatches, SubCommand}, + solana_clap_utils::{ + input_parsers::*, + input_validators::*, + keypair::{DefaultSigner, SignerIndex}, + memo::{memo_arg, MEMO_ARG}, + nonce::*, + }, + solana_cli_output::CliNonceAccount, + solana_client::{nonce_utils::*, rpc_client::RpcClient}, + solana_remote_wallet::remote_wallet::RemoteWalletManager, + solana_sdk::{ + account::Account, + feature_set::merge_nonce_error_into_system_error, + hash::Hash, + instruction::InstructionError, + message::Message, + nonce::{self, State}, + pubkey::Pubkey, + system_instruction::{ + advance_nonce_account, authorize_nonce_account, create_nonce_account, + create_nonce_account_with_seed, instruction_to_nonce_error, withdraw_nonce_account, + NonceError, SystemError, + }, + system_program, + transaction::{Transaction, TransactionError}, }, - system_program, - transaction::{Transaction, TransactionError}, + std::sync::Arc, }; -use std::sync::Arc; pub trait NonceSubCommands { fn nonce_subcommands(self) -> Self; @@ -648,18 +650,20 @@ pub fn process_withdraw_from_nonce_account( #[cfg(test)] mod tests { - use super::*; - use crate::{clap_app::get_clap_app, cli::parse_command}; - use solana_sdk::{ - account::Account, - account_utils::StateMut, - hash::hash, - nonce::{self, state::Versions, State}, - nonce_account, - signature::{read_keypair_file, write_keypair, Keypair, Signer}, - system_program, + use { + super::*, + crate::{clap_app::get_clap_app, cli::parse_command}, + solana_sdk::{ + account::Account, + account_utils::StateMut, + hash::hash, + nonce::{self, state::Versions, State}, + nonce_account, + signature::{read_keypair_file, write_keypair, Keypair, Signer}, + system_program, + }, + tempfile::NamedTempFile, }; - use tempfile::NamedTempFile; fn make_tmp_file() -> (String, NamedTempFile) { let tmp_file = NamedTempFile::new().unwrap(); diff --git a/cli/src/program.rs b/cli/src/program.rs index 6c65216746fbee..6fce75754f2a21 100644 --- a/cli/src/program.rs +++ b/cli/src/program.rs @@ -1,57 +1,56 @@ -use crate::{ - checks::*, - cli::{ - log_instruction_custom_error, CliCommand, CliCommandInfo, CliConfig, CliError, - ProcessResult, +use { + crate::{ + checks::*, + cli::{ + log_instruction_custom_error, CliCommand, CliCommandInfo, CliConfig, CliError, + ProcessResult, + }, + }, + bip39::{Language, Mnemonic, MnemonicType, Seed}, + clap::{App, AppSettings, Arg, ArgMatches, SubCommand}, + log::*, + solana_account_decoder::{UiAccountEncoding, UiDataSliceConfig}, + solana_bpf_loader_program::{syscalls::register_syscalls, BpfError, ThisInstructionMeter}, + solana_clap_utils::{self, input_parsers::*, input_validators::*, keypair::*}, + solana_cli_output::{ + CliProgram, CliProgramAccountType, CliProgramAuthority, CliProgramBuffer, CliProgramId, + CliUpgradeableBuffer, CliUpgradeableBuffers, CliUpgradeableProgram, + CliUpgradeableProgramClosed, CliUpgradeablePrograms, + }, + solana_client::{ + client_error::ClientErrorKind, + rpc_client::RpcClient, + rpc_config::{RpcAccountInfoConfig, RpcProgramAccountsConfig, RpcSendTransactionConfig}, + rpc_filter::{Memcmp, MemcmpEncodedBytes, RpcFilterType}, + tpu_client::{TpuClient, TpuClientConfig}, + }, + solana_program_runtime::invoke_context::InvokeContext, + solana_rbpf::{elf::Executable, verifier, vm::Config}, + solana_remote_wallet::remote_wallet::RemoteWalletManager, + solana_sdk::{ + account::Account, + account_utils::StateMut, + bpf_loader, bpf_loader_deprecated, + bpf_loader_upgradeable::{self, UpgradeableLoaderState}, + instruction::{Instruction, InstructionError}, + loader_instruction, + message::Message, + native_token::Sol, + packet::PACKET_DATA_SIZE, + pubkey::Pubkey, + signature::{keypair_from_seed, read_keypair_file, Keypair, Signature, Signer}, + system_instruction::{self, SystemError}, + system_program, + transaction::{Transaction, TransactionError}, + }, + std::{ + fs::File, + io::{Read, Write}, + mem::size_of, + path::PathBuf, + str::FromStr, + sync::Arc, }, -}; -use bip39::{Language, Mnemonic, MnemonicType, Seed}; -use clap::{App, AppSettings, Arg, ArgMatches, SubCommand}; -use log::*; -use solana_account_decoder::{UiAccountEncoding, UiDataSliceConfig}; -use solana_bpf_loader_program::{syscalls::register_syscalls, BpfError, ThisInstructionMeter}; -use solana_clap_utils::{self, input_parsers::*, input_validators::*, keypair::*}; -use solana_cli_output::{ - CliProgram, CliProgramAccountType, CliProgramAuthority, CliProgramBuffer, CliProgramId, - CliUpgradeableBuffer, CliUpgradeableBuffers, CliUpgradeableProgram, - CliUpgradeableProgramClosed, CliUpgradeablePrograms, -}; -use solana_client::{ - client_error::ClientErrorKind, - rpc_client::RpcClient, - rpc_config::RpcSendTransactionConfig, - rpc_config::{RpcAccountInfoConfig, RpcProgramAccountsConfig}, - rpc_filter::{Memcmp, MemcmpEncodedBytes, RpcFilterType}, - tpu_client::{TpuClient, TpuClientConfig}, -}; -use solana_program_runtime::invoke_context::InvokeContext; -use solana_rbpf::{elf::Executable, verifier, vm::Config}; -use solana_remote_wallet::remote_wallet::RemoteWalletManager; -use solana_sdk::{ - account::Account, - account_utils::StateMut, - bpf_loader, bpf_loader_deprecated, - bpf_loader_upgradeable::{self, UpgradeableLoaderState}, - instruction::Instruction, - instruction::InstructionError, - loader_instruction, - message::Message, - native_token::Sol, - packet::PACKET_DATA_SIZE, - pubkey::Pubkey, - signature::{keypair_from_seed, read_keypair_file, Keypair, Signature, Signer}, - system_instruction::{self, SystemError}, - system_program, - transaction::Transaction, - transaction::TransactionError, -}; -use std::{ - fs::File, - io::{Read, Write}, - mem::size_of, - path::PathBuf, - str::FromStr, - sync::Arc, }; #[derive(Debug, PartialEq)] @@ -2203,14 +2202,16 @@ fn report_ephemeral_mnemonic(words: usize, mnemonic: bip39::Mnemonic) { #[cfg(test)] mod tests { - use super::*; - use crate::{ - clap_app::get_clap_app, - cli::{parse_command, process_command}, + use { + super::*, + crate::{ + clap_app::get_clap_app, + cli::{parse_command, process_command}, + }, + serde_json::Value, + solana_cli_output::OutputFormat, + solana_sdk::signature::write_keypair_file, }; - use serde_json::Value; - use solana_cli_output::OutputFormat; - use solana_sdk::signature::write_keypair_file; fn make_tmp_path(name: &str) -> String { let out_dir = std::env::var("FARF_DIR").unwrap_or_else(|_| "farf".to_string()); diff --git a/cli/src/spend_utils.rs b/cli/src/spend_utils.rs index 84ff4b4e365269..b678e6e3502b46 100644 --- a/cli/src/spend_utils.rs +++ b/cli/src/spend_utils.rs @@ -1,13 +1,15 @@ -use crate::{ - checks::{check_account_for_balance_with_commitment, get_fee_for_messages}, - cli::CliError, -}; -use clap::ArgMatches; -use solana_clap_utils::{input_parsers::lamports_of_sol, offline::SIGN_ONLY_ARG}; -use solana_client::rpc_client::RpcClient; -use solana_sdk::{ - commitment_config::CommitmentConfig, hash::Hash, message::Message, - native_token::lamports_to_sol, pubkey::Pubkey, +use { + crate::{ + checks::{check_account_for_balance_with_commitment, get_fee_for_messages}, + cli::CliError, + }, + clap::ArgMatches, + solana_clap_utils::{input_parsers::lamports_of_sol, offline::SIGN_ONLY_ARG}, + solana_client::rpc_client::RpcClient, + solana_sdk::{ + commitment_config::CommitmentConfig, hash::Hash, message::Message, + native_token::lamports_to_sol, pubkey::Pubkey, + }, }; #[derive(Debug, PartialEq, Clone, Copy)] diff --git a/cli/src/stake.rs b/cli/src/stake.rs index d2b209a3285637..afbfcfcb7da3d6 100644 --- a/cli/src/stake.rs +++ b/cli/src/stake.rs @@ -1,53 +1,55 @@ -use crate::{ - checks::{check_account_for_fee_with_commitment, check_unique_pubkeys}, - cli::{ - log_instruction_custom_error, CliCommand, CliCommandInfo, CliConfig, CliError, - ProcessResult, +use { + crate::{ + checks::{check_account_for_fee_with_commitment, check_unique_pubkeys}, + cli::{ + log_instruction_custom_error, CliCommand, CliCommandInfo, CliConfig, CliError, + ProcessResult, + }, + memo::WithMemo, + nonce::check_nonce_account, + spend_utils::{resolve_spend_tx_and_check_account_balances, SpendAmount}, }, - memo::WithMemo, - nonce::check_nonce_account, - spend_utils::{resolve_spend_tx_and_check_account_balances, SpendAmount}, -}; -use clap::{value_t, App, Arg, ArgGroup, ArgMatches, SubCommand}; -use solana_clap_utils::{ - fee_payer::{fee_payer_arg, FEE_PAYER_ARG}, - input_parsers::*, - input_validators::*, - keypair::{DefaultSigner, SignerIndex}, - memo::{memo_arg, MEMO_ARG}, - nonce::*, - offline::*, - ArgConstant, -}; -use solana_cli_output::{ - return_signers_with_config, CliEpochReward, CliStakeHistory, CliStakeHistoryEntry, - CliStakeState, CliStakeType, OutputFormat, ReturnSignersConfig, -}; -use solana_client::{ - blockhash_query::BlockhashQuery, nonce_utils, rpc_client::RpcClient, - rpc_request::DELINQUENT_VALIDATOR_SLOT_DISTANCE, rpc_response::RpcInflationReward, -}; -use solana_remote_wallet::remote_wallet::RemoteWalletManager; -use solana_sdk::{ - account::from_account, - account_utils::StateMut, - clock::{Clock, UnixTimestamp, SECONDS_PER_DAY}, - commitment_config::CommitmentConfig, - epoch_schedule::EpochSchedule, - message::Message, - pubkey::Pubkey, - stake::{ - self, - instruction::{self as stake_instruction, LockupArgs, StakeError}, - state::{Authorized, Lockup, Meta, StakeActivationStatus, StakeAuthorize, StakeState}, + clap::{value_t, App, Arg, ArgGroup, ArgMatches, SubCommand}, + solana_clap_utils::{ + fee_payer::{fee_payer_arg, FEE_PAYER_ARG}, + input_parsers::*, + input_validators::*, + keypair::{DefaultSigner, SignerIndex}, + memo::{memo_arg, MEMO_ARG}, + nonce::*, + offline::*, + ArgConstant, }, - stake_history::StakeHistory, - system_instruction::SystemError, - sysvar::{clock, stake_history}, - transaction::Transaction, + solana_cli_output::{ + return_signers_with_config, CliEpochReward, CliStakeHistory, CliStakeHistoryEntry, + CliStakeState, CliStakeType, OutputFormat, ReturnSignersConfig, + }, + solana_client::{ + blockhash_query::BlockhashQuery, nonce_utils, rpc_client::RpcClient, + rpc_request::DELINQUENT_VALIDATOR_SLOT_DISTANCE, rpc_response::RpcInflationReward, + }, + solana_remote_wallet::remote_wallet::RemoteWalletManager, + solana_sdk::{ + account::from_account, + account_utils::StateMut, + clock::{Clock, UnixTimestamp, SECONDS_PER_DAY}, + commitment_config::CommitmentConfig, + epoch_schedule::EpochSchedule, + message::Message, + pubkey::Pubkey, + stake::{ + self, + instruction::{self as stake_instruction, LockupArgs, StakeError}, + state::{Authorized, Lockup, Meta, StakeActivationStatus, StakeAuthorize, StakeState}, + }, + stake_history::StakeHistory, + system_instruction::SystemError, + sysvar::{clock, stake_history}, + transaction::Transaction, + }, + solana_vote_program::vote_state::VoteState, + std::{ops::Deref, sync::Arc}, }; -use solana_vote_program::vote_state::VoteState; -use std::{ops::Deref, sync::Arc}; pub const STAKE_AUTHORITY_ARG: ArgConstant<'static> = ArgConstant { name: "stake_authority", @@ -2423,16 +2425,18 @@ pub fn process_delegate_stake( #[cfg(test)] mod tests { - use super::*; - use crate::{clap_app::get_clap_app, cli::parse_command}; - use solana_client::blockhash_query; - use solana_sdk::{ - hash::Hash, - signature::{ - keypair_from_seed, read_keypair_file, write_keypair, Keypair, Presigner, Signer, + use { + super::*, + crate::{clap_app::get_clap_app, cli::parse_command}, + solana_client::blockhash_query, + solana_sdk::{ + hash::Hash, + signature::{ + keypair_from_seed, read_keypair_file, write_keypair, Keypair, Presigner, Signer, + }, }, + tempfile::NamedTempFile, }; - use tempfile::NamedTempFile; fn make_tmp_file() -> (String, NamedTempFile) { let tmp_file = NamedTempFile::new().unwrap(); diff --git a/cli/src/test_utils.rs b/cli/src/test_utils.rs index 4e526d7f63ec0d..b3903ad090c9c0 100644 --- a/cli/src/test_utils.rs +++ b/cli/src/test_utils.rs @@ -1,6 +1,8 @@ -use solana_client::rpc_client::RpcClient; -use solana_sdk::{clock::DEFAULT_MS_PER_SLOT, commitment_config::CommitmentConfig, pubkey::Pubkey}; -use std::{thread::sleep, time::Duration}; +use { + solana_client::rpc_client::RpcClient, + solana_sdk::{clock::DEFAULT_MS_PER_SLOT, commitment_config::CommitmentConfig, pubkey::Pubkey}, + std::{thread::sleep, time::Duration}, +}; pub fn check_recent_balance(expected_balance: u64, client: &RpcClient, pubkey: &Pubkey) { (0..5).for_each(|tries| { diff --git a/cli/src/validator_info.rs b/cli/src/validator_info.rs index 8927c9a461dbac..79fb640befffde 100644 --- a/cli/src/validator_info.rs +++ b/cli/src/validator_info.rs @@ -1,31 +1,33 @@ -use crate::{ - cli::{CliCommand, CliCommandInfo, CliConfig, CliError, ProcessResult}, - spend_utils::{resolve_spend_tx_and_check_account_balance, SpendAmount}, +use { + crate::{ + cli::{CliCommand, CliCommandInfo, CliConfig, CliError, ProcessResult}, + spend_utils::{resolve_spend_tx_and_check_account_balance, SpendAmount}, + }, + bincode::deserialize, + clap::{App, AppSettings, Arg, ArgMatches, SubCommand}, + reqwest::blocking::Client, + serde_json::{Map, Value}, + solana_account_decoder::validator_info::{ + self, ValidatorInfo, MAX_LONG_FIELD_LENGTH, MAX_SHORT_FIELD_LENGTH, + }, + solana_clap_utils::{ + input_parsers::pubkey_of, + input_validators::{is_pubkey, is_url}, + keypair::DefaultSigner, + }, + solana_cli_output::{CliValidatorInfo, CliValidatorInfoVec}, + solana_client::rpc_client::RpcClient, + solana_config_program::{config_instruction, get_config_data, ConfigKeys, ConfigState}, + solana_remote_wallet::remote_wallet::RemoteWalletManager, + solana_sdk::{ + account::Account, + message::Message, + pubkey::Pubkey, + signature::{Keypair, Signer}, + transaction::Transaction, + }, + std::{error, sync::Arc}, }; -use bincode::deserialize; -use clap::{App, AppSettings, Arg, ArgMatches, SubCommand}; -use reqwest::blocking::Client; -use serde_json::{Map, Value}; -use solana_account_decoder::validator_info::{ - self, ValidatorInfo, MAX_LONG_FIELD_LENGTH, MAX_SHORT_FIELD_LENGTH, -}; -use solana_clap_utils::{ - input_parsers::pubkey_of, - input_validators::{is_pubkey, is_url}, - keypair::DefaultSigner, -}; -use solana_cli_output::{CliValidatorInfo, CliValidatorInfoVec}; -use solana_client::rpc_client::RpcClient; -use solana_config_program::{config_instruction, get_config_data, ConfigKeys, ConfigState}; -use solana_remote_wallet::remote_wallet::RemoteWalletManager; -use solana_sdk::{ - account::Account, - message::Message, - pubkey::Pubkey, - signature::{Keypair, Signer}, - transaction::Transaction, -}; -use std::{error, sync::Arc}; // Return an error if a validator details are longer than the max length. pub fn check_details_length(string: String) -> Result<(), String> { @@ -407,10 +409,12 @@ pub fn process_get_validator_info( #[cfg(test)] mod tests { - use super::*; - use crate::clap_app::get_clap_app; - use bincode::{serialize, serialized_size}; - use serde_json::json; + use { + super::*, + crate::clap_app::get_clap_app, + bincode::{serialize, serialized_size}, + serde_json::json, + }; #[test] fn test_check_details_length() { diff --git a/cli/src/vote.rs b/cli/src/vote.rs index 7e4d5b7d86fddb..d616bd9444752d 100644 --- a/cli/src/vote.rs +++ b/cli/src/vote.rs @@ -1,33 +1,35 @@ -use crate::{ - checks::{check_account_for_fee_with_commitment, check_unique_pubkeys}, - cli::{ - log_instruction_custom_error, CliCommand, CliCommandInfo, CliConfig, CliError, - ProcessResult, +use { + crate::{ + checks::{check_account_for_fee_with_commitment, check_unique_pubkeys}, + cli::{ + log_instruction_custom_error, CliCommand, CliCommandInfo, CliConfig, CliError, + ProcessResult, + }, + memo::WithMemo, + spend_utils::{resolve_spend_tx_and_check_account_balance, SpendAmount}, + stake::check_current_authority, }, - memo::WithMemo, - spend_utils::{resolve_spend_tx_and_check_account_balance, SpendAmount}, - stake::check_current_authority, -}; -use clap::{value_t_or_exit, App, Arg, ArgMatches, SubCommand}; -use solana_clap_utils::{ - input_parsers::*, - input_validators::*, - keypair::{DefaultSigner, SignerIndex}, - memo::{memo_arg, MEMO_ARG}, -}; -use solana_cli_output::{CliEpochVotingHistory, CliLockout, CliVoteAccount}; -use solana_client::{rpc_client::RpcClient, rpc_config::RpcGetVoteAccountsConfig}; -use solana_remote_wallet::remote_wallet::RemoteWalletManager; -use solana_sdk::{ - account::Account, commitment_config::CommitmentConfig, message::Message, - native_token::lamports_to_sol, pubkey::Pubkey, system_instruction::SystemError, - transaction::Transaction, -}; -use solana_vote_program::{ - vote_instruction::{self, withdraw, VoteError}, - vote_state::{VoteAuthorize, VoteInit, VoteState}, + clap::{value_t_or_exit, App, Arg, ArgMatches, SubCommand}, + solana_clap_utils::{ + input_parsers::*, + input_validators::*, + keypair::{DefaultSigner, SignerIndex}, + memo::{memo_arg, MEMO_ARG}, + }, + solana_cli_output::{CliEpochVotingHistory, CliLockout, CliVoteAccount}, + solana_client::{rpc_client::RpcClient, rpc_config::RpcGetVoteAccountsConfig}, + solana_remote_wallet::remote_wallet::RemoteWalletManager, + solana_sdk::{ + account::Account, commitment_config::CommitmentConfig, message::Message, + native_token::lamports_to_sol, pubkey::Pubkey, system_instruction::SystemError, + transaction::Transaction, + }, + solana_vote_program::{ + vote_instruction::{self, withdraw, VoteError}, + vote_state::{VoteAuthorize, VoteInit, VoteState}, + }, + std::sync::Arc, }; -use std::sync::Arc; pub trait VoteSubCommands { fn vote_subcommands(self) -> Self; @@ -1049,10 +1051,12 @@ pub fn process_close_vote_account( #[cfg(test)] mod tests { - use super::*; - use crate::{clap_app::get_clap_app, cli::parse_command}; - use solana_sdk::signature::{read_keypair_file, write_keypair, Keypair, Signer}; - use tempfile::NamedTempFile; + use { + super::*, + crate::{clap_app::get_clap_app, cli::parse_command}, + solana_sdk::signature::{read_keypair_file, write_keypair, Keypair, Signer}, + tempfile::NamedTempFile, + }; fn make_tmp_file() -> (String, NamedTempFile) { let tmp_file = NamedTempFile::new().unwrap(); diff --git a/cli/src/wallet.rs b/cli/src/wallet.rs index baa9f44bf2f8f1..0abcffccbc1991 100644 --- a/cli/src/wallet.rs +++ b/cli/src/wallet.rs @@ -1,45 +1,47 @@ -use crate::{ - cli::{ - log_instruction_custom_error, request_and_confirm_airdrop, CliCommand, CliCommandInfo, - CliConfig, CliError, ProcessResult, +use { + crate::{ + cli::{ + log_instruction_custom_error, request_and_confirm_airdrop, CliCommand, CliCommandInfo, + CliConfig, CliError, ProcessResult, + }, + memo::WithMemo, + nonce::check_nonce_account, + spend_utils::{resolve_spend_tx_and_check_account_balances, SpendAmount}, }, - memo::WithMemo, - nonce::check_nonce_account, - spend_utils::{resolve_spend_tx_and_check_account_balances, SpendAmount}, -}; -use clap::{value_t_or_exit, App, Arg, ArgMatches, SubCommand}; -use solana_account_decoder::{UiAccount, UiAccountEncoding}; -use solana_clap_utils::{ - fee_payer::*, - input_parsers::*, - input_validators::*, - keypair::{DefaultSigner, SignerIndex}, - memo::*, - nonce::*, - offline::*, -}; -use solana_cli_output::{ - display::build_balance_message, return_signers_with_config, CliAccount, - CliSignatureVerificationStatus, CliTransaction, CliTransactionConfirmation, OutputFormat, - ReturnSignersConfig, -}; -use solana_client::{ - blockhash_query::BlockhashQuery, nonce_utils, rpc_client::RpcClient, - rpc_config::RpcTransactionConfig, rpc_response::RpcKeyedAccount, -}; -use solana_remote_wallet::remote_wallet::RemoteWalletManager; -use solana_sdk::{ - commitment_config::CommitmentConfig, - message::Message, - pubkey::Pubkey, - signature::Signature, - stake, - system_instruction::{self, SystemError}, - system_program, - transaction::Transaction, + clap::{value_t_or_exit, App, Arg, ArgMatches, SubCommand}, + solana_account_decoder::{UiAccount, UiAccountEncoding}, + solana_clap_utils::{ + fee_payer::*, + input_parsers::*, + input_validators::*, + keypair::{DefaultSigner, SignerIndex}, + memo::*, + nonce::*, + offline::*, + }, + solana_cli_output::{ + display::build_balance_message, return_signers_with_config, CliAccount, + CliSignatureVerificationStatus, CliTransaction, CliTransactionConfirmation, OutputFormat, + ReturnSignersConfig, + }, + solana_client::{ + blockhash_query::BlockhashQuery, nonce_utils, rpc_client::RpcClient, + rpc_config::RpcTransactionConfig, rpc_response::RpcKeyedAccount, + }, + solana_remote_wallet::remote_wallet::RemoteWalletManager, + solana_sdk::{ + commitment_config::CommitmentConfig, + message::Message, + pubkey::Pubkey, + signature::Signature, + stake, + system_instruction::{self, SystemError}, + system_program, + transaction::Transaction, + }, + solana_transaction_status::{EncodedTransaction, UiTransactionEncoding}, + std::{fmt::Write as FmtWrite, fs::File, io::Write, sync::Arc}, }; -use solana_transaction_status::{EncodedTransaction, UiTransactionEncoding}; -use std::{fmt::Write as FmtWrite, fs::File, io::Write, sync::Arc}; pub trait WalletSubCommands { fn wallet_subcommands(self) -> Self; diff --git a/cli/tests/nonce.rs b/cli/tests/nonce.rs index 5aeccb97eb4a25..855ab2b774550b 100644 --- a/cli/tests/nonce.rs +++ b/cli/tests/nonce.rs @@ -1,24 +1,26 @@ -use solana_cli::{ - cli::{process_command, request_and_confirm_airdrop, CliCommand, CliConfig}, - spend_utils::SpendAmount, - test_utils::{check_ready, check_recent_balance}, +use { + solana_cli::{ + cli::{process_command, request_and_confirm_airdrop, CliCommand, CliConfig}, + spend_utils::SpendAmount, + test_utils::{check_ready, check_recent_balance}, + }, + solana_cli_output::{parse_sign_only_reply_string, OutputFormat}, + solana_client::{ + blockhash_query::{self, BlockhashQuery}, + nonce_utils, + rpc_client::RpcClient, + }, + solana_faucet::faucet::run_local_faucet, + solana_sdk::{ + commitment_config::CommitmentConfig, + hash::Hash, + pubkey::Pubkey, + signature::{keypair_from_seed, Keypair, Signer}, + system_program, + }, + solana_streamer::socket::SocketAddrSpace, + solana_test_validator::TestValidator, }; -use solana_cli_output::{parse_sign_only_reply_string, OutputFormat}; -use solana_client::{ - blockhash_query::{self, BlockhashQuery}, - nonce_utils, - rpc_client::RpcClient, -}; -use solana_faucet::faucet::run_local_faucet; -use solana_sdk::{ - commitment_config::CommitmentConfig, - hash::Hash, - pubkey::Pubkey, - signature::{keypair_from_seed, Keypair, Signer}, - system_program, -}; -use solana_streamer::socket::SocketAddrSpace; -use solana_test_validator::TestValidator; #[test] fn test_nonce() { diff --git a/cli/tests/program.rs b/cli/tests/program.rs index b6efecc7dcf474..8863509182c436 100644 --- a/cli/tests/program.rs +++ b/cli/tests/program.rs @@ -1,22 +1,24 @@ -use serde_json::Value; -use solana_cli::{ - cli::{process_command, CliCommand, CliConfig}, - program::ProgramCliCommand, +use { + serde_json::Value, + solana_cli::{ + cli::{process_command, CliCommand, CliConfig}, + program::ProgramCliCommand, + }, + solana_cli_output::OutputFormat, + solana_client::rpc_client::RpcClient, + solana_faucet::faucet::run_local_faucet, + solana_sdk::{ + account_utils::StateMut, + bpf_loader, + bpf_loader_upgradeable::{self, UpgradeableLoaderState}, + commitment_config::CommitmentConfig, + pubkey::Pubkey, + signature::{Keypair, Signer}, + }, + solana_streamer::socket::SocketAddrSpace, + solana_test_validator::TestValidator, + std::{env, fs::File, io::Read, path::PathBuf, str::FromStr}, }; -use solana_cli_output::OutputFormat; -use solana_client::rpc_client::RpcClient; -use solana_faucet::faucet::run_local_faucet; -use solana_sdk::{ - account_utils::StateMut, - bpf_loader, - bpf_loader_upgradeable::{self, UpgradeableLoaderState}, - commitment_config::CommitmentConfig, - pubkey::Pubkey, - signature::{Keypair, Signer}, -}; -use solana_streamer::socket::SocketAddrSpace; -use solana_test_validator::TestValidator; -use std::{env, fs::File, io::Read, path::PathBuf, str::FromStr}; #[test] fn test_cli_program_deploy_non_upgradeable() { diff --git a/cli/tests/request_airdrop.rs b/cli/tests/request_airdrop.rs index a437bf3bc4e1bf..8a724d4862817c 100644 --- a/cli/tests/request_airdrop.rs +++ b/cli/tests/request_airdrop.rs @@ -1,12 +1,14 @@ -use solana_cli::cli::{process_command, CliCommand, CliConfig}; -use solana_client::rpc_client::RpcClient; -use solana_faucet::faucet::run_local_faucet; -use solana_sdk::{ - commitment_config::CommitmentConfig, - signature::{Keypair, Signer}, +use { + solana_cli::cli::{process_command, CliCommand, CliConfig}, + solana_client::rpc_client::RpcClient, + solana_faucet::faucet::run_local_faucet, + solana_sdk::{ + commitment_config::CommitmentConfig, + signature::{Keypair, Signer}, + }, + solana_streamer::socket::SocketAddrSpace, + solana_test_validator::TestValidator, }; -use solana_streamer::socket::SocketAddrSpace; -use solana_test_validator::TestValidator; #[test] fn test_cli_request_airdrop() { diff --git a/cli/tests/stake.rs b/cli/tests/stake.rs index 580205818a25f4..2b77535b121672 100644 --- a/cli/tests/stake.rs +++ b/cli/tests/stake.rs @@ -1,31 +1,33 @@ #![allow(clippy::redundant_closure)] -use solana_cli::{ - cli::{process_command, request_and_confirm_airdrop, CliCommand, CliConfig}, - spend_utils::SpendAmount, - stake::StakeAuthorizationIndexed, - test_utils::{check_ready, check_recent_balance}, -}; -use solana_cli_output::{parse_sign_only_reply_string, OutputFormat}; -use solana_client::{ - blockhash_query::{self, BlockhashQuery}, - nonce_utils, - rpc_client::RpcClient, -}; -use solana_faucet::faucet::run_local_faucet; -use solana_sdk::{ - account_utils::StateMut, - commitment_config::CommitmentConfig, - nonce::State as NonceState, - pubkey::Pubkey, - signature::{keypair_from_seed, Keypair, Signer}, - stake::{ - self, - instruction::LockupArgs, - state::{Lockup, StakeAuthorize, StakeState}, +use { + solana_cli::{ + cli::{process_command, request_and_confirm_airdrop, CliCommand, CliConfig}, + spend_utils::SpendAmount, + stake::StakeAuthorizationIndexed, + test_utils::{check_ready, check_recent_balance}, + }, + solana_cli_output::{parse_sign_only_reply_string, OutputFormat}, + solana_client::{ + blockhash_query::{self, BlockhashQuery}, + nonce_utils, + rpc_client::RpcClient, + }, + solana_faucet::faucet::run_local_faucet, + solana_sdk::{ + account_utils::StateMut, + commitment_config::CommitmentConfig, + nonce::State as NonceState, + pubkey::Pubkey, + signature::{keypair_from_seed, Keypair, Signer}, + stake::{ + self, + instruction::LockupArgs, + state::{Lockup, StakeAuthorize, StakeState}, + }, }, + solana_streamer::socket::SocketAddrSpace, + solana_test_validator::TestValidator, }; -use solana_streamer::socket::SocketAddrSpace; -use solana_test_validator::TestValidator; #[test] fn test_stake_delegation_force() { diff --git a/cli/tests/transfer.rs b/cli/tests/transfer.rs index 20bddbe1fa57da..2fd8b09cbb2473 100644 --- a/cli/tests/transfer.rs +++ b/cli/tests/transfer.rs @@ -1,25 +1,27 @@ #![allow(clippy::redundant_closure)] -use solana_cli::{ - cli::{process_command, request_and_confirm_airdrop, CliCommand, CliConfig}, - spend_utils::SpendAmount, - test_utils::{check_ready, check_recent_balance}, +use { + solana_cli::{ + cli::{process_command, request_and_confirm_airdrop, CliCommand, CliConfig}, + spend_utils::SpendAmount, + test_utils::{check_ready, check_recent_balance}, + }, + solana_cli_output::{parse_sign_only_reply_string, OutputFormat}, + solana_client::{ + blockhash_query::{self, BlockhashQuery}, + nonce_utils, + rpc_client::RpcClient, + }, + solana_faucet::faucet::run_local_faucet, + solana_sdk::{ + commitment_config::CommitmentConfig, + nonce::State as NonceState, + pubkey::Pubkey, + signature::{keypair_from_seed, Keypair, NullSigner, Signer}, + stake, + }, + solana_streamer::socket::SocketAddrSpace, + solana_test_validator::TestValidator, }; -use solana_cli_output::{parse_sign_only_reply_string, OutputFormat}; -use solana_client::{ - blockhash_query::{self, BlockhashQuery}, - nonce_utils, - rpc_client::RpcClient, -}; -use solana_faucet::faucet::run_local_faucet; -use solana_sdk::{ - commitment_config::CommitmentConfig, - nonce::State as NonceState, - pubkey::Pubkey, - signature::{keypair_from_seed, Keypair, NullSigner, Signer}, - stake, -}; -use solana_streamer::socket::SocketAddrSpace; -use solana_test_validator::TestValidator; #[test] fn test_transfer() { diff --git a/cli/tests/vote.rs b/cli/tests/vote.rs index 904c981a60b608..ad3dd0714e2c10 100644 --- a/cli/tests/vote.rs +++ b/cli/tests/vote.rs @@ -1,21 +1,23 @@ -use solana_cli::{ - cli::{process_command, request_and_confirm_airdrop, CliCommand, CliConfig}, - spend_utils::SpendAmount, - test_utils::check_recent_balance, +use { + solana_cli::{ + cli::{process_command, request_and_confirm_airdrop, CliCommand, CliConfig}, + spend_utils::SpendAmount, + test_utils::check_recent_balance, + }, + solana_client::{ + blockhash_query::{self, BlockhashQuery}, + rpc_client::RpcClient, + }, + solana_faucet::faucet::run_local_faucet, + solana_sdk::{ + account_utils::StateMut, + commitment_config::CommitmentConfig, + signature::{Keypair, Signer}, + }, + solana_streamer::socket::SocketAddrSpace, + solana_test_validator::TestValidator, + solana_vote_program::vote_state::{VoteAuthorize, VoteState, VoteStateVersions}, }; -use solana_client::{ - blockhash_query::{self, BlockhashQuery}, - rpc_client::RpcClient, -}; -use solana_faucet::faucet::run_local_faucet; -use solana_sdk::{ - account_utils::StateMut, - commitment_config::CommitmentConfig, - signature::{Keypair, Signer}, -}; -use solana_streamer::socket::SocketAddrSpace; -use solana_test_validator::TestValidator; -use solana_vote_program::vote_state::{VoteAuthorize, VoteState, VoteStateVersions}; #[test] fn test_vote_authorize_and_withdraw() { diff --git a/client-test/tests/client.rs b/client-test/tests/client.rs index 986e8355d6c63e..799cdc41d7a31d 100644 --- a/client-test/tests/client.rs +++ b/client-test/tests/client.rs @@ -1,44 +1,46 @@ -use serde_json::{json, Value}; -use serial_test::serial; -use solana_client::{ - pubsub_client::PubsubClient, - rpc_client::RpcClient, - rpc_config::{RpcAccountInfoConfig, RpcProgramAccountsConfig}, - rpc_response::SlotInfo, -}; -use solana_rpc::{ - optimistically_confirmed_bank_tracker::OptimisticallyConfirmedBank, - rpc_pubsub_service::{PubSubConfig, PubSubService}, - rpc_subscriptions::RpcSubscriptions, -}; -use solana_runtime::{ - bank::Bank, - bank_forks::BankForks, - commitment::{BlockCommitmentCache, CommitmentSlots}, - genesis_utils::{create_genesis_config, GenesisConfigInfo}, -}; -use solana_sdk::{ - clock::Slot, - commitment_config::CommitmentConfig, - native_token::sol_to_lamports, - pubkey::Pubkey, - rpc_port, - signature::{Keypair, Signer}, - system_program, system_transaction, -}; -use solana_streamer::socket::SocketAddrSpace; -use solana_test_validator::TestValidator; -use std::{ - collections::HashSet, - net::{IpAddr, SocketAddr}, - sync::{ - atomic::{AtomicBool, Ordering}, - Arc, RwLock, +use { + serde_json::{json, Value}, + serial_test::serial, + solana_client::{ + pubsub_client::PubsubClient, + rpc_client::RpcClient, + rpc_config::{RpcAccountInfoConfig, RpcProgramAccountsConfig}, + rpc_response::SlotInfo, + }, + solana_rpc::{ + optimistically_confirmed_bank_tracker::OptimisticallyConfirmedBank, + rpc_pubsub_service::{PubSubConfig, PubSubService}, + rpc_subscriptions::RpcSubscriptions, + }, + solana_runtime::{ + bank::Bank, + bank_forks::BankForks, + commitment::{BlockCommitmentCache, CommitmentSlots}, + genesis_utils::{create_genesis_config, GenesisConfigInfo}, + }, + solana_sdk::{ + clock::Slot, + commitment_config::CommitmentConfig, + native_token::sol_to_lamports, + pubkey::Pubkey, + rpc_port, + signature::{Keypair, Signer}, + system_program, system_transaction, + }, + solana_streamer::socket::SocketAddrSpace, + solana_test_validator::TestValidator, + std::{ + collections::HashSet, + net::{IpAddr, SocketAddr}, + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, RwLock, + }, + thread::sleep, + time::{Duration, Instant}, }, - thread::sleep, - time::{Duration, Instant}, + systemstat::Ipv4Addr, }; -use systemstat::Ipv4Addr; #[test] fn test_rpc_client() { diff --git a/client/src/blockhash_query.rs b/client/src/blockhash_query.rs index c18af1f42f68ba..ca7522a12456aa 100644 --- a/client/src/blockhash_query.rs +++ b/client/src/blockhash_query.rs @@ -183,17 +183,19 @@ impl Default for BlockhashQuery { #[cfg(test)] mod tests { - use super::*; - use crate::{ - blockhash_query, - rpc_request::RpcRequest, - rpc_response::{Response, RpcFeeCalculator, RpcFees, RpcResponseContext}, + use { + super::*, + crate::{ + blockhash_query, + rpc_request::RpcRequest, + rpc_response::{Response, RpcFeeCalculator, RpcFees, RpcResponseContext}, + }, + clap::App, + serde_json::{self, json}, + solana_account_decoder::{UiAccount, UiAccountEncoding}, + solana_sdk::{account::Account, hash::hash, nonce, system_program}, + std::collections::HashMap, }; - use clap::App; - use serde_json::{self, json}; - use solana_account_decoder::{UiAccount, UiAccountEncoding}; - use solana_sdk::{account::Account, hash::hash, nonce, system_program}; - use std::collections::HashMap; #[test] fn test_blockhash_query_new_ok() { diff --git a/client/src/client_error.rs b/client/src/client_error.rs index 365d70941c4b4d..64d1d5c2f674f6 100644 --- a/client/src/client_error.rs +++ b/client/src/client_error.rs @@ -1,3 +1,4 @@ +pub use reqwest; use { crate::{rpc_request, rpc_response}, solana_faucet::faucet::FaucetError, @@ -6,9 +7,7 @@ use { }, std::io, thiserror::Error, -}; - -pub use reqwest; // export `reqwest` for clients +}; // export `reqwest` for clients #[derive(Error, Debug)] pub enum ClientErrorKind { diff --git a/client/src/rpc_client.rs b/client/src/rpc_client.rs index bdb0374108e452..afccbb7ba5c915 100644 --- a/client/src/rpc_client.rs +++ b/client/src/rpc_client.rs @@ -16,8 +16,7 @@ use { client_error::{ClientError, ClientErrorKind, Result as ClientResult}, http_sender::HttpSender, mock_sender::{MockSender, Mocks}, - rpc_config::RpcAccountInfoConfig, - rpc_config::*, + rpc_config::{RpcAccountInfoConfig, *}, rpc_request::{RpcError, RpcRequest, RpcResponseErrorData, TokenAccountsFilter}, rpc_response::*, rpc_sender::*, @@ -4937,19 +4936,21 @@ pub fn create_rpc_client_mocks() -> crate::mock_sender::Mocks { #[cfg(test)] mod tests { - use super::*; - use crate::{client_error::ClientErrorKind, mock_sender::PUBKEY}; - use assert_matches::assert_matches; - use jsonrpc_core::{futures::prelude::*, Error, IoHandler, Params}; - use jsonrpc_http_server::{AccessControlAllowOrigin, DomainsValidation, ServerBuilder}; - use serde_json::Number; - use solana_sdk::{ - instruction::InstructionError, - signature::{Keypair, Signer}, - system_transaction, - transaction::TransactionError, + use { + super::*, + crate::{client_error::ClientErrorKind, mock_sender::PUBKEY}, + assert_matches::assert_matches, + jsonrpc_core::{futures::prelude::*, Error, IoHandler, Params}, + jsonrpc_http_server::{AccessControlAllowOrigin, DomainsValidation, ServerBuilder}, + serde_json::Number, + solana_sdk::{ + instruction::InstructionError, + signature::{Keypair, Signer}, + system_transaction, + transaction::TransactionError, + }, + std::{io, sync::mpsc::channel, thread}, }; - use std::{io, sync::mpsc::channel, thread}; #[test] fn test_send() { diff --git a/client/src/rpc_custom_error.rs b/client/src/rpc_custom_error.rs index fb195c4b49f99c..6b0aa2f9598f43 100644 --- a/client/src/rpc_custom_error.rs +++ b/client/src/rpc_custom_error.rs @@ -1,9 +1,9 @@ //! Implementation defined RPC server errors -use thiserror::Error; use { crate::rpc_response::RpcSimulateTransactionResult, jsonrpc_core::{Error, ErrorCode}, solana_sdk::clock::Slot, + thiserror::Error, }; pub const JSON_RPC_SERVER_ERROR_BLOCK_CLEANED_UP: i64 = -32001; diff --git a/client/src/rpc_request.rs b/client/src/rpc_request.rs index 5ff675e6568ea0..03f4b391008be8 100644 --- a/client/src/rpc_request.rs +++ b/client/src/rpc_request.rs @@ -267,9 +267,11 @@ pub enum TokenAccountsFilter { #[cfg(test)] mod tests { - use super::*; - use crate::rpc_config::RpcTokenAccountsFilter; - use solana_sdk::commitment_config::{CommitmentConfig, CommitmentLevel}; + use { + super::*, + crate::rpc_config::RpcTokenAccountsFilter, + solana_sdk::commitment_config::{CommitmentConfig, CommitmentLevel}, + }; #[test] fn test_build_request_json() { diff --git a/client/src/thin_client.rs b/client/src/thin_client.rs index 428d309055d280..12b50eb60647ca 100644 --- a/client/src/thin_client.rs +++ b/client/src/thin_client.rs @@ -667,8 +667,7 @@ pub fn create_client_with_timeout( #[cfg(test)] mod tests { - use super::*; - use rayon::prelude::*; + use {super::*, rayon::prelude::*}; #[test] fn test_client_optimizer() { diff --git a/client/src/tpu_client.rs b/client/src/tpu_client.rs index 6823f0d982f6a8..10c649e3d1883c 100644 --- a/client/src/tpu_client.rs +++ b/client/src/tpu_client.rs @@ -1,34 +1,36 @@ -use crate::{ - client_error::ClientError, - pubsub_client::{PubsubClient, PubsubClientError, PubsubClientSubscription}, - rpc_client::RpcClient, - rpc_request::MAX_GET_SIGNATURE_STATUSES_QUERY_ITEMS, - rpc_response::SlotUpdate, - spinner, -}; -use bincode::serialize; -use log::*; -use solana_sdk::{ - clock::Slot, - commitment_config::CommitmentConfig, - message::Message, - pubkey::Pubkey, - signature::SignerError, - signers::Signers, - transaction::{Transaction, TransactionError}, -}; -use std::{ - collections::{HashMap, HashSet, VecDeque}, - net::{SocketAddr, UdpSocket}, - str::FromStr, - sync::{ - atomic::{AtomicBool, Ordering}, - Arc, RwLock, +use { + crate::{ + client_error::ClientError, + pubsub_client::{PubsubClient, PubsubClientError, PubsubClientSubscription}, + rpc_client::RpcClient, + rpc_request::MAX_GET_SIGNATURE_STATUSES_QUERY_ITEMS, + rpc_response::SlotUpdate, + spinner, + }, + bincode::serialize, + log::*, + solana_sdk::{ + clock::Slot, + commitment_config::CommitmentConfig, + message::Message, + pubkey::Pubkey, + signature::SignerError, + signers::Signers, + transaction::{Transaction, TransactionError}, + }, + std::{ + collections::{HashMap, HashSet, VecDeque}, + net::{SocketAddr, UdpSocket}, + str::FromStr, + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, RwLock, + }, + thread::{sleep, JoinHandle}, + time::{Duration, Instant}, }, - thread::{sleep, JoinHandle}, - time::{Duration, Instant}, + thiserror::Error, }; -use thiserror::Error; #[derive(Error, Debug)] pub enum TpuSenderError { diff --git a/client/src/transaction_executor.rs b/client/src/transaction_executor.rs index 377e52fb15aed0..56f7a8002275e4 100644 --- a/client/src/transaction_executor.rs +++ b/client/src/transaction_executor.rs @@ -1,19 +1,21 @@ #![allow(clippy::integer_arithmetic)] -use crate::rpc_client::RpcClient; -use log::*; -use solana_measure::measure::Measure; -use solana_sdk::{ - commitment_config::CommitmentConfig, signature::Signature, timing::timestamp, - transaction::Transaction, -}; -use std::{ - net::SocketAddr, - sync::{ - atomic::{AtomicBool, AtomicU64, Ordering}, - Arc, RwLock, +use { + crate::rpc_client::RpcClient, + log::*, + solana_measure::measure::Measure, + solana_sdk::{ + commitment_config::CommitmentConfig, signature::Signature, timing::timestamp, + transaction::Transaction, + }, + std::{ + net::SocketAddr, + sync::{ + atomic::{AtomicBool, AtomicU64, Ordering}, + Arc, RwLock, + }, + thread::{sleep, Builder, JoinHandle}, + time::{Duration, Instant}, }, - thread::{sleep, Builder, JoinHandle}, - time::{Duration, Instant}, }; // signature, timestamp, id diff --git a/core/benches/banking_stage.rs b/core/benches/banking_stage.rs index 14959b98440f70..1b9e79a8568482 100644 --- a/core/benches/banking_stage.rs +++ b/core/benches/banking_stage.rs @@ -3,41 +3,44 @@ extern crate test; -use crossbeam_channel::unbounded; -use log::*; -use rand::{thread_rng, Rng}; -use rayon::prelude::*; -use solana_core::banking_stage::{BankingStage, BankingStageStats}; -use solana_core::qos_service::QosService; -use solana_entry::entry::{next_hash, Entry}; -use solana_gossip::cluster_info::ClusterInfo; -use solana_gossip::cluster_info::Node; -use solana_ledger::blockstore_processor::process_entries_for_tests; -use solana_ledger::genesis_utils::{create_genesis_config, GenesisConfigInfo}; -use solana_ledger::{blockstore::Blockstore, get_tmp_ledger_path}; -use solana_perf::packet::to_packets_chunked; -use solana_perf::test_tx::test_tx; -use solana_poh::poh_recorder::{create_test_recorder, WorkingBankEntry}; -use solana_runtime::bank::Bank; -use solana_runtime::cost_model::CostModel; -use solana_sdk::genesis_config::GenesisConfig; -use solana_sdk::hash::Hash; -use solana_sdk::message::Message; -use solana_sdk::pubkey; -use solana_sdk::signature::Keypair; -use solana_sdk::signature::Signature; -use solana_sdk::signature::Signer; -use solana_sdk::system_instruction; -use solana_sdk::system_transaction; -use solana_sdk::timing::{duration_as_us, timestamp}; -use solana_sdk::transaction::{Transaction, VersionedTransaction}; -use solana_streamer::socket::SocketAddrSpace; -use std::collections::VecDeque; -use std::sync::atomic::Ordering; -use std::sync::mpsc::Receiver; -use std::sync::{Arc, RwLock}; -use std::time::{Duration, Instant}; -use test::Bencher; +use { + crossbeam_channel::unbounded, + log::*, + rand::{thread_rng, Rng}, + rayon::prelude::*, + solana_core::{ + banking_stage::{BankingStage, BankingStageStats}, + qos_service::QosService, + }, + solana_entry::entry::{next_hash, Entry}, + solana_gossip::cluster_info::{ClusterInfo, Node}, + solana_ledger::{ + blockstore::Blockstore, + blockstore_processor::process_entries_for_tests, + genesis_utils::{create_genesis_config, GenesisConfigInfo}, + get_tmp_ledger_path, + }, + solana_perf::{packet::to_packets_chunked, test_tx::test_tx}, + solana_poh::poh_recorder::{create_test_recorder, WorkingBankEntry}, + solana_runtime::{bank::Bank, cost_model::CostModel}, + solana_sdk::{ + genesis_config::GenesisConfig, + hash::Hash, + message::Message, + pubkey, + signature::{Keypair, Signature, Signer}, + system_instruction, system_transaction, + timing::{duration_as_us, timestamp}, + transaction::{Transaction, VersionedTransaction}, + }, + solana_streamer::socket::SocketAddrSpace, + std::{ + collections::VecDeque, + sync::{atomic::Ordering, mpsc::Receiver, Arc, RwLock}, + time::{Duration, Instant}, + }, + test::Bencher, +}; fn check_txs(receiver: &Arc>, ref_tx_count: usize) { let mut total = 0; diff --git a/core/benches/consensus.rs b/core/benches/consensus.rs index b72b955bc045ad..247a5c53273850 100644 --- a/core/benches/consensus.rs +++ b/core/benches/consensus.rs @@ -7,8 +7,7 @@ use { solana_core::{ consensus::Tower, tower_storage::FileTowerStorage, vote_simulator::VoteSimulator, }, - solana_runtime::bank::Bank, - solana_runtime::bank_forks::BankForks, + solana_runtime::{bank::Bank, bank_forks::BankForks}, solana_sdk::{ pubkey::Pubkey, signature::{Keypair, Signer}, diff --git a/core/benches/gen_keys.rs b/core/benches/gen_keys.rs index c584e83ed2be8f..410ec2b733b1fa 100644 --- a/core/benches/gen_keys.rs +++ b/core/benches/gen_keys.rs @@ -2,8 +2,7 @@ extern crate test; -use solana_core::gen_keys::GenKeys; -use test::Bencher; +use {solana_core::gen_keys::GenKeys, test::Bencher}; #[bench] fn bench_gen_keys(b: &mut Bencher) { diff --git a/core/benches/shredder.rs b/core/benches/shredder.rs index 97f503c2dfc2f3..d632858a8c129f 100644 --- a/core/benches/shredder.rs +++ b/core/benches/shredder.rs @@ -3,18 +3,19 @@ extern crate test; -use rand::seq::SliceRandom; -use raptorq::{Decoder, Encoder}; -use solana_entry::entry::{create_ticks, Entry}; -use solana_ledger::shred::{ - max_entries_per_n_shred, max_ticks_per_n_shreds, ProcessShredsStats, Shred, Shredder, - MAX_DATA_SHREDS_PER_FEC_BLOCK, SHRED_PAYLOAD_SIZE, SIZE_OF_CODING_SHRED_HEADERS, - SIZE_OF_DATA_SHRED_PAYLOAD, +use { + rand::seq::SliceRandom, + raptorq::{Decoder, Encoder}, + solana_entry::entry::{create_ticks, Entry}, + solana_ledger::shred::{ + max_entries_per_n_shred, max_ticks_per_n_shreds, ProcessShredsStats, Shred, Shredder, + MAX_DATA_SHREDS_PER_FEC_BLOCK, SHRED_PAYLOAD_SIZE, SIZE_OF_CODING_SHRED_HEADERS, + SIZE_OF_DATA_SHRED_PAYLOAD, + }, + solana_perf::test_tx, + solana_sdk::{hash::Hash, signature::Keypair}, + test::Bencher, }; -use solana_perf::test_tx; -use solana_sdk::hash::Hash; -use solana_sdk::signature::Keypair; -use test::Bencher; fn make_test_entry(txs_per_entry: u64) -> Entry { Entry { diff --git a/core/benches/sigverify_stage.rs b/core/benches/sigverify_stage.rs index 1a14c80835270c..e48ab9301c1690 100644 --- a/core/benches/sigverify_stage.rs +++ b/core/benches/sigverify_stage.rs @@ -3,20 +3,24 @@ extern crate solana_core; extern crate test; -use crossbeam_channel::unbounded; -use log::*; -use rand::{thread_rng, Rng}; -use solana_core::sigverify::TransactionSigVerifier; -use solana_core::sigverify_stage::SigVerifyStage; -use solana_perf::packet::to_packets_chunked; -use solana_perf::test_tx::test_tx; -use solana_sdk::hash::Hash; -use solana_sdk::signature::{Keypair, Signer}; -use solana_sdk::system_transaction; -use solana_sdk::timing::duration_as_ms; -use std::sync::mpsc::channel; -use std::time::{Duration, Instant}; -use test::Bencher; +use { + crossbeam_channel::unbounded, + log::*, + rand::{thread_rng, Rng}, + solana_core::{sigverify::TransactionSigVerifier, sigverify_stage::SigVerifyStage}, + solana_perf::{packet::to_packets_chunked, test_tx::test_tx}, + solana_sdk::{ + hash::Hash, + signature::{Keypair, Signer}, + system_transaction, + timing::duration_as_ms, + }, + std::{ + sync::mpsc::channel, + time::{Duration, Instant}, + }, + test::Bencher, +}; #[bench] fn bench_packet_discard(bencher: &mut Bencher) { diff --git a/core/src/accounts_hash_verifier.rs b/core/src/accounts_hash_verifier.rs index decc309b749ac2..ff8647f64dbf62 100644 --- a/core/src/accounts_hash_verifier.rs +++ b/core/src/accounts_hash_verifier.rs @@ -4,30 +4,32 @@ // hash on gossip. Monitor gossip for messages from validators in the `--known-validator`s // set and halt the node if a mismatch is detected. -use rayon::ThreadPool; -use solana_gossip::cluster_info::{ClusterInfo, MAX_SNAPSHOT_HASHES}; -use solana_measure::measure::Measure; -use solana_runtime::{ - accounts_db::{self, AccountsDb}, - accounts_hash::HashStats, - snapshot_config::SnapshotConfig, - snapshot_package::{ - AccountsPackage, AccountsPackageReceiver, PendingSnapshotPackage, SnapshotPackage, - SnapshotType, +use { + rayon::ThreadPool, + solana_gossip::cluster_info::{ClusterInfo, MAX_SNAPSHOT_HASHES}, + solana_measure::measure::Measure, + solana_runtime::{ + accounts_db::{self, AccountsDb}, + accounts_hash::HashStats, + snapshot_config::SnapshotConfig, + snapshot_package::{ + AccountsPackage, AccountsPackageReceiver, PendingSnapshotPackage, SnapshotPackage, + SnapshotType, + }, + sorted_storages::SortedStorages, }, - sorted_storages::SortedStorages, -}; -use solana_sdk::{clock::Slot, hash::Hash, pubkey::Pubkey}; -use std::collections::{HashMap, HashSet}; -use std::{ - path::{Path, PathBuf}, - sync::{ - atomic::{AtomicBool, Ordering}, - mpsc::RecvTimeoutError, - Arc, + solana_sdk::{clock::Slot, hash::Hash, pubkey::Pubkey}, + std::{ + collections::{HashMap, HashSet}, + path::{Path, PathBuf}, + sync::{ + atomic::{AtomicBool, Ordering}, + mpsc::RecvTimeoutError, + Arc, + }, + thread::{self, Builder, JoinHandle}, + time::Duration, }, - thread::{self, Builder, JoinHandle}, - time::Duration, }; pub struct AccountsHashVerifier { @@ -163,8 +165,10 @@ impl AccountsHashVerifier { && accounts_package.slot % fault_injection_rate_slots == 0 { // For testing, publish an invalid hash to gossip. - use rand::{thread_rng, Rng}; - use solana_sdk::hash::extend_and_hash; + use { + rand::{thread_rng, Rng}, + solana_sdk::hash::extend_and_hash, + }; warn!("inserting fault at slot: {}", accounts_package.slot); let rand = thread_rng().gen_range(0, 10); let hash = extend_and_hash(&hash, &[rand]); @@ -277,15 +281,17 @@ impl AccountsHashVerifier { #[cfg(test)] mod tests { - use super::*; - use solana_gossip::{cluster_info::make_accounts_hashes_message, contact_info::ContactInfo}; - use solana_runtime::snapshot_utils::{ArchiveFormat, SnapshotVersion}; - use solana_sdk::{ - genesis_config::ClusterType, - hash::hash, - signature::{Keypair, Signer}, + use { + super::*, + solana_gossip::{cluster_info::make_accounts_hashes_message, contact_info::ContactInfo}, + solana_runtime::snapshot_utils::{ArchiveFormat, SnapshotVersion}, + solana_sdk::{ + genesis_config::ClusterType, + hash::hash, + signature::{Keypair, Signer}, + }, + solana_streamer::socket::SocketAddrSpace, }; - use solana_streamer::socket::SocketAddrSpace; fn new_test_cluster_info(contact_info: ContactInfo) -> ClusterInfo { ClusterInfo::new( @@ -331,8 +337,7 @@ mod tests { #[test] fn test_max_hashes() { solana_logger::setup(); - use std::path::PathBuf; - use tempfile::TempDir; + use {std::path::PathBuf, tempfile::TempDir}; let keypair = Keypair::new(); let contact_info = ContactInfo::new_localhost(&keypair.pubkey(), 0); diff --git a/core/src/ancestor_hashes_service.rs b/core/src/ancestor_hashes_service.rs index 9c980a6af50b95..c824036cd85fed 100644 --- a/core/src/ancestor_hashes_service.rs +++ b/core/src/ancestor_hashes_service.rs @@ -1,38 +1,40 @@ -use crate::{ - cluster_slots::ClusterSlots, - duplicate_repair_status::{DeadSlotAncestorRequestStatus, DuplicateAncestorDecision}, - outstanding_requests::OutstandingRequests, - repair_response::{self}, - repair_service::{DuplicateSlotsResetSender, RepairInfo, RepairStatsGroup}, - replay_stage::DUPLICATE_THRESHOLD, - result::{Error, Result}, - serve_repair::{AncestorHashesRepairType, ServeRepair}, -}; -use crossbeam_channel::{unbounded, Receiver, Sender}; -use dashmap::{mapref::entry::Entry::Occupied, DashMap}; -use solana_ledger::{blockstore::Blockstore, shred::SIZE_OF_NONCE}; -use solana_measure::measure::Measure; -use solana_perf::{ - packet::{limited_deserialize, Packet, Packets}, - recycler::Recycler, -}; -use solana_runtime::bank::Bank; -use solana_sdk::{ - clock::{Slot, SLOT_MS}, - pubkey::Pubkey, - timing::timestamp, -}; -use solana_streamer::streamer::{self, PacketReceiver}; -use std::{ - collections::HashSet, - net::UdpSocket, - sync::{ - atomic::{AtomicBool, Ordering}, - mpsc::channel, - {Arc, RwLock}, +use { + crate::{ + cluster_slots::ClusterSlots, + duplicate_repair_status::{DeadSlotAncestorRequestStatus, DuplicateAncestorDecision}, + outstanding_requests::OutstandingRequests, + repair_response::{self}, + repair_service::{DuplicateSlotsResetSender, RepairInfo, RepairStatsGroup}, + replay_stage::DUPLICATE_THRESHOLD, + result::{Error, Result}, + serve_repair::{AncestorHashesRepairType, ServeRepair}, + }, + crossbeam_channel::{unbounded, Receiver, Sender}, + dashmap::{mapref::entry::Entry::Occupied, DashMap}, + solana_ledger::{blockstore::Blockstore, shred::SIZE_OF_NONCE}, + solana_measure::measure::Measure, + solana_perf::{ + packet::{limited_deserialize, Packet, Packets}, + recycler::Recycler, + }, + solana_runtime::bank::Bank, + solana_sdk::{ + clock::{Slot, SLOT_MS}, + pubkey::Pubkey, + timing::timestamp, + }, + solana_streamer::streamer::{self, PacketReceiver}, + std::{ + collections::HashSet, + net::UdpSocket, + sync::{ + atomic::{AtomicBool, Ordering}, + mpsc::channel, + Arc, RwLock, + }, + thread::{self, sleep, Builder, JoinHandle}, + time::{Duration, Instant}, }, - thread::{self, sleep, Builder, JoinHandle}, - time::{Duration, Instant}, }; #[derive(Debug, PartialEq)] @@ -681,27 +683,29 @@ impl AncestorHashesService { #[cfg(test)] mod test { - use super::*; - use crate::{ - cluster_slot_state_verifier::DuplicateSlotsToRepair, - repair_service::DuplicateSlotsResetReceiver, - replay_stage::{ - tests::{replay_blockstore_components, ReplayBlockstoreComponents}, - ReplayStage, + use { + super::*, + crate::{ + cluster_slot_state_verifier::DuplicateSlotsToRepair, + repair_service::DuplicateSlotsResetReceiver, + replay_stage::{ + tests::{replay_blockstore_components, ReplayBlockstoreComponents}, + ReplayStage, + }, + serve_repair::MAX_ANCESTOR_RESPONSES, + vote_simulator::VoteSimulator, }, - serve_repair::MAX_ANCESTOR_RESPONSES, - vote_simulator::VoteSimulator, - }; - use solana_gossip::{ - cluster_info::{ClusterInfo, Node}, - contact_info::ContactInfo, + solana_gossip::{ + cluster_info::{ClusterInfo, Node}, + contact_info::ContactInfo, + }, + solana_ledger::{blockstore::make_many_slot_entries, get_tmp_ledger_path}, + solana_runtime::{accounts_background_service::AbsRequestSender, bank_forks::BankForks}, + solana_sdk::{hash::Hash, signature::Keypair}, + solana_streamer::socket::SocketAddrSpace, + std::{collections::HashMap, sync::mpsc::channel}, + trees::tr, }; - use solana_ledger::{blockstore::make_many_slot_entries, get_tmp_ledger_path}; - use solana_runtime::{accounts_background_service::AbsRequestSender, bank_forks::BankForks}; - use solana_sdk::{hash::Hash, signature::Keypair}; - use solana_streamer::socket::SocketAddrSpace; - use std::{collections::HashMap, sync::mpsc::channel}; - use trees::tr; #[test] pub fn test_ancestor_hashes_service_process_replay_updates() { diff --git a/core/src/banking_stage.rs b/core/src/banking_stage.rs index b4460edce3f230..d1c7e5eb086eec 100644 --- a/core/src/banking_stage.rs +++ b/core/src/banking_stage.rs @@ -1,63 +1,66 @@ //! The `banking_stage` processes Transaction messages. It is intended to be used //! to contruct a software pipeline. The stage uses all available CPU cores and //! can do its processing in parallel with signature verification on the GPU. -use crate::{packet_hasher::PacketHasher, qos_service::QosService}; -use crossbeam_channel::{Receiver as CrossbeamReceiver, RecvTimeoutError}; -use itertools::Itertools; -use lru::LruCache; -use retain_mut::RetainMut; -use solana_entry::entry::hash_transactions; -use solana_gossip::{cluster_info::ClusterInfo, contact_info::ContactInfo}; -use solana_ledger::blockstore_processor::TransactionStatusSender; -use solana_measure::measure::Measure; -use solana_metrics::{inc_new_counter_debug, inc_new_counter_info}; -use solana_perf::{ - cuda_runtime::PinnedVec, - data_budget::DataBudget, - packet::{limited_deserialize, Packet, Packets, PACKETS_PER_BATCH}, - perf_libs, -}; -use solana_poh::poh_recorder::{BankStart, PohRecorder, PohRecorderError, TransactionRecorder}; -use solana_runtime::{ - accounts_db::ErrorCounters, - bank::{ - Bank, ExecuteTimings, TransactionBalancesSet, TransactionCheckResult, - TransactionExecutionResult, +use { + crate::{packet_hasher::PacketHasher, qos_service::QosService}, + crossbeam_channel::{Receiver as CrossbeamReceiver, RecvTimeoutError}, + itertools::Itertools, + lru::LruCache, + retain_mut::RetainMut, + solana_entry::entry::hash_transactions, + solana_gossip::{cluster_info::ClusterInfo, contact_info::ContactInfo}, + solana_ledger::blockstore_processor::TransactionStatusSender, + solana_measure::measure::Measure, + solana_metrics::{inc_new_counter_debug, inc_new_counter_info}, + solana_perf::{ + cuda_runtime::PinnedVec, + data_budget::DataBudget, + packet::{limited_deserialize, Packet, Packets, PACKETS_PER_BATCH}, + perf_libs, }, - bank_utils, - cost_model::CostModel, - transaction_batch::TransactionBatch, - vote_sender_types::ReplayVoteSender, -}; -use solana_sdk::{ - clock::{ - Slot, DEFAULT_TICKS_PER_SLOT, MAX_PROCESSING_AGE, MAX_TRANSACTION_FORWARDING_DELAY, - MAX_TRANSACTION_FORWARDING_DELAY_GPU, + solana_poh::poh_recorder::{BankStart, PohRecorder, PohRecorderError, TransactionRecorder}, + solana_runtime::{ + accounts_db::ErrorCounters, + bank::{ + Bank, ExecuteTimings, TransactionBalancesSet, TransactionCheckResult, + TransactionExecutionResult, + }, + bank_utils, + cost_model::CostModel, + transaction_batch::TransactionBatch, + vote_sender_types::ReplayVoteSender, + }, + solana_sdk::{ + clock::{ + Slot, DEFAULT_TICKS_PER_SLOT, MAX_PROCESSING_AGE, MAX_TRANSACTION_FORWARDING_DELAY, + MAX_TRANSACTION_FORWARDING_DELAY_GPU, + }, + feature_set, + message::Message, + pubkey::Pubkey, + short_vec::decode_shortu16_len, + signature::Signature, + timing::{duration_as_ms, timestamp, AtomicInterval}, + transaction::{self, SanitizedTransaction, TransactionError, VersionedTransaction}, + }, + solana_streamer::sendmmsg::{batch_send, SendPktsError}, + solana_transaction_status::token_balances::{ + collect_token_balances, TransactionTokenBalancesSet, + }, + std::{ + cmp, + collections::{HashMap, VecDeque}, + env, + mem::size_of, + net::{SocketAddr, UdpSocket}, + ops::DerefMut, + sync::{ + atomic::{AtomicU64, AtomicUsize, Ordering}, + Arc, Mutex, RwLock, + }, + thread::{self, Builder, JoinHandle}, + time::{Duration, Instant}, }, - feature_set, - message::Message, - pubkey::Pubkey, - short_vec::decode_shortu16_len, - signature::Signature, - timing::{duration_as_ms, timestamp, AtomicInterval}, - transaction::{self, SanitizedTransaction, TransactionError, VersionedTransaction}, -}; -use solana_streamer::sendmmsg::{batch_send, SendPktsError}; -use solana_transaction_status::token_balances::{ - collect_token_balances, TransactionTokenBalancesSet, -}; -use std::{ - cmp, - collections::{HashMap, VecDeque}, - env, - mem::size_of, - net::{SocketAddr, UdpSocket}, - ops::DerefMut, - sync::atomic::{AtomicU64, AtomicUsize, Ordering}, - sync::{Arc, Mutex, RwLock}, - thread::{self, Builder, JoinHandle}, - time::Duration, - time::Instant, }; /// (packets, valid_indexes, forwarded) @@ -1545,43 +1548,45 @@ where #[cfg(test)] mod tests { - use super::*; - use crossbeam_channel::unbounded; - use itertools::Itertools; - use solana_entry::entry::{next_entry, Entry, EntrySlice}; - use solana_gossip::{cluster_info::Node, contact_info::ContactInfo}; - use solana_ledger::{ - blockstore::{entries_to_test_shreds, Blockstore}, - genesis_utils::{create_genesis_config, GenesisConfigInfo}, - get_tmp_ledger_path, - leader_schedule_cache::LeaderScheduleCache, - }; - use solana_perf::packet::to_packets_chunked; - use solana_poh::{ - poh_recorder::{create_test_recorder, Record, WorkingBankEntry}, - poh_service::PohService, - }; - use solana_rpc::transaction_status_service::TransactionStatusService; - use solana_sdk::{ - hash::Hash, - instruction::InstructionError, - poh_config::PohConfig, - signature::{Keypair, Signer}, - system_instruction::SystemError, - system_transaction, - transaction::{Transaction, TransactionError}, - }; - use solana_streamer::socket::SocketAddrSpace; - use solana_transaction_status::TransactionWithStatusMeta; - use solana_vote_program::vote_transaction; - use std::{ - net::SocketAddr, - path::Path, - sync::{ - atomic::{AtomicBool, Ordering}, - mpsc::Receiver, + use { + super::*, + crossbeam_channel::unbounded, + itertools::Itertools, + solana_entry::entry::{next_entry, Entry, EntrySlice}, + solana_gossip::{cluster_info::Node, contact_info::ContactInfo}, + solana_ledger::{ + blockstore::{entries_to_test_shreds, Blockstore}, + genesis_utils::{create_genesis_config, GenesisConfigInfo}, + get_tmp_ledger_path, + leader_schedule_cache::LeaderScheduleCache, + }, + solana_perf::packet::to_packets_chunked, + solana_poh::{ + poh_recorder::{create_test_recorder, Record, WorkingBankEntry}, + poh_service::PohService, + }, + solana_rpc::transaction_status_service::TransactionStatusService, + solana_sdk::{ + hash::Hash, + instruction::InstructionError, + poh_config::PohConfig, + signature::{Keypair, Signer}, + system_instruction::SystemError, + system_transaction, + transaction::{Transaction, TransactionError}, + }, + solana_streamer::socket::SocketAddrSpace, + solana_transaction_status::TransactionWithStatusMeta, + solana_vote_program::vote_transaction, + std::{ + net::SocketAddr, + path::Path, + sync::{ + atomic::{AtomicBool, Ordering}, + mpsc::Receiver, + }, + thread::sleep, }, - thread::sleep, }; fn new_test_cluster_info(contact_info: ContactInfo) -> ClusterInfo { diff --git a/core/src/broadcast_stage.rs b/core/src/broadcast_stage.rs index 9db03d8f0a8355..388f3e6168acc0 100644 --- a/core/src/broadcast_stage.rs +++ b/core/src/broadcast_stage.rs @@ -24,8 +24,10 @@ use { solana_poh::poh_recorder::WorkingBankEntry, solana_runtime::{bank::Bank, bank_forks::BankForks}, solana_sdk::{ + clock::Slot, + pubkey::Pubkey, + signature::Keypair, timing::{timestamp, AtomicInterval}, - {clock::Slot, pubkey::Pubkey, signature::Keypair}, }, solana_streamer::{ sendmmsg::{batch_send, SendPktsError}, @@ -452,24 +454,28 @@ pub fn broadcast_shreds( #[cfg(test)] pub mod test { - use super::*; - use crossbeam_channel::unbounded; - use solana_entry::entry::create_ticks; - use solana_gossip::cluster_info::{ClusterInfo, Node}; - use solana_ledger::{ - blockstore::{make_slot_entries, Blockstore}, - genesis_utils::{create_genesis_config, GenesisConfigInfo}, - get_tmp_ledger_path, - shred::{max_ticks_per_n_shreds, ProcessShredsStats, Shredder}, - }; - use solana_runtime::bank::Bank; - use solana_sdk::{ - hash::Hash, - pubkey::Pubkey, - signature::{Keypair, Signer}, - }; - use std::{ - path::Path, sync::atomic::AtomicBool, sync::mpsc::channel, sync::Arc, thread::sleep, + use { + super::*, + crossbeam_channel::unbounded, + solana_entry::entry::create_ticks, + solana_gossip::cluster_info::{ClusterInfo, Node}, + solana_ledger::{ + blockstore::{make_slot_entries, Blockstore}, + genesis_utils::{create_genesis_config, GenesisConfigInfo}, + get_tmp_ledger_path, + shred::{max_ticks_per_n_shreds, ProcessShredsStats, Shredder}, + }, + solana_runtime::bank::Bank, + solana_sdk::{ + hash::Hash, + pubkey::Pubkey, + signature::{Keypair, Signer}, + }, + std::{ + path::Path, + sync::{atomic::AtomicBool, mpsc::channel, Arc}, + thread::sleep, + }, }; #[allow(clippy::implicit_hasher)] diff --git a/core/src/broadcast_stage/broadcast_fake_shreds_run.rs b/core/src/broadcast_stage/broadcast_fake_shreds_run.rs index 07dfb809c72dbb..f430da9b0fada8 100644 --- a/core/src/broadcast_stage/broadcast_fake_shreds_run.rs +++ b/core/src/broadcast_stage/broadcast_fake_shreds_run.rs @@ -1,8 +1,9 @@ -use super::*; -use solana_entry::entry::Entry; -use solana_ledger::shred::Shredder; -use solana_sdk::hash::Hash; -use solana_sdk::signature::Keypair; +use { + super::*, + solana_entry::entry::Entry, + solana_ledger::shred::Shredder, + solana_sdk::{hash::Hash, signature::Keypair}, +}; #[derive(Clone)] pub(super) struct BroadcastFakeShredsRun { @@ -139,10 +140,12 @@ impl BroadcastRun for BroadcastFakeShredsRun { #[cfg(test)] mod tests { - use super::*; - use solana_gossip::contact_info::ContactInfo; - use solana_streamer::socket::SocketAddrSpace; - use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use { + super::*, + solana_gossip::contact_info::ContactInfo, + solana_streamer::socket::SocketAddrSpace, + std::net::{IpAddr, Ipv4Addr, SocketAddr}, + }; #[test] fn test_tvu_peers_ordering() { diff --git a/core/src/broadcast_stage/broadcast_utils.rs b/core/src/broadcast_stage/broadcast_utils.rs index 001ee7f621c5d0..0e76de935b2b49 100644 --- a/core/src/broadcast_stage/broadcast_utils.rs +++ b/core/src/broadcast_stage/broadcast_utils.rs @@ -1,13 +1,14 @@ -use crate::result::Result; -use solana_entry::entry::Entry; -use solana_ledger::shred::Shred; -use solana_poh::poh_recorder::WorkingBankEntry; -use solana_runtime::bank::Bank; -use solana_sdk::clock::Slot; -use std::{ - sync::mpsc::Receiver, - sync::Arc, - time::{Duration, Instant}, +use { + crate::result::Result, + solana_entry::entry::Entry, + solana_ledger::shred::Shred, + solana_poh::poh_recorder::WorkingBankEntry, + solana_runtime::bank::Bank, + solana_sdk::clock::Slot, + std::{ + sync::{mpsc::Receiver, Arc}, + time::{Duration, Instant}, + }, }; pub(super) struct ReceiveResults { @@ -80,13 +81,15 @@ pub(super) fn recv_slot_entries(receiver: &Receiver) -> Result #[cfg(test)] mod tests { - use super::*; - use solana_ledger::genesis_utils::{create_genesis_config, GenesisConfigInfo}; - use solana_sdk::genesis_config::GenesisConfig; - use solana_sdk::pubkey::Pubkey; - use solana_sdk::system_transaction; - use solana_sdk::transaction::Transaction; - use std::sync::mpsc::channel; + use { + super::*, + solana_ledger::genesis_utils::{create_genesis_config, GenesisConfigInfo}, + solana_sdk::{ + genesis_config::GenesisConfig, pubkey::Pubkey, system_transaction, + transaction::Transaction, + }, + std::sync::mpsc::channel, + }; fn setup_test() -> (GenesisConfig, Arc, Transaction) { let GenesisConfigInfo { diff --git a/core/src/broadcast_stage/standard_broadcast_run.rs b/core/src/broadcast_stage/standard_broadcast_run.rs index 32bc1b3610711d..7a0dbdfa560f80 100644 --- a/core/src/broadcast_stage/standard_broadcast_run.rs +++ b/core/src/broadcast_stage/standard_broadcast_run.rs @@ -508,22 +508,22 @@ impl BroadcastRun for StandardBroadcastRun { #[cfg(test)] mod test { - use super::*; - use solana_entry::entry::create_ticks; - use solana_gossip::cluster_info::{ClusterInfo, Node}; - use solana_ledger::genesis_utils::create_genesis_config; - use solana_ledger::{ - blockstore::Blockstore, get_tmp_ledger_path, shred::max_ticks_per_n_shreds, + use { + super::*, + solana_entry::entry::create_ticks, + solana_gossip::cluster_info::{ClusterInfo, Node}, + solana_ledger::{ + blockstore::Blockstore, genesis_utils::create_genesis_config, get_tmp_ledger_path, + shred::max_ticks_per_n_shreds, + }, + solana_runtime::bank::Bank, + solana_sdk::{ + genesis_config::GenesisConfig, + signature::{Keypair, Signer}, + }, + solana_streamer::socket::SocketAddrSpace, + std::{ops::Deref, sync::Arc, time::Duration}, }; - use solana_runtime::bank::Bank; - use solana_sdk::{ - genesis_config::GenesisConfig, - signature::{Keypair, Signer}, - }; - use solana_streamer::socket::SocketAddrSpace; - use std::ops::Deref; - use std::sync::Arc; - use std::time::Duration; #[allow(clippy::type_complexity)] fn setup( diff --git a/core/src/cluster_info_vote_listener.rs b/core/src/cluster_info_vote_listener.rs index c528c399517147..d6c20973d40aba 100644 --- a/core/src/cluster_info_vote_listener.rs +++ b/core/src/cluster_info_vote_listener.rs @@ -1,56 +1,59 @@ -use crate::{ - optimistic_confirmation_verifier::OptimisticConfirmationVerifier, - replay_stage::DUPLICATE_THRESHOLD, - result::{Error, Result}, - sigverify, - verified_vote_packets::{ - ValidatorGossipVotesIterator, VerifiedVoteMetadata, VerifiedVotePackets, +use { + crate::{ + optimistic_confirmation_verifier::OptimisticConfirmationVerifier, + replay_stage::DUPLICATE_THRESHOLD, + result::{Error, Result}, + sigverify, + verified_vote_packets::{ + ValidatorGossipVotesIterator, VerifiedVoteMetadata, VerifiedVotePackets, + }, + vote_stake_tracker::VoteStakeTracker, }, - vote_stake_tracker::VoteStakeTracker, -}; -use crossbeam_channel::{ - unbounded, Receiver as CrossbeamReceiver, RecvTimeoutError, Select, Sender as CrossbeamSender, -}; -use itertools::izip; -use log::*; -use solana_gossip::{ - cluster_info::{ClusterInfo, GOSSIP_SLEEP_MILLIS}, - crds::Cursor, -}; -use solana_ledger::blockstore::Blockstore; -use solana_measure::measure::Measure; -use solana_metrics::inc_new_counter_debug; -use solana_perf::packet::{self, Packets}; -use solana_poh::poh_recorder::PohRecorder; -use solana_rpc::{ - optimistically_confirmed_bank_tracker::{BankNotification, BankNotificationSender}, - rpc_subscriptions::RpcSubscriptions, -}; -use solana_runtime::{ - bank::Bank, - bank_forks::BankForks, - commitment::VOTE_THRESHOLD_SIZE, - epoch_stakes::{EpochAuthorizedVoters, EpochStakes}, - vote_sender_types::{ReplayVoteReceiver, ReplayedVote}, -}; -use solana_sdk::{ - clock::{Epoch, Slot, DEFAULT_MS_PER_SLOT, DEFAULT_TICKS_PER_SLOT}, - epoch_schedule::EpochSchedule, - hash::Hash, - pubkey::Pubkey, - signature::Signature, - slot_hashes, - transaction::Transaction, -}; -use solana_vote_program::{self, vote_state::Vote, vote_transaction}; -use std::{ - collections::{HashMap, HashSet}, - sync::{ - atomic::{AtomicBool, Ordering}, - {Arc, Mutex, RwLock}, + crossbeam_channel::{ + unbounded, Receiver as CrossbeamReceiver, RecvTimeoutError, Select, + Sender as CrossbeamSender, + }, + itertools::izip, + log::*, + solana_gossip::{ + cluster_info::{ClusterInfo, GOSSIP_SLEEP_MILLIS}, + crds::Cursor, + }, + solana_ledger::blockstore::Blockstore, + solana_measure::measure::Measure, + solana_metrics::inc_new_counter_debug, + solana_perf::packet::{self, Packets}, + solana_poh::poh_recorder::PohRecorder, + solana_rpc::{ + optimistically_confirmed_bank_tracker::{BankNotification, BankNotificationSender}, + rpc_subscriptions::RpcSubscriptions, + }, + solana_runtime::{ + bank::Bank, + bank_forks::BankForks, + commitment::VOTE_THRESHOLD_SIZE, + epoch_stakes::{EpochAuthorizedVoters, EpochStakes}, + vote_sender_types::{ReplayVoteReceiver, ReplayedVote}, + }, + solana_sdk::{ + clock::{Epoch, Slot, DEFAULT_MS_PER_SLOT, DEFAULT_TICKS_PER_SLOT}, + epoch_schedule::EpochSchedule, + hash::Hash, + pubkey::Pubkey, + signature::Signature, + slot_hashes, + transaction::Transaction, + }, + solana_vote_program::{self, vote_state::Vote, vote_transaction}, + std::{ + collections::{HashMap, HashSet}, + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, Mutex, RwLock, + }, + thread::{self, sleep, Builder, JoinHandle}, + time::{Duration, Instant}, }, - thread::{self, sleep, Builder, JoinHandle}, - time::{Duration, Instant}, }; // Map from a vote account to the authorized voter for an epoch @@ -939,23 +942,26 @@ impl ClusterInfoVoteListener { #[cfg(test)] mod tests { - use super::*; - use solana_perf::packet; - use solana_rpc::optimistically_confirmed_bank_tracker::OptimisticallyConfirmedBank; - use solana_runtime::{ - bank::Bank, - commitment::BlockCommitmentCache, - genesis_utils::{self, create_genesis_config, GenesisConfigInfo, ValidatorVoteKeypairs}, - vote_sender_types::ReplayVoteSender, - }; - use solana_sdk::{ - hash::Hash, - pubkey::Pubkey, - signature::{Keypair, Signature, Signer}, + use { + super::*, + solana_perf::packet, + solana_rpc::optimistically_confirmed_bank_tracker::OptimisticallyConfirmedBank, + solana_runtime::{ + bank::Bank, + commitment::BlockCommitmentCache, + genesis_utils::{ + self, create_genesis_config, GenesisConfigInfo, ValidatorVoteKeypairs, + }, + vote_sender_types::ReplayVoteSender, + }, + solana_sdk::{ + hash::Hash, + pubkey::Pubkey, + signature::{Keypair, Signature, Signer}, + }, + solana_vote_program::vote_state::Vote, + std::{collections::BTreeSet, sync::Arc}, }; - use solana_vote_program::vote_state::Vote; - use std::collections::BTreeSet; - use std::sync::Arc; #[test] fn test_max_vote_tx_fits() { diff --git a/core/src/cluster_slot_state_verifier.rs b/core/src/cluster_slot_state_verifier.rs index b29a9608ab1aca..a182cbcf278b16 100644 --- a/core/src/cluster_slot_state_verifier.rs +++ b/core/src/cluster_slot_state_verifier.rs @@ -1,11 +1,13 @@ -use crate::{ - ancestor_hashes_service::{AncestorHashesReplayUpdate, AncestorHashesReplayUpdateSender}, - fork_choice::ForkChoice, - heaviest_subtree_fork_choice::HeaviestSubtreeForkChoice, +use { + crate::{ + ancestor_hashes_service::{AncestorHashesReplayUpdate, AncestorHashesReplayUpdateSender}, + fork_choice::ForkChoice, + heaviest_subtree_fork_choice::HeaviestSubtreeForkChoice, + }, + solana_ledger::blockstore::Blockstore, + solana_sdk::{clock::Slot, hash::Hash}, + std::collections::{BTreeMap, BTreeSet, HashMap}, }; -use solana_ledger::blockstore::Blockstore; -use solana_sdk::{clock::Slot, hash::Hash}; -use std::collections::{BTreeMap, BTreeSet, HashMap}; pub(crate) type DuplicateSlotsTracker = BTreeSet; pub(crate) type DuplicateSlotsToRepair = HashMap; @@ -805,15 +807,17 @@ pub(crate) fn check_slot_agrees_with_cluster( #[cfg(test)] mod test { - use super::*; - use crate::{progress_map::ProgressMap, replay_stage::tests::setup_forks_from_tree}; - use crossbeam_channel::unbounded; - use solana_runtime::bank_forks::BankForks; - use std::{ - collections::{HashMap, HashSet}, - sync::{Arc, RwLock}, + use { + super::*, + crate::{progress_map::ProgressMap, replay_stage::tests::setup_forks_from_tree}, + crossbeam_channel::unbounded, + solana_runtime::bank_forks::BankForks, + std::{ + collections::{HashMap, HashSet}, + sync::{Arc, RwLock}, + }, + trees::tr, }; - use trees::tr; macro_rules! state_update_tests { ($($name:ident: $value:expr,)*) => { diff --git a/core/src/cluster_slots.rs b/core/src/cluster_slots.rs index 92b4cc2527e765..6f43a2ac8d2092 100644 --- a/core/src/cluster_slots.rs +++ b/core/src/cluster_slots.rs @@ -218,8 +218,7 @@ impl ClusterSlots { #[cfg(test)] mod tests { - use super::*; - use solana_runtime::epoch_stakes::NodeVoteAccounts; + use {super::*, solana_runtime::epoch_stakes::NodeVoteAccounts}; #[test] fn test_default() { diff --git a/core/src/cluster_slots_service.rs b/core/src/cluster_slots_service.rs index 251ac39999d36b..119f6081cff0e4 100644 --- a/core/src/cluster_slots_service.rs +++ b/core/src/cluster_slots_service.rs @@ -1,17 +1,19 @@ -use crate::cluster_slots::ClusterSlots; -use crossbeam_channel::{Receiver, RecvTimeoutError, Sender}; -use solana_gossip::cluster_info::ClusterInfo; -use solana_ledger::blockstore::Blockstore; -use solana_measure::measure::Measure; -use solana_runtime::bank_forks::BankForks; -use solana_sdk::clock::Slot; -use std::{ - sync::{ - atomic::{AtomicBool, Ordering}, - {Arc, RwLock}, +use { + crate::cluster_slots::ClusterSlots, + crossbeam_channel::{Receiver, RecvTimeoutError, Sender}, + solana_gossip::cluster_info::ClusterInfo, + solana_ledger::blockstore::Blockstore, + solana_measure::measure::Measure, + solana_runtime::bank_forks::BankForks, + solana_sdk::clock::Slot, + std::{ + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, RwLock, + }, + thread::{self, Builder, JoinHandle}, + time::{Duration, Instant}, }, - thread::{self, Builder, JoinHandle}, - time::{Duration, Instant}, }; pub type ClusterSlotsUpdateReceiver = Receiver>; diff --git a/core/src/commitment_service.rs b/core/src/commitment_service.rs index f5225c34ea4c4d..f918065d024724 100644 --- a/core/src/commitment_service.rs +++ b/core/src/commitment_service.rs @@ -1,21 +1,25 @@ -use crate::consensus::Stake; -use solana_measure::measure::Measure; -use solana_metrics::datapoint_info; -use solana_rpc::rpc_subscriptions::RpcSubscriptions; -use solana_runtime::{ - bank::Bank, - commitment::{BlockCommitment, BlockCommitmentCache, CommitmentSlots, VOTE_THRESHOLD_SIZE}, -}; -use solana_sdk::clock::Slot; -use solana_vote_program::vote_state::VoteState; -use std::{ - cmp::max, - collections::HashMap, - sync::atomic::{AtomicBool, Ordering}, - sync::mpsc::{channel, Receiver, RecvTimeoutError, Sender}, - sync::{Arc, RwLock}, - thread::{self, Builder, JoinHandle}, - time::Duration, +use { + crate::consensus::Stake, + solana_measure::measure::Measure, + solana_metrics::datapoint_info, + solana_rpc::rpc_subscriptions::RpcSubscriptions, + solana_runtime::{ + bank::Bank, + commitment::{BlockCommitment, BlockCommitmentCache, CommitmentSlots, VOTE_THRESHOLD_SIZE}, + }, + solana_sdk::clock::Slot, + solana_vote_program::vote_state::VoteState, + std::{ + cmp::max, + collections::HashMap, + sync::{ + atomic::{AtomicBool, Ordering}, + mpsc::{channel, Receiver, RecvTimeoutError, Sender}, + Arc, RwLock, + }, + thread::{self, Builder, JoinHandle}, + time::Duration, + }, }; pub struct CommitmentAggregationData { @@ -247,18 +251,20 @@ impl AggregateCommitmentService { #[cfg(test)] mod tests { - use super::*; - use solana_ledger::genesis_utils::{create_genesis_config, GenesisConfigInfo}; - use solana_runtime::{ - accounts_background_service::AbsRequestSender, - bank_forks::BankForks, - genesis_utils::{create_genesis_config_with_vote_accounts, ValidatorVoteKeypairs}, - }; - use solana_sdk::{account::Account, pubkey::Pubkey, signature::Signer}; - use solana_stake_program::stake_state; - use solana_vote_program::{ - vote_state::{self, VoteStateVersions}, - vote_transaction, + use { + super::*, + solana_ledger::genesis_utils::{create_genesis_config, GenesisConfigInfo}, + solana_runtime::{ + accounts_background_service::AbsRequestSender, + bank_forks::BankForks, + genesis_utils::{create_genesis_config_with_vote_accounts, ValidatorVoteKeypairs}, + }, + solana_sdk::{account::Account, pubkey::Pubkey, signature::Signer}, + solana_stake_program::stake_state, + solana_vote_program::{ + vote_state::{self, VoteStateVersions}, + vote_transaction, + }, }; #[test] diff --git a/core/src/completed_data_sets_service.rs b/core/src/completed_data_sets_service.rs index b1435b4403bb1f..08b561b8aca12f 100644 --- a/core/src/completed_data_sets_service.rs +++ b/core/src/completed_data_sets_service.rs @@ -1,15 +1,17 @@ -use crossbeam_channel::{Receiver, RecvTimeoutError, Sender}; -use solana_entry::entry::Entry; -use solana_ledger::blockstore::{Blockstore, CompletedDataSetInfo}; -use solana_rpc::{max_slots::MaxSlots, rpc_subscriptions::RpcSubscriptions}; -use solana_sdk::signature::Signature; -use std::{ - sync::{ - atomic::{AtomicBool, Ordering}, - Arc, +use { + crossbeam_channel::{Receiver, RecvTimeoutError, Sender}, + solana_entry::entry::Entry, + solana_ledger::blockstore::{Blockstore, CompletedDataSetInfo}, + solana_rpc::{max_slots::MaxSlots, rpc_subscriptions::RpcSubscriptions}, + solana_sdk::signature::Signature, + std::{ + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, + }, + thread::{self, Builder, JoinHandle}, + time::Duration, }, - thread::{self, Builder, JoinHandle}, - time::Duration, }; pub type CompletedDataSetsReceiver = Receiver>; @@ -100,10 +102,14 @@ impl CompletedDataSetsService { #[cfg(test)] pub mod test { - use super::*; - use solana_sdk::hash::Hash; - use solana_sdk::signature::{Keypair, Signer}; - use solana_sdk::transaction::Transaction; + use { + super::*, + solana_sdk::{ + hash::Hash, + signature::{Keypair, Signer}, + transaction::Transaction, + }, + }; #[test] fn test_zero_signatures() { diff --git a/core/src/cost_update_service.rs b/core/src/cost_update_service.rs index 4f852b3d97a409..0ebee0c09c45ee 100644 --- a/core/src/cost_update_service.rs +++ b/core/src/cost_update_service.rs @@ -3,18 +3,23 @@ //! packing transactions into block; it also triggers persisting cost //! table to blockstore. -use solana_ledger::blockstore::Blockstore; -use solana_measure::measure::Measure; -use solana_runtime::{bank::Bank, bank::ExecuteTimings, cost_model::CostModel}; -use solana_sdk::timing::timestamp; -use std::{ - sync::{ - atomic::{AtomicBool, Ordering}, - mpsc::Receiver, - Arc, RwLock, +use { + solana_ledger::blockstore::Blockstore, + solana_measure::measure::Measure, + solana_runtime::{ + bank::{Bank, ExecuteTimings}, + cost_model::CostModel, + }, + solana_sdk::timing::timestamp, + std::{ + sync::{ + atomic::{AtomicBool, Ordering}, + mpsc::Receiver, + Arc, RwLock, + }, + thread::{self, Builder, JoinHandle}, + time::Duration, }, - thread::{self, Builder, JoinHandle}, - time::Duration, }; #[derive(Default)] @@ -203,9 +208,7 @@ impl CostUpdateService { #[cfg(test)] mod tests { - use super::*; - use solana_program_runtime::timings::ProgramTiming; - use solana_sdk::pubkey::Pubkey; + use {super::*, solana_program_runtime::timings::ProgramTiming, solana_sdk::pubkey::Pubkey}; #[test] fn test_update_cost_model_with_empty_execute_timings() { diff --git a/core/src/drop_bank_service.rs b/core/src/drop_bank_service.rs index a53f6f152019e3..8359bf1e6314ad 100644 --- a/core/src/drop_bank_service.rs +++ b/core/src/drop_bank_service.rs @@ -1,8 +1,10 @@ -use solana_measure::measure::Measure; -use solana_runtime::bank::Bank; -use std::{ - sync::{mpsc::Receiver, Arc}, - thread::{self, Builder, JoinHandle}, +use { + solana_measure::measure::Measure, + solana_runtime::bank::Bank, + std::{ + sync::{mpsc::Receiver, Arc}, + thread::{self, Builder, JoinHandle}, + }, }; pub struct DropBankService { diff --git a/core/src/duplicate_repair_status.rs b/core/src/duplicate_repair_status.rs index c0894333efa78a..781b647b73eb37 100644 --- a/core/src/duplicate_repair_status.rs +++ b/core/src/duplicate_repair_status.rs @@ -1,6 +1,8 @@ -use solana_ledger::blockstore::Blockstore; -use solana_sdk::{clock::Slot, hash::Hash, pubkey::Pubkey, timing::timestamp}; -use std::{collections::HashMap, net::SocketAddr}; +use { + solana_ledger::blockstore::Blockstore, + solana_sdk::{clock::Slot, hash::Hash, pubkey::Pubkey, timing::timestamp}, + std::{collections::HashMap, net::SocketAddr}, +}; // Number of validators to sample for the ancestor repair pub const ANCESTOR_HASH_REPAIR_SAMPLE_SIZE: usize = 21; @@ -350,11 +352,13 @@ impl DeadSlotAncestorRequestStatus { #[cfg(test)] pub mod tests { - use super::*; - use rand::{self, seq::SliceRandom, thread_rng}; - use solana_ledger::get_tmp_ledger_path_auto_delete; - use std::{collections::BTreeMap, net::IpAddr}; - use tempfile::TempDir; + use { + super::*, + rand::{self, seq::SliceRandom, thread_rng}, + solana_ledger::get_tmp_ledger_path_auto_delete, + std::{collections::BTreeMap, net::IpAddr}, + tempfile::TempDir, + }; struct TestSetup { sampled_addresses: Vec, diff --git a/core/src/fetch_stage.rs b/core/src/fetch_stage.rs index b99b569e031f5f..248d3bf65d6181 100644 --- a/core/src/fetch_stage.rs +++ b/core/src/fetch_stage.rs @@ -1,18 +1,25 @@ //! The `fetch_stage` batches input from a UDP socket and sends it to a channel. -use crate::banking_stage::HOLD_TRANSACTIONS_SLOT_OFFSET; -use crate::result::{Error, Result}; -use solana_metrics::{inc_new_counter_debug, inc_new_counter_info}; -use solana_perf::packet::PacketsRecycler; -use solana_perf::recycler::Recycler; -use solana_poh::poh_recorder::PohRecorder; -use solana_sdk::clock::DEFAULT_TICKS_PER_SLOT; -use solana_streamer::streamer::{self, PacketReceiver, PacketSender}; -use std::net::UdpSocket; -use std::sync::atomic::AtomicBool; -use std::sync::mpsc::{channel, RecvTimeoutError}; -use std::sync::{Arc, Mutex}; -use std::thread::{self, Builder, JoinHandle}; +use { + crate::{ + banking_stage::HOLD_TRANSACTIONS_SLOT_OFFSET, + result::{Error, Result}, + }, + solana_metrics::{inc_new_counter_debug, inc_new_counter_info}, + solana_perf::{packet::PacketsRecycler, recycler::Recycler}, + solana_poh::poh_recorder::PohRecorder, + solana_sdk::clock::DEFAULT_TICKS_PER_SLOT, + solana_streamer::streamer::{self, PacketReceiver, PacketSender}, + std::{ + net::UdpSocket, + sync::{ + atomic::AtomicBool, + mpsc::{channel, RecvTimeoutError}, + Arc, Mutex, + }, + thread::{self, Builder, JoinHandle}, + }, +}; pub struct FetchStage { thread_hdls: Vec>, diff --git a/core/src/fork_choice.rs b/core/src/fork_choice.rs index f358be303c0620..ef5e39f3ddc53e 100644 --- a/core/src/fork_choice.rs +++ b/core/src/fork_choice.rs @@ -1,13 +1,15 @@ -use crate::{ - consensus::{SwitchForkDecision, Tower}, - latest_validator_votes_for_frozen_banks::LatestValidatorVotesForFrozenBanks, - progress_map::ProgressMap, - replay_stage::HeaviestForkFailures, -}; -use solana_runtime::{bank::Bank, bank_forks::BankForks}; -use std::{ - collections::{HashMap, HashSet}, - sync::{Arc, RwLock}, +use { + crate::{ + consensus::{SwitchForkDecision, Tower}, + latest_validator_votes_for_frozen_banks::LatestValidatorVotesForFrozenBanks, + progress_map::ProgressMap, + replay_stage::HeaviestForkFailures, + }, + solana_runtime::{bank::Bank, bank_forks::BankForks}, + std::{ + collections::{HashMap, HashSet}, + sync::{Arc, RwLock}, + }, }; pub struct SelectVoteAndResetForkResult { diff --git a/core/src/gen_keys.rs b/core/src/gen_keys.rs index 4f8f4d86d9c155..b037b26596b759 100644 --- a/core/src/gen_keys.rs +++ b/core/src/gen_keys.rs @@ -1,9 +1,11 @@ //! The `gen_keys` module makes lots of keypairs -use rand::{Rng, SeedableRng}; -use rand_chacha::ChaChaRng; -use rayon::prelude::*; -use solana_sdk::signature::Keypair; +use { + rand::{Rng, SeedableRng}, + rand_chacha::ChaChaRng, + rayon::prelude::*, + solana_sdk::signature::Keypair, +}; pub struct GenKeys { generator: ChaChaRng, @@ -39,10 +41,8 @@ impl GenKeys { #[cfg(test)] mod tests { - use super::*; pub use solana_sdk::pubkey::Pubkey; - use solana_sdk::signature::Signer; - use std::collections::HashSet; + use {super::*, solana_sdk::signature::Signer, std::collections::HashSet}; #[test] fn test_new_key_is_deterministic() { diff --git a/core/src/heaviest_subtree_fork_choice.rs b/core/src/heaviest_subtree_fork_choice.rs index ebe048d46db60f..66ecc3c2c65d63 100644 --- a/core/src/heaviest_subtree_fork_choice.rs +++ b/core/src/heaviest_subtree_fork_choice.rs @@ -1,24 +1,26 @@ -use crate::{ - consensus::Tower, fork_choice::ForkChoice, - latest_validator_votes_for_frozen_banks::LatestValidatorVotesForFrozenBanks, - progress_map::ProgressMap, tree_diff::TreeDiff, -}; -use solana_measure::measure::Measure; -use solana_runtime::{bank::Bank, bank_forks::BankForks, epoch_stakes::EpochStakes}; -use solana_sdk::{ - clock::{Epoch, Slot}, - epoch_schedule::EpochSchedule, - hash::Hash, - pubkey::Pubkey, -}; -use std::{ - borrow::Borrow, - collections::{hash_map::Entry, BTreeMap, HashMap, HashSet, VecDeque}, - sync::{Arc, RwLock}, - time::Instant, -}; #[cfg(test)] use trees::{Tree, TreeWalk}; +use { + crate::{ + consensus::Tower, fork_choice::ForkChoice, + latest_validator_votes_for_frozen_banks::LatestValidatorVotesForFrozenBanks, + progress_map::ProgressMap, tree_diff::TreeDiff, + }, + solana_measure::measure::Measure, + solana_runtime::{bank::Bank, bank_forks::BankForks, epoch_stakes::EpochStakes}, + solana_sdk::{ + clock::{Epoch, Slot}, + epoch_schedule::EpochSchedule, + hash::Hash, + pubkey::Pubkey, + }, + std::{ + borrow::Borrow, + collections::{hash_map::Entry, BTreeMap, HashMap, HashSet, VecDeque}, + sync::{Arc, RwLock}, + time::Instant, + }, +}; pub type ForkWeight = u64; pub type SlotHashKey = (Slot, Hash); @@ -1076,12 +1078,14 @@ impl<'a> Iterator for AncestorIterator<'a> { #[cfg(test)] mod test { - use super::*; - use crate::vote_simulator::VoteSimulator; - use solana_runtime::{bank::Bank, bank_utils}; - use solana_sdk::{hash::Hash, slot_history::SlotHistory}; - use std::{collections::HashSet, ops::Range}; - use trees::tr; + use { + super::*, + crate::vote_simulator::VoteSimulator, + solana_runtime::{bank::Bank, bank_utils}, + solana_sdk::{hash::Hash, slot_history::SlotHistory}, + std::{collections::HashSet, ops::Range}, + trees::tr, + }; #[test] fn test_max_by_weight() { diff --git a/core/src/latest_validator_votes_for_frozen_banks.rs b/core/src/latest_validator_votes_for_frozen_banks.rs index efff736f2290ab..039990bf72a235 100644 --- a/core/src/latest_validator_votes_for_frozen_banks.rs +++ b/core/src/latest_validator_votes_for_frozen_banks.rs @@ -1,6 +1,8 @@ -use crate::heaviest_subtree_fork_choice::SlotHashKey; -use solana_sdk::{clock::Slot, hash::Hash, pubkey::Pubkey}; -use std::collections::{hash_map::Entry, HashMap}; +use { + crate::heaviest_subtree_fork_choice::SlotHashKey, + solana_sdk::{clock::Slot, hash::Hash, pubkey::Pubkey}, + std::collections::{hash_map::Entry, HashMap}, +}; #[derive(Default)] pub struct LatestValidatorVotesForFrozenBanks { diff --git a/core/src/ledger_cleanup_service.rs b/core/src/ledger_cleanup_service.rs index 574e1dc7a28fa3..3486a24ad21677 100644 --- a/core/src/ledger_cleanup_service.rs +++ b/core/src/ledger_cleanup_service.rs @@ -1,17 +1,24 @@ //! The `ledger_cleanup_service` drops older ledger data to limit disk space usage -use rand::{thread_rng, Rng}; -use solana_ledger::blockstore::{Blockstore, PurgeType}; -use solana_ledger::blockstore_db::Result as BlockstoreResult; -use solana_measure::measure::Measure; -use solana_sdk::clock::{Slot, DEFAULT_TICKS_PER_SLOT, TICKS_PER_DAY}; -use std::string::ToString; -use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use std::sync::mpsc::{Receiver, RecvTimeoutError}; -use std::sync::Arc; -use std::thread; -use std::thread::{sleep, Builder, JoinHandle}; -use std::time::Duration; +use { + rand::{thread_rng, Rng}, + solana_ledger::{ + blockstore::{Blockstore, PurgeType}, + blockstore_db::Result as BlockstoreResult, + }, + solana_measure::measure::Measure, + solana_sdk::clock::{Slot, DEFAULT_TICKS_PER_SLOT, TICKS_PER_DAY}, + std::{ + string::ToString, + sync::{ + atomic::{AtomicBool, AtomicU64, Ordering}, + mpsc::{Receiver, RecvTimeoutError}, + Arc, + }, + thread::{self, sleep, Builder, JoinHandle}, + time::Duration, + }, +}; // - To try and keep the RocksDB size under 400GB: // Seeing about 1600b/shred, using 2000b/shred for margin, so 200m shreds can be stored in 400gb. @@ -306,10 +313,11 @@ impl LedgerCleanupService { } #[cfg(test)] mod tests { - use super::*; - use solana_ledger::blockstore::make_many_slot_entries; - use solana_ledger::get_tmp_ledger_path; - use std::sync::mpsc::channel; + use { + super::*, + solana_ledger::{blockstore::make_many_slot_entries, get_tmp_ledger_path}, + std::sync::mpsc::channel, + }; #[test] fn test_cleanup1() { diff --git a/core/src/optimistic_confirmation_verifier.rs b/core/src/optimistic_confirmation_verifier.rs index 09215fd5ec5378..52c47a577a215f 100644 --- a/core/src/optimistic_confirmation_verifier.rs +++ b/core/src/optimistic_confirmation_verifier.rs @@ -1,8 +1,10 @@ -use crate::cluster_info_vote_listener::VoteTracker; -use solana_ledger::blockstore::Blockstore; -use solana_runtime::bank::Bank; -use solana_sdk::{clock::Slot, hash::Hash}; -use std::{collections::BTreeSet, time::Instant}; +use { + crate::cluster_info_vote_listener::VoteTracker, + solana_ledger::blockstore::Blockstore, + solana_runtime::bank::Bank, + solana_sdk::{clock::Slot, hash::Hash}, + std::{collections::BTreeSet, time::Instant}, +}; pub struct OptimisticConfirmationVerifier { snapshot_start_slot: Slot, @@ -139,13 +141,11 @@ impl OptimisticConfirmationVerifier { #[cfg(test)] mod test { - use super::*; - use crate::vote_simulator::VoteSimulator; - use solana_ledger::get_tmp_ledger_path; - use solana_runtime::bank::Bank; - use solana_sdk::pubkey::Pubkey; - use std::collections::HashMap; - use trees::tr; + use { + super::*, crate::vote_simulator::VoteSimulator, solana_ledger::get_tmp_ledger_path, + solana_runtime::bank::Bank, solana_sdk::pubkey::Pubkey, std::collections::HashMap, + trees::tr, + }; #[test] fn test_add_new_optimistic_confirmed_slots() { diff --git a/core/src/outstanding_requests.rs b/core/src/outstanding_requests.rs index 7f8a8c109d06ff..5f5dc6a889bdb0 100644 --- a/core/src/outstanding_requests.rs +++ b/core/src/outstanding_requests.rs @@ -1,7 +1,9 @@ -use crate::request_response::RequestResponse; -use lru::LruCache; -use rand::{thread_rng, Rng}; -use solana_ledger::shred::Nonce; +use { + crate::request_response::RequestResponse, + lru::LruCache, + rand::{thread_rng, Rng}, + solana_ledger::shred::Nonce, +}; pub const DEFAULT_REQUEST_EXPIRATION_MS: u64 = 60_000; @@ -82,10 +84,10 @@ pub struct RequestStatus { #[cfg(test)] pub(crate) mod tests { - use super::*; - use crate::serve_repair::ShredRepairType; - use solana_ledger::shred::Shred; - use solana_sdk::timing::timestamp; + use { + super::*, crate::serve_repair::ShredRepairType, solana_ledger::shred::Shred, + solana_sdk::timing::timestamp, + }; #[test] fn test_add_request() { diff --git a/core/src/progress_map.rs b/core/src/progress_map.rs index 600e0497f673aa..11758dfbf73eb5 100644 --- a/core/src/progress_map.rs +++ b/core/src/progress_map.rs @@ -2,8 +2,8 @@ use { crate::{ cluster_info_vote_listener::SlotVoteTracker, cluster_slots::SlotPubkeys, + consensus::{Stake, VotedStakes}, replay_stage::SUPERMINORITY_THRESHOLD, - {consensus::Stake, consensus::VotedStakes}, }, solana_ledger::blockstore_processor::{ConfirmationProgress, ConfirmationTiming}, solana_runtime::{bank::Bank, bank_forks::BankForks, vote_account::VoteAccount}, diff --git a/core/src/repair_generic_traversal.rs b/core/src/repair_generic_traversal.rs index 24eb36aacc9da7..8509e23c07c89e 100644 --- a/core/src/repair_generic_traversal.rs +++ b/core/src/repair_generic_traversal.rs @@ -1,10 +1,12 @@ -use crate::{ - heaviest_subtree_fork_choice::HeaviestSubtreeForkChoice, repair_service::RepairService, - serve_repair::ShredRepairType, tree_diff::TreeDiff, +use { + crate::{ + heaviest_subtree_fork_choice::HeaviestSubtreeForkChoice, repair_service::RepairService, + serve_repair::ShredRepairType, tree_diff::TreeDiff, + }, + solana_ledger::{blockstore::Blockstore, blockstore_meta::SlotMeta}, + solana_sdk::{clock::Slot, hash::Hash}, + std::collections::{HashMap, HashSet}, }; -use solana_ledger::{blockstore::Blockstore, blockstore_meta::SlotMeta}; -use solana_sdk::{clock::Slot, hash::Hash}; -use std::collections::{HashMap, HashSet}; struct GenericTraversal<'a> { tree: &'a HeaviestSubtreeForkChoice, @@ -164,14 +166,16 @@ pub fn get_closest_completion( #[cfg(test)] pub mod test { - use super::*; - use solana_ledger::{ - blockstore::{Blockstore, MAX_TURBINE_PROPAGATION_IN_MS}, - get_tmp_ledger_path, + use { + super::*, + solana_ledger::{ + blockstore::{Blockstore, MAX_TURBINE_PROPAGATION_IN_MS}, + get_tmp_ledger_path, + }, + solana_sdk::hash::Hash, + std::{thread::sleep, time::Duration}, + trees::{tr, Tree, TreeWalk}, }; - use solana_sdk::hash::Hash; - use std::{thread::sleep, time::Duration}; - use trees::{tr, Tree, TreeWalk}; #[test] fn test_get_unknown_last_index() { diff --git a/core/src/repair_response.rs b/core/src/repair_response.rs index ecd8b5d7c2fb4e..3c5c30aaee5cac 100644 --- a/core/src/repair_response.rs +++ b/core/src/repair_response.rs @@ -1,10 +1,12 @@ -use solana_ledger::{ - blockstore::Blockstore, - shred::{Nonce, SIZE_OF_NONCE}, +use { + solana_ledger::{ + blockstore::Blockstore, + shred::{Nonce, SIZE_OF_NONCE}, + }, + solana_perf::packet::limited_deserialize, + solana_sdk::{clock::Slot, packet::Packet}, + std::{io, net::SocketAddr}, }; -use solana_perf::packet::limited_deserialize; -use solana_sdk::{clock::Slot, packet::Packet}; -use std::{io, net::SocketAddr}; pub fn repair_response_packet( blockstore: &Blockstore, @@ -48,15 +50,17 @@ pub fn nonce(buf: &[u8]) -> Option { #[cfg(test)] mod test { - use super::*; - use solana_ledger::{ - shred::{Shred, Shredder}, - sigverify_shreds::verify_shred_cpu, - }; - use solana_sdk::signature::{Keypair, Signer}; - use std::{ - collections::HashMap, - net::{IpAddr, Ipv4Addr}, + use { + super::*, + solana_ledger::{ + shred::{Shred, Shredder}, + sigverify_shreds::verify_shred_cpu, + }, + solana_sdk::signature::{Keypair, Signer}, + std::{ + collections::HashMap, + net::{IpAddr, Ipv4Addr}, + }, }; fn run_test_sigverify_shred_cpu_repair(slot: Slot) { diff --git a/core/src/repair_service.rs b/core/src/repair_service.rs index 3a38a9e92cc384..df5e25e7051cca 100644 --- a/core/src/repair_service.rs +++ b/core/src/repair_service.rs @@ -1,38 +1,40 @@ //! The `repair_service` module implements the tools necessary to generate a thread which //! regularly finds missing shreds in the ledger and sends repair requests for those shreds -use crate::{ - ancestor_hashes_service::{AncestorHashesReplayUpdateReceiver, AncestorHashesService}, - cluster_info_vote_listener::VerifiedVoteReceiver, - cluster_slots::ClusterSlots, - duplicate_repair_status::DuplicateSlotRepairStatus, - outstanding_requests::OutstandingRequests, - repair_weight::RepairWeight, - result::Result, - serve_repair::{ServeRepair, ShredRepairType, REPAIR_PEERS_CACHE_CAPACITY}, -}; -use crossbeam_channel::{Receiver as CrossbeamReceiver, Sender as CrossbeamSender}; -use lru::LruCache; -use solana_gossip::cluster_info::ClusterInfo; -use solana_ledger::{ - blockstore::{Blockstore, SlotMeta}, - shred::Nonce, -}; -use solana_measure::measure::Measure; -use solana_runtime::{bank_forks::BankForks, contains::Contains}; -use solana_sdk::{ - clock::Slot, epoch_schedule::EpochSchedule, hash::Hash, pubkey::Pubkey, timing::timestamp, -}; -use solana_streamer::sendmmsg::{batch_send, SendPktsError}; -use std::{ - collections::{HashMap, HashSet}, - iter::Iterator, - net::SocketAddr, - net::UdpSocket, - sync::atomic::{AtomicBool, Ordering}, - sync::{Arc, RwLock}, - thread::sleep, - thread::{self, Builder, JoinHandle}, - time::{Duration, Instant}, +use { + crate::{ + ancestor_hashes_service::{AncestorHashesReplayUpdateReceiver, AncestorHashesService}, + cluster_info_vote_listener::VerifiedVoteReceiver, + cluster_slots::ClusterSlots, + duplicate_repair_status::DuplicateSlotRepairStatus, + outstanding_requests::OutstandingRequests, + repair_weight::RepairWeight, + result::Result, + serve_repair::{ServeRepair, ShredRepairType, REPAIR_PEERS_CACHE_CAPACITY}, + }, + crossbeam_channel::{Receiver as CrossbeamReceiver, Sender as CrossbeamSender}, + lru::LruCache, + solana_gossip::cluster_info::ClusterInfo, + solana_ledger::{ + blockstore::{Blockstore, SlotMeta}, + shred::Nonce, + }, + solana_measure::measure::Measure, + solana_runtime::{bank_forks::BankForks, contains::Contains}, + solana_sdk::{ + clock::Slot, epoch_schedule::EpochSchedule, hash::Hash, pubkey::Pubkey, timing::timestamp, + }, + solana_streamer::sendmmsg::{batch_send, SendPktsError}, + std::{ + collections::{HashMap, HashSet}, + iter::Iterator, + net::{SocketAddr, UdpSocket}, + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, RwLock, + }, + thread::{self, sleep, Builder, JoinHandle}, + time::{Duration, Instant}, + }, }; pub type DuplicateSlotsResetSender = CrossbeamSender>; @@ -715,16 +717,20 @@ impl RepairService { #[cfg(test)] mod test { - use super::*; - use solana_gossip::{cluster_info::Node, contact_info::ContactInfo}; - use solana_ledger::blockstore::{ - make_chaining_slot_entries, make_many_slot_entries, make_slot_entries, + use { + super::*, + solana_gossip::{cluster_info::Node, contact_info::ContactInfo}, + solana_ledger::{ + blockstore::{ + make_chaining_slot_entries, make_many_slot_entries, make_slot_entries, Blockstore, + }, + get_tmp_ledger_path, + shred::max_ticks_per_n_shreds, + }, + solana_sdk::signature::Keypair, + solana_streamer::socket::SocketAddrSpace, + std::collections::HashSet, }; - use solana_ledger::shred::max_ticks_per_n_shreds; - use solana_ledger::{blockstore::Blockstore, get_tmp_ledger_path}; - use solana_sdk::signature::Keypair; - use solana_streamer::socket::SocketAddrSpace; - use std::collections::HashSet; fn new_test_cluster_info(contact_info: ContactInfo) -> ClusterInfo { ClusterInfo::new( diff --git a/core/src/repair_weight.rs b/core/src/repair_weight.rs index a167a6811ef4c6..ae535804fbd65b 100644 --- a/core/src/repair_weight.rs +++ b/core/src/repair_weight.rs @@ -1,23 +1,25 @@ -use crate::{ - heaviest_subtree_fork_choice::HeaviestSubtreeForkChoice, - repair_generic_traversal::{get_closest_completion, get_unknown_last_index}, - repair_service::{BestRepairsStats, RepairTiming}, - repair_weighted_traversal, - serve_repair::ShredRepairType, - tree_diff::TreeDiff, +use { + crate::{ + heaviest_subtree_fork_choice::HeaviestSubtreeForkChoice, + repair_generic_traversal::{get_closest_completion, get_unknown_last_index}, + repair_service::{BestRepairsStats, RepairTiming}, + repair_weighted_traversal, + serve_repair::ShredRepairType, + tree_diff::TreeDiff, + }, + solana_ledger::{ + ancestor_iterator::AncestorIterator, blockstore::Blockstore, blockstore_meta::SlotMeta, + }, + solana_measure::measure::Measure, + solana_runtime::{contains::Contains, epoch_stakes::EpochStakes}, + solana_sdk::{ + clock::Slot, + epoch_schedule::{Epoch, EpochSchedule}, + hash::Hash, + pubkey::Pubkey, + }, + std::collections::{BTreeSet, HashMap, HashSet, VecDeque}, }; -use solana_ledger::{ - ancestor_iterator::AncestorIterator, blockstore::Blockstore, blockstore_meta::SlotMeta, -}; -use solana_measure::measure::Measure; -use solana_runtime::{contains::Contains, epoch_stakes::EpochStakes}; -use solana_sdk::{ - clock::Slot, - epoch_schedule::{Epoch, EpochSchedule}, - hash::Hash, - pubkey::Pubkey, -}; -use std::collections::{BTreeSet, HashMap, HashSet, VecDeque}; pub struct RepairWeight { // Map from root -> a subtree rooted at that `root` @@ -653,11 +655,13 @@ impl RepairWeight { #[cfg(test)] mod test { - use super::*; - use solana_ledger::{blockstore::Blockstore, get_tmp_ledger_path}; - use solana_runtime::{bank::Bank, bank_utils}; - use solana_sdk::hash::Hash; - use trees::tr; + use { + super::*, + solana_ledger::{blockstore::Blockstore, get_tmp_ledger_path}, + solana_runtime::{bank::Bank, bank_utils}, + solana_sdk::hash::Hash, + trees::tr, + }; #[test] fn test_sort_by_stake_weight_slot() { diff --git a/core/src/repair_weighted_traversal.rs b/core/src/repair_weighted_traversal.rs index a7e744d6e7192e..939955ff420210 100644 --- a/core/src/repair_weighted_traversal.rs +++ b/core/src/repair_weighted_traversal.rs @@ -1,11 +1,13 @@ -use crate::{ - heaviest_subtree_fork_choice::HeaviestSubtreeForkChoice, repair_service::RepairService, - serve_repair::ShredRepairType, tree_diff::TreeDiff, +use { + crate::{ + heaviest_subtree_fork_choice::HeaviestSubtreeForkChoice, repair_service::RepairService, + serve_repair::ShredRepairType, tree_diff::TreeDiff, + }, + solana_ledger::{blockstore::Blockstore, blockstore_meta::SlotMeta}, + solana_runtime::contains::Contains, + solana_sdk::{clock::Slot, hash::Hash}, + std::collections::{HashMap, HashSet}, }; -use solana_ledger::{blockstore::Blockstore, blockstore_meta::SlotMeta}; -use solana_runtime::contains::Contains; -use solana_sdk::{clock::Slot, hash::Hash}; -use std::collections::{HashMap, HashSet}; #[derive(Debug, PartialEq)] enum Visit { @@ -136,11 +138,13 @@ pub fn get_best_repair_shreds<'a>( #[cfg(test)] pub mod test { - use super::*; - use solana_ledger::{get_tmp_ledger_path, shred::Shred}; - use solana_runtime::bank_utils; - use solana_sdk::hash::Hash; - use trees::tr; + use { + super::*, + solana_ledger::{get_tmp_ledger_path, shred::Shred}, + solana_runtime::bank_utils, + solana_sdk::hash::Hash, + trees::tr, + }; #[test] fn test_weighted_repair_traversal_single() { diff --git a/core/src/replay_stage.rs b/core/src/replay_stage.rs index f6e33960f1f766..39eeb7759ff9ec 100644 --- a/core/src/replay_stage.rs +++ b/core/src/replay_stage.rs @@ -43,8 +43,10 @@ use { rpc_subscriptions::RpcSubscriptions, }, solana_runtime::{ - accounts_background_service::AbsRequestSender, bank::Bank, bank::ExecuteTimings, - bank::NewBankOptions, bank_forks::BankForks, commitment::BlockCommitmentCache, + accounts_background_service::AbsRequestSender, + bank::{Bank, ExecuteTimings, NewBankOptions}, + bank_forks::BankForks, + commitment::BlockCommitmentCache, vote_sender_types::ReplayVoteSender, }, solana_sdk::{ @@ -52,8 +54,7 @@ use { genesis_config::ClusterType, hash::Hash, pubkey::Pubkey, - signature::Signature, - signature::{Keypair, Signer}, + signature::{Keypair, Signature, Signer}, timing::timestamp, transaction::Transaction, }, @@ -2882,61 +2883,61 @@ impl ReplayStage { #[cfg(test)] pub mod tests { - use super::*; - use crate::{ - consensus::Tower, - progress_map::ValidatorStakeInfo, - replay_stage::ReplayStage, - tree_diff::TreeDiff, - vote_simulator::{self, VoteSimulator}, - }; - use crossbeam_channel::unbounded; - use solana_entry::entry::{self, Entry}; - use solana_gossip::{cluster_info::Node, crds::Cursor}; - use solana_ledger::{ - blockstore::make_slot_entries, - blockstore::{entries_to_test_shreds, BlockstoreError}, - create_new_tmp_ledger, - genesis_utils::{create_genesis_config, create_genesis_config_with_leader}, - get_tmp_ledger_path, - shred::{ - CodingShredHeader, DataShredHeader, Shred, ShredCommonHeader, DATA_COMPLETE_SHRED, - SIZE_OF_COMMON_SHRED_HEADER, SIZE_OF_DATA_SHRED_HEADER, SIZE_OF_DATA_SHRED_PAYLOAD, + use { + super::*, + crate::{ + consensus::Tower, + progress_map::ValidatorStakeInfo, + replay_stage::ReplayStage, + tree_diff::TreeDiff, + vote_simulator::{self, VoteSimulator}, }, + crossbeam_channel::unbounded, + solana_entry::entry::{self, Entry}, + solana_gossip::{cluster_info::Node, crds::Cursor}, + solana_ledger::{ + blockstore::{entries_to_test_shreds, make_slot_entries, BlockstoreError}, + create_new_tmp_ledger, + genesis_utils::{create_genesis_config, create_genesis_config_with_leader}, + get_tmp_ledger_path, + shred::{ + CodingShredHeader, DataShredHeader, Shred, ShredCommonHeader, DATA_COMPLETE_SHRED, + SIZE_OF_COMMON_SHRED_HEADER, SIZE_OF_DATA_SHRED_HEADER, SIZE_OF_DATA_SHRED_PAYLOAD, + }, + }, + solana_rpc::{ + optimistically_confirmed_bank_tracker::OptimisticallyConfirmedBank, + rpc::create_test_transactions_and_populate_blockstore, + }, + solana_runtime::{ + accounts_background_service::AbsRequestSender, + commitment::BlockCommitment, + genesis_utils::{GenesisConfigInfo, ValidatorVoteKeypairs}, + }, + solana_sdk::{ + clock::NUM_CONSECUTIVE_LEADER_SLOTS, + genesis_config, + hash::{hash, Hash}, + instruction::InstructionError, + packet::PACKET_DATA_SIZE, + poh_config::PohConfig, + signature::{Keypair, Signer}, + system_transaction, + transaction::TransactionError, + }, + solana_streamer::socket::SocketAddrSpace, + solana_transaction_status::TransactionWithStatusMeta, + solana_vote_program::{ + vote_state::{VoteState, VoteStateVersions}, + vote_transaction, + }, + std::{ + fs::remove_dir_all, + iter, + sync::{atomic::AtomicU64, mpsc::channel, Arc, RwLock}, + }, + trees::{tr, Tree}, }; - use solana_rpc::{ - optimistically_confirmed_bank_tracker::OptimisticallyConfirmedBank, - rpc::create_test_transactions_and_populate_blockstore, - }; - use solana_runtime::{ - accounts_background_service::AbsRequestSender, - commitment::BlockCommitment, - genesis_utils::{GenesisConfigInfo, ValidatorVoteKeypairs}, - }; - use solana_sdk::{ - clock::NUM_CONSECUTIVE_LEADER_SLOTS, - genesis_config, - hash::{hash, Hash}, - instruction::InstructionError, - packet::PACKET_DATA_SIZE, - poh_config::PohConfig, - signature::{Keypair, Signer}, - system_transaction, - transaction::TransactionError, - }; - use solana_streamer::socket::SocketAddrSpace; - use solana_transaction_status::TransactionWithStatusMeta; - use solana_vote_program::{ - vote_state::{VoteState, VoteStateVersions}, - vote_transaction, - }; - use std::sync::mpsc::channel; - use std::{ - fs::remove_dir_all, - iter, - sync::{atomic::AtomicU64, Arc, RwLock}, - }; - use trees::{tr, Tree}; #[test] fn test_is_partition_detected() { diff --git a/core/src/result.rs b/core/src/result.rs index 5fafca2ee1bed7..dbe32850c9e328 100644 --- a/core/src/result.rs +++ b/core/src/result.rs @@ -1,7 +1,9 @@ //! The `result` module exposes a Result type that propagates one of many different Error types. -use solana_gossip::{cluster_info, gossip_error::GossipError}; -use solana_ledger::blockstore; +use { + solana_gossip::{cluster_info, gossip_error::GossipError}, + solana_ledger::blockstore, +}; #[derive(Debug)] pub enum Error { @@ -98,14 +100,15 @@ impl std::convert::From for Error { #[cfg(test)] mod tests { - use crate::result::Error; - use crate::result::Result; - use std::io; - use std::io::Write; - use std::panic; - use std::sync::mpsc::channel; - use std::sync::mpsc::RecvError; - use std::sync::mpsc::RecvTimeoutError; + use { + crate::result::{Error, Result}, + std::{ + io, + io::Write, + panic, + sync::mpsc::{channel, RecvError, RecvTimeoutError}, + }, + }; fn send_error() -> Result<()> { let (s, r) = channel(); diff --git a/core/src/retransmit_stage.rs b/core/src/retransmit_stage.rs index df43d373fc4763..dacf89e06dca87 100644 --- a/core/src/retransmit_stage.rs +++ b/core/src/retransmit_stage.rs @@ -22,8 +22,9 @@ use { contact_info::ContactInfo, }, solana_ledger::{ + blockstore::Blockstore, + leader_schedule_cache::LeaderScheduleCache, shred::{Shred, ShredType}, - {blockstore::Blockstore, leader_schedule_cache::LeaderScheduleCache}, }, solana_measure::measure::Measure, solana_perf::packet::Packets, diff --git a/core/src/rewards_recorder_service.rs b/core/src/rewards_recorder_service.rs index 65c66fe49aa66c..8988441d22222f 100644 --- a/core/src/rewards_recorder_service.rs +++ b/core/src/rewards_recorder_service.rs @@ -1,15 +1,17 @@ -use crossbeam_channel::{Receiver, RecvTimeoutError, Sender}; -use solana_ledger::blockstore::Blockstore; -use solana_runtime::bank::RewardInfo; -use solana_sdk::{clock::Slot, pubkey::Pubkey}; -use solana_transaction_status::Reward; -use std::{ - sync::{ - atomic::{AtomicBool, Ordering}, - Arc, +use { + crossbeam_channel::{Receiver, RecvTimeoutError, Sender}, + solana_ledger::blockstore::Blockstore, + solana_runtime::bank::RewardInfo, + solana_sdk::{clock::Slot, pubkey::Pubkey}, + solana_transaction_status::Reward, + std::{ + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, + }, + thread::{self, Builder, JoinHandle}, + time::Duration, }, - thread::{self, Builder, JoinHandle}, - time::Duration, }; pub type RewardsRecorderReceiver = Receiver<(Slot, Vec<(Pubkey, RewardInfo)>)>; diff --git a/core/src/sample_performance_service.rs b/core/src/sample_performance_service.rs index c02be57746916b..fe6820c91dde8d 100644 --- a/core/src/sample_performance_service.rs +++ b/core/src/sample_performance_service.rs @@ -1,12 +1,14 @@ -use solana_ledger::{blockstore::Blockstore, blockstore_meta::PerfSample}; -use solana_runtime::bank_forks::BankForks; -use std::{ - sync::{ - atomic::{AtomicBool, Ordering}, - Arc, RwLock, +use { + solana_ledger::{blockstore::Blockstore, blockstore_meta::PerfSample}, + solana_runtime::bank_forks::BankForks, + std::{ + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, RwLock, + }, + thread::{self, sleep, Builder, JoinHandle}, + time::{Duration, Instant}, }, - thread::{self, sleep, Builder, JoinHandle}, - time::{Duration, Instant}, }; const SAMPLE_INTERVAL: u64 = 60; diff --git a/core/src/serve_repair.rs b/core/src/serve_repair.rs index a5443d998bf4e1..2086661e785818 100644 --- a/core/src/serve_repair.rs +++ b/core/src/serve_repair.rs @@ -1,41 +1,45 @@ -use crate::{ - cluster_slots::ClusterSlots, - duplicate_repair_status::ANCESTOR_HASH_REPAIR_SAMPLE_SIZE, - repair_response, - repair_service::{OutstandingShredRepairs, RepairStats}, - request_response::RequestResponse, - result::{Error, Result}, -}; -use bincode::serialize; -use lru::LruCache; -use rand::{ - distributions::{Distribution, WeightedError, WeightedIndex}, - Rng, -}; -use solana_gossip::{ - cluster_info::{ClusterInfo, ClusterInfoError}, - contact_info::ContactInfo, - weighted_shuffle::{weighted_best, weighted_shuffle}, -}; -use solana_ledger::{ - ancestor_iterator::{AncestorIterator, AncestorIteratorWithHash}, - blockstore::Blockstore, - shred::{Nonce, Shred, SIZE_OF_NONCE}, -}; -use solana_measure::measure::Measure; -use solana_metrics::inc_new_counter_debug; -use solana_perf::packet::{limited_deserialize, Packets, PacketsRecycler}; -use solana_sdk::{ - clock::Slot, hash::Hash, packet::PACKET_DATA_SIZE, pubkey::Pubkey, timing::duration_as_ms, -}; -use solana_streamer::streamer::{PacketReceiver, PacketSender}; -use std::{ - collections::HashSet, - net::SocketAddr, - sync::atomic::{AtomicBool, Ordering}, - sync::{Arc, RwLock}, - thread::{Builder, JoinHandle}, - time::{Duration, Instant}, +use { + crate::{ + cluster_slots::ClusterSlots, + duplicate_repair_status::ANCESTOR_HASH_REPAIR_SAMPLE_SIZE, + repair_response, + repair_service::{OutstandingShredRepairs, RepairStats}, + request_response::RequestResponse, + result::{Error, Result}, + }, + bincode::serialize, + lru::LruCache, + rand::{ + distributions::{Distribution, WeightedError, WeightedIndex}, + Rng, + }, + solana_gossip::{ + cluster_info::{ClusterInfo, ClusterInfoError}, + contact_info::ContactInfo, + weighted_shuffle::{weighted_best, weighted_shuffle}, + }, + solana_ledger::{ + ancestor_iterator::{AncestorIterator, AncestorIteratorWithHash}, + blockstore::Blockstore, + shred::{Nonce, Shred, SIZE_OF_NONCE}, + }, + solana_measure::measure::Measure, + solana_metrics::inc_new_counter_debug, + solana_perf::packet::{limited_deserialize, Packets, PacketsRecycler}, + solana_sdk::{ + clock::Slot, hash::Hash, packet::PACKET_DATA_SIZE, pubkey::Pubkey, timing::duration_as_ms, + }, + solana_streamer::streamer::{PacketReceiver, PacketSender}, + std::{ + collections::HashSet, + net::SocketAddr, + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, RwLock, + }, + thread::{Builder, JoinHandle}, + time::{Duration, Instant}, + }, }; type SlotHash = (Slot, Hash); @@ -752,18 +756,20 @@ impl ServeRepair { #[cfg(test)] mod tests { - use super::*; - use crate::{repair_response, result::Error}; - use solana_gossip::{socketaddr, socketaddr_any}; - use solana_ledger::get_tmp_ledger_path; - use solana_ledger::{ - blockstore::make_many_slot_entries, - blockstore_processor::fill_blockstore_slot_with_ticks, - shred::{max_ticks_per_n_shreds, Shred}, + use { + super::*, + crate::{repair_response, result::Error}, + solana_gossip::{socketaddr, socketaddr_any}, + solana_ledger::{ + blockstore::make_many_slot_entries, + blockstore_processor::fill_blockstore_slot_with_ticks, + get_tmp_ledger_path, + shred::{max_ticks_per_n_shreds, Shred}, + }, + solana_perf::packet::Packet, + solana_sdk::{hash::Hash, pubkey::Pubkey, signature::Keypair, timing::timestamp}, + solana_streamer::socket::SocketAddrSpace, }; - use solana_perf::packet::Packet; - use solana_sdk::{hash::Hash, pubkey::Pubkey, signature::Keypair, timing::timestamp}; - use solana_streamer::socket::SocketAddrSpace; #[test] fn test_run_highest_window_request() { diff --git a/core/src/serve_repair_service.rs b/core/src/serve_repair_service.rs index 91583f007f5da8..75a69ecc223c6d 100644 --- a/core/src/serve_repair_service.rs +++ b/core/src/serve_repair_service.rs @@ -1,12 +1,14 @@ -use crate::serve_repair::ServeRepair; -use solana_ledger::blockstore::Blockstore; -use solana_perf::recycler::Recycler; -use solana_streamer::{socket::SocketAddrSpace, streamer}; -use std::net::UdpSocket; -use std::sync::atomic::AtomicBool; -use std::sync::mpsc::channel; -use std::sync::{Arc, RwLock}; -use std::thread::{self, JoinHandle}; +use { + crate::serve_repair::ServeRepair, + solana_ledger::blockstore::Blockstore, + solana_perf::recycler::Recycler, + solana_streamer::{socket::SocketAddrSpace, streamer}, + std::{ + net::UdpSocket, + sync::{atomic::AtomicBool, mpsc::channel, Arc, RwLock}, + thread::{self, JoinHandle}, + }, +}; pub struct ServeRepairService { thread_hdls: Vec>, diff --git a/core/src/shred_fetch_stage.rs b/core/src/shred_fetch_stage.rs index 49685f3391d659..a0d02ba4a14caa 100644 --- a/core/src/shred_fetch_stage.rs +++ b/core/src/shred_fetch_stage.rs @@ -1,21 +1,24 @@ //! The `shred_fetch_stage` pulls shreds from UDP sockets and sends it to a channel. -use crate::packet_hasher::PacketHasher; -use lru::LruCache; -use solana_ledger::shred::{get_shred_slot_index_type, ShredFetchStats}; -use solana_perf::cuda_runtime::PinnedVec; -use solana_perf::packet::{Packet, PacketsRecycler}; -use solana_perf::recycler::Recycler; -use solana_runtime::bank_forks::BankForks; -use solana_sdk::clock::{Slot, DEFAULT_MS_PER_SLOT}; -use solana_streamer::streamer::{self, PacketReceiver, PacketSender}; -use std::net::UdpSocket; -use std::sync::atomic::AtomicBool; -use std::sync::mpsc::channel; -use std::sync::Arc; -use std::sync::RwLock; -use std::thread::{self, Builder, JoinHandle}; -use std::time::Instant; +use { + crate::packet_hasher::PacketHasher, + lru::LruCache, + solana_ledger::shred::{get_shred_slot_index_type, ShredFetchStats}, + solana_perf::{ + cuda_runtime::PinnedVec, + packet::{Packet, PacketsRecycler}, + recycler::Recycler, + }, + solana_runtime::bank_forks::BankForks, + solana_sdk::clock::{Slot, DEFAULT_MS_PER_SLOT}, + solana_streamer::streamer::{self, PacketReceiver, PacketSender}, + std::{ + net::UdpSocket, + sync::{atomic::AtomicBool, mpsc::channel, Arc, RwLock}, + thread::{self, Builder, JoinHandle}, + time::Instant, + }, +}; const DEFAULT_LRU_SIZE: usize = 10_000; pub type ShredsReceived = LruCache; @@ -223,9 +226,10 @@ impl ShredFetchStage { #[cfg(test)] mod tests { - use super::*; - use solana_ledger::blockstore::MAX_DATA_SHREDS_PER_SLOT; - use solana_ledger::shred::Shred; + use { + super::*, + solana_ledger::{blockstore::MAX_DATA_SHREDS_PER_SLOT, shred::Shred}, + }; #[test] fn test_data_code_same_index() { diff --git a/core/src/sigverify.rs b/core/src/sigverify.rs index 53b1da56ae5e0d..8ffa30bb84168a 100644 --- a/core/src/sigverify.rs +++ b/core/src/sigverify.rs @@ -4,14 +4,13 @@ //! to the GPU. //! -use crate::sigverify_stage::SigVerifier; -use solana_perf::cuda_runtime::PinnedVec; -use solana_perf::packet::Packets; -use solana_perf::recycler::Recycler; -use solana_perf::sigverify; pub use solana_perf::sigverify::{ batch_size, ed25519_verify_cpu, ed25519_verify_disabled, init, TxOffset, }; +use { + crate::sigverify_stage::SigVerifier, + solana_perf::{cuda_runtime::PinnedVec, packet::Packets, recycler::Recycler, sigverify}, +}; #[derive(Clone)] pub struct TransactionSigVerifier { diff --git a/core/src/sigverify_shreds.rs b/core/src/sigverify_shreds.rs index 4026b56b4d83f5..08ebae0bb22d8d 100644 --- a/core/src/sigverify_shreds.rs +++ b/core/src/sigverify_shreds.rs @@ -1,13 +1,17 @@ #![allow(clippy::implicit_hasher)] -use crate::sigverify; -use crate::sigverify_stage::SigVerifier; -use solana_ledger::leader_schedule_cache::LeaderScheduleCache; -use solana_ledger::shred::Shred; -use solana_ledger::sigverify_shreds::verify_shreds_gpu; -use solana_perf::{self, packet::Packets, recycler_cache::RecyclerCache}; -use solana_runtime::bank_forks::BankForks; -use std::collections::{HashMap, HashSet}; -use std::sync::{Arc, RwLock}; +use { + crate::{sigverify, sigverify_stage::SigVerifier}, + solana_ledger::{ + leader_schedule_cache::LeaderScheduleCache, shred::Shred, + sigverify_shreds::verify_shreds_gpu, + }, + solana_perf::{self, packet::Packets, recycler_cache::RecyclerCache}, + solana_runtime::bank_forks::BankForks, + std::{ + collections::{HashMap, HashSet}, + sync::{Arc, RwLock}, + }, +}; #[derive(Clone)] pub struct ShredSigVerifier { @@ -59,12 +63,16 @@ impl SigVerifier for ShredSigVerifier { #[cfg(test)] pub mod tests { - use super::*; - use solana_ledger::genesis_utils::create_genesis_config_with_leader; - use solana_ledger::shred::{Shred, Shredder}; - use solana_perf::packet::Packet; - use solana_runtime::bank::Bank; - use solana_sdk::signature::{Keypair, Signer}; + use { + super::*, + solana_ledger::{ + genesis_utils::create_genesis_config_with_leader, + shred::{Shred, Shredder}, + }, + solana_perf::packet::Packet, + solana_runtime::bank::Bank, + solana_sdk::signature::{Keypair, Signer}, + }; #[test] fn test_sigverify_shreds_read_slots() { diff --git a/core/src/sigverify_stage.rs b/core/src/sigverify_stage.rs index 96fa36f1196dab..9810c5dc270852 100644 --- a/core/src/sigverify_stage.rs +++ b/core/src/sigverify_stage.rs @@ -5,19 +5,21 @@ //! transaction. All processing is done on the CPU by default and on a GPU //! if perf-libs are available -use crate::sigverify; -use crossbeam_channel::{SendError, Sender as CrossbeamSender}; -use solana_measure::measure::Measure; -use solana_perf::packet::Packets; -use solana_sdk::timing; -use solana_streamer::streamer::{self, PacketReceiver, StreamerError}; -use std::{ - collections::HashMap, - sync::mpsc::{Receiver, RecvTimeoutError}, - thread::{self, Builder, JoinHandle}, - time::Instant, +use { + crate::sigverify, + crossbeam_channel::{SendError, Sender as CrossbeamSender}, + solana_measure::measure::Measure, + solana_perf::packet::Packets, + solana_sdk::timing, + solana_streamer::streamer::{self, PacketReceiver, StreamerError}, + std::{ + collections::HashMap, + sync::mpsc::{Receiver, RecvTimeoutError}, + thread::{self, Builder, JoinHandle}, + time::Instant, + }, + thiserror::Error, }; -use thiserror::Error; const MAX_SIGVERIFY_BATCH: usize = 10_000; @@ -264,8 +266,7 @@ impl SigVerifyStage { #[cfg(test)] mod tests { - use super::*; - use solana_perf::packet::Packet; + use {super::*, solana_perf::packet::Packet}; fn count_non_discard(packets: &[Packets]) -> usize { packets diff --git a/core/src/snapshot_packager_service.rs b/core/src/snapshot_packager_service.rs index 675f6573a6fa1b..6460dcca2c7c53 100644 --- a/core/src/snapshot_packager_service.rs +++ b/core/src/snapshot_packager_service.rs @@ -1,25 +1,27 @@ -use solana_gossip::cluster_info::{ - ClusterInfo, MAX_INCREMENTAL_SNAPSHOT_HASHES, MAX_SNAPSHOT_HASHES, -}; -use solana_perf::thread::renice_this_thread; -use solana_runtime::{ - snapshot_archive_info::SnapshotArchiveInfoGetter, - snapshot_config::SnapshotConfig, - snapshot_hash::{ - FullSnapshotHash, FullSnapshotHashes, IncrementalSnapshotHash, IncrementalSnapshotHashes, - StartingSnapshotHashes, +use { + solana_gossip::cluster_info::{ + ClusterInfo, MAX_INCREMENTAL_SNAPSHOT_HASHES, MAX_SNAPSHOT_HASHES, }, - snapshot_package::{PendingSnapshotPackage, SnapshotType}, - snapshot_utils, -}; -use solana_sdk::{clock::Slot, hash::Hash}; -use std::{ - sync::{ - atomic::{AtomicBool, Ordering}, - Arc, + solana_perf::thread::renice_this_thread, + solana_runtime::{ + snapshot_archive_info::SnapshotArchiveInfoGetter, + snapshot_config::SnapshotConfig, + snapshot_hash::{ + FullSnapshotHash, FullSnapshotHashes, IncrementalSnapshotHash, + IncrementalSnapshotHashes, StartingSnapshotHashes, + }, + snapshot_package::{PendingSnapshotPackage, SnapshotType}, + snapshot_utils, + }, + solana_sdk::{clock::Slot, hash::Hash}, + std::{ + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, + }, + thread::{self, Builder, JoinHandle}, + time::Duration, }, - thread::{self, Builder, JoinHandle}, - time::Duration, }; pub struct SnapshotPackagerService { @@ -208,22 +210,26 @@ impl SnapshotGossipManager { #[cfg(test)] mod tests { - use super::*; - use bincode::serialize_into; - use solana_runtime::{ - accounts_db::AccountStorageEntry, - bank::BankSlotDelta, - snapshot_archive_info::SnapshotArchiveInfo, - snapshot_package::{SnapshotPackage, SnapshotType}, - snapshot_utils::{self, ArchiveFormat, SnapshotVersion, SNAPSHOT_STATUS_CACHE_FILE_NAME}, - }; - use solana_sdk::hash::Hash; - use std::{ - fs::{self, remove_dir_all, OpenOptions}, - io::Write, - path::{Path, PathBuf}, + use { + super::*, + bincode::serialize_into, + solana_runtime::{ + accounts_db::AccountStorageEntry, + bank::BankSlotDelta, + snapshot_archive_info::SnapshotArchiveInfo, + snapshot_package::{SnapshotPackage, SnapshotType}, + snapshot_utils::{ + self, ArchiveFormat, SnapshotVersion, SNAPSHOT_STATUS_CACHE_FILE_NAME, + }, + }, + solana_sdk::hash::Hash, + std::{ + fs::{self, remove_dir_all, OpenOptions}, + io::Write, + path::{Path, PathBuf}, + }, + tempfile::TempDir, }; - use tempfile::TempDir; // Create temporary placeholder directory for all test files fn make_tmp_dir_path() -> PathBuf { diff --git a/core/src/system_monitor_service.rs b/core/src/system_monitor_service.rs index b609dda7022071..6e5d519bda2400 100644 --- a/core/src/system_monitor_service.rs +++ b/core/src/system_monitor_service.rs @@ -1,17 +1,18 @@ -use solana_sdk::timing::AtomicInterval; -use std::{ - collections::HashMap, - io::BufRead, - sync::{ - atomic::{AtomicBool, Ordering}, - Arc, - }, - thread::{self, sleep, Builder, JoinHandle}, - time::Duration, -}; - #[cfg(target_os = "linux")] use std::{fs::File, io::BufReader, path::Path}; +use { + solana_sdk::timing::AtomicInterval, + std::{ + collections::HashMap, + io::BufRead, + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, + }, + thread::{self, sleep, Builder, JoinHandle}, + time::Duration, + }, +}; const MS_PER_S: u64 = 1_000; const SAMPLE_INTERVAL_UDP_MS: u64 = 60 * MS_PER_S; diff --git a/core/src/tpu.rs b/core/src/tpu.rs index fb895bd084f58d..4b4eadf92cdc9d 100644 --- a/core/src/tpu.rs +++ b/core/src/tpu.rs @@ -1,38 +1,40 @@ //! The `tpu` module implements the Transaction Processing Unit, a //! multi-stage transaction processing pipeline in software. -use crate::{ - banking_stage::BankingStage, - broadcast_stage::{BroadcastStage, BroadcastStageType, RetransmitSlotsReceiver}, - cluster_info_vote_listener::{ - ClusterInfoVoteListener, GossipDuplicateConfirmedSlotsSender, GossipVerifiedVoteHashSender, - VerifiedVoteSender, VoteTracker, +use { + crate::{ + banking_stage::BankingStage, + broadcast_stage::{BroadcastStage, BroadcastStageType, RetransmitSlotsReceiver}, + cluster_info_vote_listener::{ + ClusterInfoVoteListener, GossipDuplicateConfirmedSlotsSender, + GossipVerifiedVoteHashSender, VerifiedVoteSender, VoteTracker, + }, + fetch_stage::FetchStage, + sigverify::TransactionSigVerifier, + sigverify_stage::SigVerifyStage, }, - fetch_stage::FetchStage, - sigverify::TransactionSigVerifier, - sigverify_stage::SigVerifyStage, -}; -use crossbeam_channel::unbounded; -use solana_gossip::cluster_info::ClusterInfo; -use solana_ledger::{blockstore::Blockstore, blockstore_processor::TransactionStatusSender}; -use solana_poh::poh_recorder::{PohRecorder, WorkingBankEntry}; -use solana_rpc::{ - optimistically_confirmed_bank_tracker::BankNotificationSender, - rpc_subscriptions::RpcSubscriptions, -}; -use solana_runtime::{ - bank_forks::BankForks, - cost_model::CostModel, - vote_sender_types::{ReplayVoteReceiver, ReplayVoteSender}, -}; -use std::{ - net::UdpSocket, - sync::{ - atomic::AtomicBool, - mpsc::{channel, Receiver}, - Arc, Mutex, RwLock, + crossbeam_channel::unbounded, + solana_gossip::cluster_info::ClusterInfo, + solana_ledger::{blockstore::Blockstore, blockstore_processor::TransactionStatusSender}, + solana_poh::poh_recorder::{PohRecorder, WorkingBankEntry}, + solana_rpc::{ + optimistically_confirmed_bank_tracker::BankNotificationSender, + rpc_subscriptions::RpcSubscriptions, + }, + solana_runtime::{ + bank_forks::BankForks, + cost_model::CostModel, + vote_sender_types::{ReplayVoteReceiver, ReplayVoteSender}, + }, + std::{ + net::UdpSocket, + sync::{ + atomic::AtomicBool, + mpsc::{channel, Receiver}, + Arc, Mutex, RwLock, + }, + thread, }, - thread, }; pub const DEFAULT_TPU_COALESCE_MS: u64 = 5; diff --git a/core/src/tvu.rs b/core/src/tvu.rs index 387d6baeb14542..adda7b0d01b5e9 100644 --- a/core/src/tvu.rs +++ b/core/src/tvu.rs @@ -1,63 +1,67 @@ //! The `tvu` module implements the Transaction Validation Unit, a multi-stage transaction //! validation pipeline in software. -use crate::{ - accounts_hash_verifier::AccountsHashVerifier, - broadcast_stage::RetransmitSlotsSender, - cache_block_meta_service::CacheBlockMetaSender, - cluster_info_vote_listener::{ - GossipDuplicateConfirmedSlotsReceiver, GossipVerifiedVoteHashReceiver, - VerifiedVoteReceiver, VoteTracker, +use { + crate::{ + accounts_hash_verifier::AccountsHashVerifier, + broadcast_stage::RetransmitSlotsSender, + cache_block_meta_service::CacheBlockMetaSender, + cluster_info_vote_listener::{ + GossipDuplicateConfirmedSlotsReceiver, GossipVerifiedVoteHashReceiver, + VerifiedVoteReceiver, VoteTracker, + }, + cluster_slots::ClusterSlots, + completed_data_sets_service::CompletedDataSetsSender, + consensus::Tower, + cost_update_service::CostUpdateService, + drop_bank_service::DropBankService, + ledger_cleanup_service::LedgerCleanupService, + replay_stage::{ReplayStage, ReplayStageConfig}, + retransmit_stage::RetransmitStage, + rewards_recorder_service::RewardsRecorderSender, + shred_fetch_stage::ShredFetchStage, + sigverify_shreds::ShredSigVerifier, + sigverify_stage::SigVerifyStage, + tower_storage::TowerStorage, + voting_service::VotingService, }, - cluster_slots::ClusterSlots, - completed_data_sets_service::CompletedDataSetsSender, - consensus::Tower, - cost_update_service::CostUpdateService, - drop_bank_service::DropBankService, - ledger_cleanup_service::LedgerCleanupService, - replay_stage::{ReplayStage, ReplayStageConfig}, - retransmit_stage::RetransmitStage, - rewards_recorder_service::RewardsRecorderSender, - shred_fetch_stage::ShredFetchStage, - sigverify_shreds::ShredSigVerifier, - sigverify_stage::SigVerifyStage, - tower_storage::TowerStorage, - voting_service::VotingService, -}; -use crossbeam_channel::unbounded; -use solana_gossip::cluster_info::ClusterInfo; -use solana_ledger::{ - blockstore::Blockstore, blockstore_processor::TransactionStatusSender, - leader_schedule_cache::LeaderScheduleCache, -}; -use solana_poh::poh_recorder::PohRecorder; -use solana_rpc::{ - max_slots::MaxSlots, optimistically_confirmed_bank_tracker::BankNotificationSender, - rpc_subscriptions::RpcSubscriptions, -}; -use solana_runtime::{ - accounts_background_service::{ - AbsRequestHandler, AbsRequestSender, AccountsBackgroundService, SnapshotRequestHandler, + crossbeam_channel::unbounded, + solana_gossip::cluster_info::ClusterInfo, + solana_ledger::{ + blockstore::Blockstore, blockstore_processor::TransactionStatusSender, + leader_schedule_cache::LeaderScheduleCache, }, - accounts_db::AccountShrinkThreshold, - bank_forks::BankForks, - commitment::BlockCommitmentCache, - cost_model::CostModel, - snapshot_config::SnapshotConfig, - snapshot_package::{AccountsPackageReceiver, AccountsPackageSender, PendingSnapshotPackage}, - vote_sender_types::ReplayVoteSender, -}; -use solana_sdk::{clock::Slot, pubkey::Pubkey, signature::Keypair}; -use std::{ - boxed::Box, - collections::HashSet, - net::UdpSocket, - sync::{ - atomic::AtomicBool, - mpsc::{channel, Receiver}, - Arc, Mutex, RwLock, + solana_poh::poh_recorder::PohRecorder, + solana_rpc::{ + max_slots::MaxSlots, optimistically_confirmed_bank_tracker::BankNotificationSender, + rpc_subscriptions::RpcSubscriptions, + }, + solana_runtime::{ + accounts_background_service::{ + AbsRequestHandler, AbsRequestSender, AccountsBackgroundService, SnapshotRequestHandler, + }, + accounts_db::AccountShrinkThreshold, + bank_forks::BankForks, + commitment::BlockCommitmentCache, + cost_model::CostModel, + snapshot_config::SnapshotConfig, + snapshot_package::{ + AccountsPackageReceiver, AccountsPackageSender, PendingSnapshotPackage, + }, + vote_sender_types::ReplayVoteSender, + }, + solana_sdk::{clock::Slot, pubkey::Pubkey, signature::Keypair}, + std::{ + boxed::Box, + collections::HashSet, + net::UdpSocket, + sync::{ + atomic::AtomicBool, + mpsc::{channel, Receiver}, + Arc, Mutex, RwLock, + }, + thread, }, - thread, }; pub struct Tvu { @@ -383,20 +387,22 @@ impl Tvu { #[cfg(test)] pub mod tests { - use super::*; - use serial_test::serial; - use solana_gossip::cluster_info::{ClusterInfo, Node}; - use solana_ledger::{ - blockstore::BlockstoreSignals, - create_new_tmp_ledger, - genesis_utils::{create_genesis_config, GenesisConfigInfo}, + use { + super::*, + serial_test::serial, + solana_gossip::cluster_info::{ClusterInfo, Node}, + solana_ledger::{ + blockstore::BlockstoreSignals, + create_new_tmp_ledger, + genesis_utils::{create_genesis_config, GenesisConfigInfo}, + }, + solana_poh::poh_recorder::create_test_recorder, + solana_rpc::optimistically_confirmed_bank_tracker::OptimisticallyConfirmedBank, + solana_runtime::bank::Bank, + solana_sdk::signature::{Keypair, Signer}, + solana_streamer::socket::SocketAddrSpace, + std::sync::atomic::Ordering, }; - use solana_poh::poh_recorder::create_test_recorder; - use solana_rpc::optimistically_confirmed_bank_tracker::OptimisticallyConfirmedBank; - use solana_runtime::bank::Bank; - use solana_sdk::signature::{Keypair, Signer}; - use solana_streamer::socket::SocketAddrSpace; - use std::sync::atomic::Ordering; #[ignore] #[test] diff --git a/core/src/unfrozen_gossip_verified_vote_hashes.rs b/core/src/unfrozen_gossip_verified_vote_hashes.rs index e22c90ea61623e..3224b3900f4c2d 100644 --- a/core/src/unfrozen_gossip_verified_vote_hashes.rs +++ b/core/src/unfrozen_gossip_verified_vote_hashes.rs @@ -1,6 +1,8 @@ -use crate::latest_validator_votes_for_frozen_banks::LatestValidatorVotesForFrozenBanks; -use solana_sdk::{clock::Slot, hash::Hash, pubkey::Pubkey}; -use std::collections::{BTreeMap, HashMap}; +use { + crate::latest_validator_votes_for_frozen_banks::LatestValidatorVotesForFrozenBanks, + solana_sdk::{clock::Slot, hash::Hash, pubkey::Pubkey}, + std::collections::{BTreeMap, HashMap}, +}; #[derive(Default)] pub struct UnfrozenGossipVerifiedVoteHashes { diff --git a/core/src/validator.rs b/core/src/validator.rs index 61e403ca9d085f..cfa1752605347a 100644 --- a/core/src/validator.rs +++ b/core/src/validator.rs @@ -1740,11 +1740,12 @@ pub fn is_snapshot_config_valid( #[cfg(test)] mod tests { - use super::*; - use solana_ledger::{create_new_tmp_ledger, genesis_utils::create_genesis_config_with_leader}; - use solana_sdk::genesis_config::create_genesis_config; - use solana_sdk::poh_config::PohConfig; - use std::fs::remove_dir_all; + use { + super::*, + solana_ledger::{create_new_tmp_ledger, genesis_utils::create_genesis_config_with_leader}, + solana_sdk::{genesis_config::create_genesis_config, poh_config::PohConfig}, + std::fs::remove_dir_all, + }; #[test] fn validator_exit() { @@ -1789,8 +1790,10 @@ mod tests { fn test_backup_and_clear_blockstore() { use std::time::Instant; solana_logger::setup(); - use solana_entry::entry; - use solana_ledger::{blockstore, get_tmp_ledger_path}; + use { + solana_entry::entry, + solana_ledger::{blockstore, get_tmp_ledger_path}, + }; let blockstore_path = get_tmp_ledger_path!(); { let blockstore = Blockstore::open(&blockstore_path).unwrap(); diff --git a/core/src/verified_vote_packets.rs b/core/src/verified_vote_packets.rs index 7df699762011f2..13ffe50ec1dc33 100644 --- a/core/src/verified_vote_packets.rs +++ b/core/src/verified_vote_packets.rs @@ -1,16 +1,18 @@ -use crate::{cluster_info_vote_listener::VerifiedLabelVotePacketsReceiver, result::Result}; -use crossbeam_channel::Select; -use solana_perf::packet::Packets; -use solana_runtime::bank::Bank; -use solana_sdk::{ - account::from_account, clock::Slot, hash::Hash, pubkey::Pubkey, signature::Signature, - slot_hashes::SlotHashes, sysvar, -}; -use solana_vote_program::vote_state::Vote; -use std::{ - collections::{BTreeMap, HashMap, HashSet}, - sync::Arc, - time::Duration, +use { + crate::{cluster_info_vote_listener::VerifiedLabelVotePacketsReceiver, result::Result}, + crossbeam_channel::Select, + solana_perf::packet::Packets, + solana_runtime::bank::Bank, + solana_sdk::{ + account::from_account, clock::Slot, hash::Hash, pubkey::Pubkey, signature::Signature, + slot_hashes::SlotHashes, sysvar, + }, + solana_vote_program::vote_state::Vote, + std::{ + collections::{BTreeMap, HashMap, HashSet}, + sync::Arc, + time::Duration, + }, }; const MAX_VOTES_PER_VALIDATOR: usize = 1000; @@ -174,11 +176,13 @@ impl VerifiedVotePackets { #[cfg(test)] mod tests { - use super::*; - use crate::{result::Error, vote_simulator::VoteSimulator}; - use crossbeam_channel::unbounded; - use solana_perf::packet::Packet; - use solana_sdk::slot_hashes::MAX_ENTRIES; + use { + super::*, + crate::{result::Error, vote_simulator::VoteSimulator}, + crossbeam_channel::unbounded, + solana_perf::packet::Packet, + solana_sdk::slot_hashes::MAX_ENTRIES, + }; #[test] fn test_verified_vote_packets_receive_and_process_vote_packets() { diff --git a/core/src/vote_simulator.rs b/core/src/vote_simulator.rs index 43a0ba2d8360ad..0c9e4ca7403346 100644 --- a/core/src/vote_simulator.rs +++ b/core/src/vote_simulator.rs @@ -1,32 +1,34 @@ -use crate::{ - cluster_info_vote_listener::VoteTracker, - cluster_slot_state_verifier::{ - DuplicateSlotsTracker, EpochSlotsFrozenSlots, GossipDuplicateConfirmedSlots, +use { + crate::{ + cluster_info_vote_listener::VoteTracker, + cluster_slot_state_verifier::{ + DuplicateSlotsTracker, EpochSlotsFrozenSlots, GossipDuplicateConfirmedSlots, + }, + cluster_slots::ClusterSlots, + consensus::Tower, + fork_choice::SelectVoteAndResetForkResult, + heaviest_subtree_fork_choice::HeaviestSubtreeForkChoice, + latest_validator_votes_for_frozen_banks::LatestValidatorVotesForFrozenBanks, + progress_map::{ForkProgress, ProgressMap}, + replay_stage::{HeaviestForkFailures, ReplayStage}, + unfrozen_gossip_verified_vote_hashes::UnfrozenGossipVerifiedVoteHashes, }, - cluster_slots::ClusterSlots, - consensus::Tower, - fork_choice::SelectVoteAndResetForkResult, - heaviest_subtree_fork_choice::HeaviestSubtreeForkChoice, - latest_validator_votes_for_frozen_banks::LatestValidatorVotesForFrozenBanks, - progress_map::{ForkProgress, ProgressMap}, - replay_stage::{HeaviestForkFailures, ReplayStage}, - unfrozen_gossip_verified_vote_hashes::UnfrozenGossipVerifiedVoteHashes, -}; -use solana_runtime::{ - accounts_background_service::AbsRequestSender, - bank::Bank, - bank_forks::BankForks, - genesis_utils::{ - create_genesis_config_with_vote_accounts, GenesisConfigInfo, ValidatorVoteKeypairs, + solana_runtime::{ + accounts_background_service::AbsRequestSender, + bank::Bank, + bank_forks::BankForks, + genesis_utils::{ + create_genesis_config_with_vote_accounts, GenesisConfigInfo, ValidatorVoteKeypairs, + }, }, + solana_sdk::{clock::Slot, hash::Hash, pubkey::Pubkey, signature::Signer}, + solana_vote_program::vote_transaction, + std::{ + collections::{HashMap, HashSet}, + sync::{Arc, RwLock}, + }, + trees::{tr, Tree, TreeWalk}, }; -use solana_sdk::{clock::Slot, hash::Hash, pubkey::Pubkey, signature::Signer}; -use solana_vote_program::vote_transaction; -use std::{ - collections::{HashMap, HashSet}, - sync::{Arc, RwLock}, -}; -use trees::{tr, Tree, TreeWalk}; pub struct VoteSimulator { pub validator_keypairs: HashMap, diff --git a/core/src/vote_stake_tracker.rs b/core/src/vote_stake_tracker.rs index feaede7bdcfdba..f51c6a0f616c2b 100644 --- a/core/src/vote_stake_tracker.rs +++ b/core/src/vote_stake_tracker.rs @@ -1,5 +1,4 @@ -use solana_sdk::pubkey::Pubkey; -use std::collections::HashSet; +use {solana_sdk::pubkey::Pubkey, std::collections::HashSet}; #[derive(Default)] pub struct VoteStakeTracker { @@ -49,8 +48,7 @@ impl VoteStakeTracker { #[cfg(test)] mod test { - use super::*; - use solana_runtime::commitment::VOTE_THRESHOLD_SIZE; + use {super::*, solana_runtime::commitment::VOTE_THRESHOLD_SIZE}; #[test] fn test_add_vote_pubkey() { diff --git a/core/src/voting_service.rs b/core/src/voting_service.rs index 5553bc3225548c..647612484f2ae9 100644 --- a/core/src/voting_service.rs +++ b/core/src/voting_service.rs @@ -1,12 +1,14 @@ -use crate::tower_storage::{SavedTower, TowerStorage}; -use solana_gossip::cluster_info::ClusterInfo; -use solana_measure::measure::Measure; -use solana_poh::poh_recorder::PohRecorder; -use solana_runtime::bank_forks::BankForks; -use solana_sdk::{clock::Slot, transaction::Transaction}; -use std::{ - sync::{mpsc::Receiver, Arc, Mutex, RwLock}, - thread::{self, Builder, JoinHandle}, +use { + crate::tower_storage::{SavedTower, TowerStorage}, + solana_gossip::cluster_info::ClusterInfo, + solana_measure::measure::Measure, + solana_poh::poh_recorder::PohRecorder, + solana_runtime::bank_forks::BankForks, + solana_sdk::{clock::Slot, transaction::Transaction}, + std::{ + sync::{mpsc::Receiver, Arc, Mutex, RwLock}, + thread::{self, Builder, JoinHandle}, + }, }; pub enum VoteOp { diff --git a/core/src/window_service.rs b/core/src/window_service.rs index cba1fa158e5b00..e56b333bdb4895 100644 --- a/core/src/window_service.rs +++ b/core/src/window_service.rs @@ -26,10 +26,9 @@ use { solana_rayon_threadlimit::get_thread_count, solana_runtime::{bank::Bank, bank_forks::BankForks}, solana_sdk::{clock::Slot, packet::PACKET_DATA_SIZE, pubkey::Pubkey}, - std::collections::HashSet, std::{ cmp::Reverse, - collections::HashMap, + collections::{HashMap, HashSet}, net::{SocketAddr, UdpSocket}, sync::{ atomic::{AtomicBool, Ordering}, @@ -950,8 +949,10 @@ mod test { #[test] fn test_prune_shreds() { - use crate::serve_repair::ShredRepairType; - use std::net::{IpAddr, Ipv4Addr}; + use { + crate::serve_repair::ShredRepairType, + std::net::{IpAddr, Ipv4Addr}, + }; solana_logger::setup(); let (common, coding) = Shredder::new_coding_shred_header(5, 5, 5, 6, 6, 0); let shred = Shred::new_empty_from_header(common, DataShredHeader::default(), coding); diff --git a/core/tests/fork-selection.rs b/core/tests/fork-selection.rs index cfeda12228486a..21d4ebd4c3289d 100644 --- a/core/tests/fork-selection.rs +++ b/core/tests/fork-selection.rs @@ -74,8 +74,10 @@ #![allow(clippy::integer_arithmetic)] extern crate rand; -use rand::{thread_rng, Rng}; -use std::collections::{HashMap, VecDeque}; +use { + rand::{thread_rng, Rng}, + std::collections::{HashMap, VecDeque}, +}; #[derive(Clone, Default, Debug, Hash, Eq, PartialEq)] pub struct Fork { diff --git a/core/tests/ledger_cleanup.rs b/core/tests/ledger_cleanup.rs index 33dd1dc383f976..cf43483d0cbe64 100644 --- a/core/tests/ledger_cleanup.rs +++ b/core/tests/ledger_cleanup.rs @@ -3,20 +3,28 @@ #[cfg(test)] mod tests { - use log::*; - use solana_core::ledger_cleanup_service::LedgerCleanupService; - use solana_ledger::blockstore::{make_many_slot_entries, Blockstore}; - use solana_ledger::get_tmp_ledger_path; - use solana_ledger::shred::Shred; - use solana_measure::measure::Measure; - use std::collections::VecDeque; - use std::str::FromStr; - use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; - use std::sync::mpsc::channel; - use std::sync::{Arc, Mutex, RwLock}; - use std::thread::{self, Builder, JoinHandle}; - use std::time::{Duration, Instant}; - use systemstat::{CPULoad, Platform, System}; + use { + log::*, + solana_core::ledger_cleanup_service::LedgerCleanupService, + solana_ledger::{ + blockstore::{make_many_slot_entries, Blockstore}, + get_tmp_ledger_path, + shred::Shred, + }, + solana_measure::measure::Measure, + std::{ + collections::VecDeque, + str::FromStr, + sync::{ + atomic::{AtomicBool, AtomicU64, Ordering}, + mpsc::channel, + Arc, Mutex, RwLock, + }, + thread::{self, Builder, JoinHandle}, + time::{Duration, Instant}, + }, + systemstat::{CPULoad, Platform, System}, + }; const DEFAULT_BENCHMARK_SLOTS: u64 = 50; const DEFAULT_BATCH_SIZE: u64 = 1; diff --git a/core/tests/snapshots.rs b/core/tests/snapshots.rs index 1961ce0fb73d63..cab0f0887b72f0 100644 --- a/core/tests/snapshots.rs +++ b/core/tests/snapshots.rs @@ -45,56 +45,59 @@ macro_rules! DEFINE_SNAPSHOT_VERSION_PARAMETERIZED_TEST_FUNCTIONS { #[cfg(test)] mod tests { - use bincode::serialize_into; - use crossbeam_channel::unbounded; - use fs_extra::dir::CopyOptions; - use itertools::Itertools; - use log::{info, trace}; - use solana_core::{ - accounts_hash_verifier::AccountsHashVerifier, - snapshot_packager_service::SnapshotPackagerService, - }; - use solana_gossip::{cluster_info::ClusterInfo, contact_info::ContactInfo}; - use solana_runtime::{ - accounts_background_service::{ - AbsRequestHandler, AbsRequestSender, AccountsBackgroundService, SnapshotRequestHandler, + use { + bincode::serialize_into, + crossbeam_channel::unbounded, + fs_extra::dir::CopyOptions, + itertools::Itertools, + log::{info, trace}, + solana_core::{ + accounts_hash_verifier::AccountsHashVerifier, + snapshot_packager_service::SnapshotPackagerService, }, - accounts_db::{self, ACCOUNTS_DB_CONFIG_FOR_TESTING}, - accounts_index::AccountSecondaryIndexes, - bank::{Bank, BankSlotDelta}, - bank_forks::BankForks, - genesis_utils::{create_genesis_config, GenesisConfigInfo}, - snapshot_archive_info::FullSnapshotArchiveInfo, - snapshot_config::SnapshotConfig, - snapshot_package::{ - AccountsPackage, PendingSnapshotPackage, SnapshotPackage, SnapshotType, + solana_gossip::{cluster_info::ClusterInfo, contact_info::ContactInfo}, + solana_runtime::{ + accounts_background_service::{ + AbsRequestHandler, AbsRequestSender, AccountsBackgroundService, + SnapshotRequestHandler, + }, + accounts_db::{self, ACCOUNTS_DB_CONFIG_FOR_TESTING}, + accounts_index::AccountSecondaryIndexes, + bank::{Bank, BankSlotDelta}, + bank_forks::BankForks, + genesis_utils::{create_genesis_config, GenesisConfigInfo}, + snapshot_archive_info::FullSnapshotArchiveInfo, + snapshot_config::SnapshotConfig, + snapshot_package::{ + AccountsPackage, PendingSnapshotPackage, SnapshotPackage, SnapshotType, + }, + snapshot_utils::{self, ArchiveFormat, SnapshotVersion}, + status_cache::MAX_CACHE_ENTRIES, }, - snapshot_utils::{self, ArchiveFormat, SnapshotVersion}, - status_cache::MAX_CACHE_ENTRIES, - }; - use solana_sdk::{ - clock::Slot, - genesis_config::{ClusterType, GenesisConfig}, - hash::{hashv, Hash}, - pubkey::Pubkey, - signature::{Keypair, Signer}, - system_transaction, - timing::timestamp, - }; - use solana_streamer::socket::SocketAddrSpace; - use std::{ - collections::HashSet, - fs, - io::{Error, ErrorKind}, - path::PathBuf, - sync::{ - atomic::{AtomicBool, Ordering}, - mpsc::channel, - Arc, RwLock, + solana_sdk::{ + clock::Slot, + genesis_config::{ClusterType, GenesisConfig}, + hash::{hashv, Hash}, + pubkey::Pubkey, + signature::{Keypair, Signer}, + system_transaction, + timing::timestamp, + }, + solana_streamer::socket::SocketAddrSpace, + std::{ + collections::HashSet, + fs, + io::{Error, ErrorKind}, + path::PathBuf, + sync::{ + atomic::{AtomicBool, Ordering}, + mpsc::channel, + Arc, RwLock, + }, + time::Duration, }, - time::Duration, + tempfile::TempDir, }; - use tempfile::TempDir; DEFINE_SNAPSHOT_VERSION_PARAMETERIZED_TEST_FUNCTIONS!(V1_2_0, Development, V1_2_0_Development); DEFINE_SNAPSHOT_VERSION_PARAMETERIZED_TEST_FUNCTIONS!(V1_2_0, Devnet, V1_2_0_Devnet); diff --git a/dos/src/main.rs b/dos/src/main.rs index ab8d5f5b515c4e..7ec6274edb0846 100644 --- a/dos/src/main.rs +++ b/dos/src/main.rs @@ -1,16 +1,20 @@ #![allow(clippy::integer_arithmetic)] -use clap::{crate_description, crate_name, value_t, value_t_or_exit, App, Arg}; -use log::*; -use rand::{thread_rng, Rng}; -use solana_client::rpc_client::RpcClient; -use solana_core::serve_repair::RepairProtocol; -use solana_gossip::{contact_info::ContactInfo, gossip_service::discover}; -use solana_sdk::pubkey::Pubkey; -use solana_streamer::socket::SocketAddrSpace; -use std::net::{SocketAddr, UdpSocket}; -use std::process::exit; -use std::str::FromStr; -use std::time::{Duration, Instant}; +use { + clap::{crate_description, crate_name, value_t, value_t_or_exit, App, Arg}, + log::*, + rand::{thread_rng, Rng}, + solana_client::rpc_client::RpcClient, + solana_core::serve_repair::RepairProtocol, + solana_gossip::{contact_info::ContactInfo, gossip_service::discover}, + solana_sdk::pubkey::Pubkey, + solana_streamer::socket::SocketAddrSpace, + std::{ + net::{SocketAddr, UdpSocket}, + process::exit, + str::FromStr, + time::{Duration, Instant}, + }, +}; fn get_repair_contact(nodes: &[ContactInfo]) -> ContactInfo { let source = thread_rng().gen_range(0, nodes.len()); @@ -267,8 +271,7 @@ fn main() { #[cfg(test)] pub mod test { - use super::*; - use solana_sdk::timing::timestamp; + use {super::*, solana_sdk::timing::timestamp}; #[test] fn test_dos() { diff --git a/download-utils/src/lib.rs b/download-utils/src/lib.rs index 4fdd3130e96c0c..407b32f8e8d398 100644 --- a/download-utils/src/lib.rs +++ b/download-utils/src/lib.rs @@ -1,18 +1,21 @@ #![allow(clippy::integer_arithmetic)] -use console::Emoji; -use indicatif::{ProgressBar, ProgressStyle}; -use log::*; -use solana_runtime::{ - snapshot_package::SnapshotType, - snapshot_utils::{self, ArchiveFormat}, +use { + console::Emoji, + indicatif::{ProgressBar, ProgressStyle}, + log::*, + solana_runtime::{ + snapshot_package::SnapshotType, + snapshot_utils::{self, ArchiveFormat}, + }, + solana_sdk::{clock::Slot, genesis_config::DEFAULT_GENESIS_ARCHIVE, hash::Hash}, + std::{ + fs::{self, File}, + io::{self, Read}, + net::SocketAddr, + path::{Path, PathBuf}, + time::{Duration, Instant}, + }, }; -use solana_sdk::{clock::Slot, genesis_config::DEFAULT_GENESIS_ARCHIVE, hash::Hash}; -use std::fs::{self, File}; -use std::io; -use std::io::Read; -use std::net::SocketAddr; -use std::path::{Path, PathBuf}; -use std::time::{Duration, Instant}; static TRUCK: Emoji = Emoji("🚚 ", ""); static SPARKLE: Emoji = Emoji("✨ ", ""); diff --git a/entry/benches/entry_sigverify.rs b/entry/benches/entry_sigverify.rs index 07bf92d6102a61..d2c80a69a7a863 100644 --- a/entry/benches/entry_sigverify.rs +++ b/entry/benches/entry_sigverify.rs @@ -1,19 +1,19 @@ #![feature(test)] extern crate test; -use test::Bencher; - -use std::sync::Arc; - -use solana_perf::test_tx::test_tx; -use solana_sdk::transaction::{ - Result, SanitizedTransaction, TransactionError, TransactionVerificationMode, - VersionedTransaction, +use { + solana_entry::entry::{self, VerifyRecyclers}, + solana_perf::test_tx::test_tx, + solana_sdk::{ + hash::Hash, + transaction::{ + Result, SanitizedTransaction, TransactionError, TransactionVerificationMode, + VersionedTransaction, + }, + }, + std::sync::Arc, + test::Bencher, }; -use solana_entry::entry::{self, VerifyRecyclers}; - -use solana_sdk::hash::Hash; - #[bench] fn bench_gpusigverify(bencher: &mut Bencher) { let entries = (0..131072) diff --git a/entry/src/entry.rs b/entry/src/entry.rs index 79adc57992fd1b..59a607838caa88 100644 --- a/entry/src/entry.rs +++ b/entry/src/entry.rs @@ -2,40 +2,46 @@ //! unique ID that is the hash of the Entry before it, plus the hash of the //! transactions within it. Entries cannot be reordered, and its field `num_hashes` //! represents an approximate amount of time since the last Entry was created. -use crate::poh::Poh; -use dlopen::symbor::{Container, SymBorApi, Symbol}; -use dlopen_derive::SymBorApi; -use log::*; -use rand::{thread_rng, Rng}; -use rayon::prelude::*; -use rayon::ThreadPool; -use serde::{Deserialize, Serialize}; -use solana_measure::measure::Measure; -use solana_merkle_tree::MerkleTree; -use solana_metrics::*; -use solana_perf::{ - cuda_runtime::PinnedVec, - packet::{Packet, Packets, PacketsRecycler, PACKETS_PER_BATCH}, - perf_libs, - recycler::Recycler, - sigverify, +use { + crate::poh::Poh, + dlopen::symbor::{Container, SymBorApi, Symbol}, + dlopen_derive::SymBorApi, + log::*, + rand::{thread_rng, Rng}, + rayon::{prelude::*, ThreadPool}, + serde::{Deserialize, Serialize}, + solana_measure::measure::Measure, + solana_merkle_tree::MerkleTree, + solana_metrics::*, + solana_perf::{ + cuda_runtime::PinnedVec, + packet::{Packet, Packets, PacketsRecycler, PACKETS_PER_BATCH}, + perf_libs, + recycler::Recycler, + sigverify, + }, + solana_rayon_threadlimit::get_thread_count, + solana_sdk::{ + hash::Hash, + packet::Meta, + timing, + transaction::{ + Result, SanitizedTransaction, Transaction, TransactionError, + TransactionVerificationMode, VersionedTransaction, + }, + }, + std::{ + cell::RefCell, + cmp, + ffi::OsStr, + sync::{ + mpsc::{Receiver, Sender}, + Arc, Mutex, Once, + }, + thread::{self, JoinHandle}, + time::Instant, + }, }; -use solana_rayon_threadlimit::get_thread_count; -use solana_sdk::hash::Hash; -use solana_sdk::packet::Meta; -use solana_sdk::timing; -use solana_sdk::transaction::{ - Result, SanitizedTransaction, Transaction, TransactionError, TransactionVerificationMode, - VersionedTransaction, -}; -use std::cell::RefCell; -use std::ffi::OsStr; -use std::sync::mpsc::{Receiver, Sender}; -use std::sync::Once; -use std::sync::{Arc, Mutex}; -use std::thread::JoinHandle; -use std::time::Instant; -use std::{cmp, thread}; thread_local!(static PAR_THREAD_POOL: RefCell = RefCell::new(rayon::ThreadPoolBuilder::new() .num_threads(get_thread_count()) @@ -905,17 +911,16 @@ pub fn next_entry(prev_hash: &Hash, num_hashes: u64, transactions: Vec u #[cfg(test)] mod tests { - use crate::poh::{Poh, PohEntry}; - use matches::assert_matches; - use solana_sdk::hash::{hash, hashv, Hash}; - use std::time::Duration; + use { + crate::poh::{Poh, PohEntry}, + matches::assert_matches, + solana_sdk::hash::{hash, hashv, Hash}, + std::time::Duration, + }; fn verify(initial_hash: Hash, entries: &[(PohEntry, Option)]) -> bool { let mut current_hash = initial_hash; diff --git a/faucet/src/faucet.rs b/faucet/src/faucet.rs index 1ce287ed854734..d57567357dd5ff 100644 --- a/faucet/src/faucet.rs +++ b/faucet/src/faucet.rs @@ -492,9 +492,7 @@ impl LimitByTime for Pubkey { #[cfg(test)] mod tests { - use super::*; - use solana_sdk::system_instruction::SystemInstruction; - use std::time::Duration; + use {super::*, solana_sdk::system_instruction::SystemInstruction, std::time::Duration}; #[test] fn test_check_time_request_limit() { diff --git a/faucet/tests/local-faucet.rs b/faucet/tests/local-faucet.rs index 8629c68ac25dfe..7f2bfe5e2506f6 100644 --- a/faucet/tests/local-faucet.rs +++ b/faucet/tests/local-faucet.rs @@ -1,10 +1,12 @@ -use solana_faucet::faucet::{request_airdrop_transaction, run_local_faucet}; -use solana_sdk::{ - hash::Hash, - message::Message, - signature::{Keypair, Signer}, - system_instruction, - transaction::Transaction, +use { + solana_faucet::faucet::{request_airdrop_transaction, run_local_faucet}, + solana_sdk::{ + hash::Hash, + message::Message, + signature::{Keypair, Signer}, + system_instruction, + transaction::Transaction, + }, }; #[test] diff --git a/frozen-abi/src/abi_digester.rs b/frozen-abi/src/abi_digester.rs index 5eb0bc1a33114d..5a041321f44759 100644 --- a/frozen-abi/src/abi_digester.rs +++ b/frozen-abi/src/abi_digester.rs @@ -1,12 +1,16 @@ -use crate::abi_example::{normalize_type_name, AbiEnumVisitor}; -use crate::hash::{Hash, Hasher}; -use log::*; -use serde::ser::Error as SerdeError; -use serde::ser::*; -use serde::{Serialize, Serializer}; -use std::any::type_name; -use std::io::Write; -use thiserror::Error; +use { + crate::{ + abi_example::{normalize_type_name, AbiEnumVisitor}, + hash::{Hash, Hasher}, + }, + log::*, + serde::{ + ser::{Error as SerdeError, *}, + Serialize, Serializer, + }, + std::{any::type_name, io::Write}, + thiserror::Error, +}; #[derive(Debug)] pub struct AbiDigester { @@ -538,8 +542,7 @@ impl SerializeStructVariant for AbiDigester { #[cfg(test)] mod tests { - use std::collections::HashMap; - use std::sync::atomic::AtomicIsize; + use std::{collections::HashMap, sync::atomic::AtomicIsize}; #[frozen_abi(digest = "CQiGCzsGquChkwffHjZKFqa3tCYtS3GWYRRYX7iDR38Q")] type TestTypeAlias = i32; diff --git a/frozen-abi/src/abi_example.rs b/frozen-abi/src/abi_example.rs index b9bb57b3641914..0bf16b61064260 100644 --- a/frozen-abi/src/abi_example.rs +++ b/frozen-abi/src/abi_example.rs @@ -1,9 +1,9 @@ -use crate::abi_digester::{AbiDigester, DigestError, DigestResult}; - -use log::*; - -use serde::Serialize; -use std::any::type_name; +use { + crate::abi_digester::{AbiDigester, DigestError, DigestResult}, + log::*, + serde::Serialize, + std::any::type_name, +}; pub trait AbiExample: Sized { fn example() -> Self; diff --git a/frozen-abi/src/hash.rs b/frozen-abi/src/hash.rs index 480131b7d17635..58020994623a86 100644 --- a/frozen-abi/src/hash.rs +++ b/frozen-abi/src/hash.rs @@ -1,5 +1,7 @@ -use sha2::{Digest, Sha256}; -use std::{convert::TryFrom, fmt}; +use { + sha2::{Digest, Sha256}, + std::{convert::TryFrom, fmt}, +}; const HASH_BYTES: usize = 32; #[derive(AbiExample)] diff --git a/genesis-utils/src/lib.rs b/genesis-utils/src/lib.rs index 513da409ad20cd..6af1981aac473d 100644 --- a/genesis-utils/src/lib.rs +++ b/genesis-utils/src/lib.rs @@ -1,10 +1,12 @@ -use solana_download_utils::download_genesis_if_missing; -use solana_runtime::hardened_unpack::unpack_genesis_archive; -use solana_sdk::{ - genesis_config::{GenesisConfig, DEFAULT_GENESIS_ARCHIVE}, - hash::Hash, +use { + solana_download_utils::download_genesis_if_missing, + solana_runtime::hardened_unpack::unpack_genesis_archive, + solana_sdk::{ + genesis_config::{GenesisConfig, DEFAULT_GENESIS_ARCHIVE}, + hash::Hash, + }, + std::net::SocketAddr, }; -use std::net::SocketAddr; fn check_genesis_hash( genesis_config: &GenesisConfig, diff --git a/genesis/src/genesis_accounts.rs b/genesis/src/genesis_accounts.rs index 7bf3504402c8e0..1f540d4c6f72b6 100644 --- a/genesis/src/genesis_accounts.rs +++ b/genesis/src/genesis_accounts.rs @@ -1,8 +1,10 @@ -use crate::{ - stakes::{create_and_add_stakes, StakerInfo}, - unlocks::UnlockInfo, +use { + crate::{ + stakes::{create_and_add_stakes, StakerInfo}, + unlocks::UnlockInfo, + }, + solana_sdk::{genesis_config::GenesisConfig, native_token::LAMPORTS_PER_SOL}, }; -use solana_sdk::{genesis_config::GenesisConfig, native_token::LAMPORTS_PER_SOL}; // 9 month schedule is 100% after 9 months const UNLOCKS_ALL_AT_9_MONTHS: UnlockInfo = UnlockInfo { diff --git a/genesis/src/main.rs b/genesis/src/main.rs index e149a00756cbed..06c9e373b979d3 100644 --- a/genesis/src/main.rs +++ b/genesis/src/main.rs @@ -1,41 +1,47 @@ //! A command-line executable for generating the chain's genesis config. #![allow(clippy::integer_arithmetic)] -use clap::{crate_description, crate_name, value_t, value_t_or_exit, App, Arg, ArgMatches}; -use solana_clap_utils::{ - input_parsers::{cluster_type_of, pubkey_of, pubkeys_of, unix_timestamp_from_rfc3339_datetime}, - input_validators::{is_pubkey_or_keypair, is_rfc3339_datetime, is_slot, is_valid_percentage}, -}; -use solana_entry::poh::compute_hashes_per_tick; -use solana_genesis::{genesis_accounts::add_genesis_accounts, Base64Account}; -use solana_ledger::{blockstore::create_new_ledger, blockstore_db::AccessType}; -use solana_runtime::hardened_unpack::MAX_GENESIS_ARCHIVE_UNPACKED_SIZE; -use solana_sdk::{ - account::{Account, AccountSharedData, ReadableAccount, WritableAccount}, - clock, - epoch_schedule::EpochSchedule, - fee_calculator::FeeRateGovernor, - genesis_config::{ClusterType, GenesisConfig}, - inflation::Inflation, - native_token::sol_to_lamports, - poh_config::PohConfig, - pubkey::Pubkey, - rent::Rent, - signature::{Keypair, Signer}, - stake::state::StakeState, - system_program, timing, -}; -use solana_stake_program::stake_state; -use solana_vote_program::vote_state::{self, VoteState}; -use std::{ - collections::HashMap, - error, - fs::File, - io::{self, Read}, - path::PathBuf, - process, - str::FromStr, - time::Duration, +use { + clap::{crate_description, crate_name, value_t, value_t_or_exit, App, Arg, ArgMatches}, + solana_clap_utils::{ + input_parsers::{ + cluster_type_of, pubkey_of, pubkeys_of, unix_timestamp_from_rfc3339_datetime, + }, + input_validators::{ + is_pubkey_or_keypair, is_rfc3339_datetime, is_slot, is_valid_percentage, + }, + }, + solana_entry::poh::compute_hashes_per_tick, + solana_genesis::{genesis_accounts::add_genesis_accounts, Base64Account}, + solana_ledger::{blockstore::create_new_ledger, blockstore_db::AccessType}, + solana_runtime::hardened_unpack::MAX_GENESIS_ARCHIVE_UNPACKED_SIZE, + solana_sdk::{ + account::{Account, AccountSharedData, ReadableAccount, WritableAccount}, + clock, + epoch_schedule::EpochSchedule, + fee_calculator::FeeRateGovernor, + genesis_config::{ClusterType, GenesisConfig}, + inflation::Inflation, + native_token::sol_to_lamports, + poh_config::PohConfig, + pubkey::Pubkey, + rent::Rent, + signature::{Keypair, Signer}, + stake::state::StakeState, + system_program, timing, + }, + solana_stake_program::stake_state, + solana_vote_program::vote_state::{self, VoteState}, + std::{ + collections::HashMap, + error, + fs::File, + io::{self, Read}, + path::PathBuf, + process, + str::FromStr, + time::Duration, + }, }; pub enum AccountFileFormat { @@ -632,12 +638,11 @@ fn main() -> Result<(), Box> { #[cfg(test)] mod tests { - use super::*; - use solana_sdk::genesis_config::GenesisConfig; - use std::collections::HashMap; - use std::fs::remove_file; - use std::io::Write; - use std::path::Path; + use { + super::*, + solana_sdk::genesis_config::GenesisConfig, + std::{collections::HashMap, fs::remove_file, io::Write, path::Path}, + }; #[test] fn test_append_primordial_accounts_to_genesis() { diff --git a/genesis/src/stakes.rs b/genesis/src/stakes.rs index ca2b8da4d9791b..9ee08bf69be8ab 100644 --- a/genesis/src/stakes.rs +++ b/genesis/src/stakes.rs @@ -165,8 +165,7 @@ pub fn create_and_add_stakes( #[cfg(test)] mod tests { - use super::*; - use solana_sdk::rent::Rent; + use {super::*, solana_sdk::rent::Rent}; fn create_and_check_stakes( genesis_config: &mut GenesisConfig, diff --git a/genesis/src/unlocks.rs b/genesis/src/unlocks.rs index c54cf88515298a..0fb1a692076ad8 100644 --- a/genesis/src/unlocks.rs +++ b/genesis/src/unlocks.rs @@ -1,6 +1,8 @@ //! lockups generator -use solana_sdk::{clock::Epoch, epoch_schedule::EpochSchedule, timing::years_as_slots}; -use std::time::Duration; +use { + solana_sdk::{clock::Epoch, epoch_schedule::EpochSchedule, timing::years_as_slots}, + std::time::Duration, +}; #[derive(Debug)] pub struct UnlockInfo { diff --git a/gossip/src/cluster_info.rs b/gossip/src/cluster_info.rs index 65208a347eebd4..edf51db192ade3 100644 --- a/gossip/src/cluster_info.rs +++ b/gossip/src/cluster_info.rs @@ -44,10 +44,12 @@ use { bind_common, bind_common_in_range, bind_in_range, find_available_port_in_range, multi_bind_in_range, PortRange, }, - solana_perf::data_budget::DataBudget, - solana_perf::packet::{ - limited_deserialize, to_packets_with_destination, Packet, Packets, PacketsRecycler, - PACKET_DATA_SIZE, + solana_perf::{ + data_budget::DataBudget, + packet::{ + limited_deserialize, to_packets_with_destination, Packet, Packets, PacketsRecycler, + PACKET_DATA_SIZE, + }, }, solana_rayon_threadlimit::get_thread_count, solana_runtime::bank_forks::BankForks, @@ -84,7 +86,7 @@ use { sync::{ atomic::{AtomicBool, Ordering}, mpsc::{Receiver, RecvTimeoutError, Sender}, - {Arc, Mutex, RwLock, RwLockReadGuard}, + Arc, Mutex, RwLock, RwLockReadGuard, }, thread::{sleep, Builder, JoinHandle}, time::{Duration, Instant}, diff --git a/gossip/src/crds_value.rs b/gossip/src/crds_value.rs index 709de9639e6144..310bdf268f9b98 100644 --- a/gossip/src/crds_value.rs +++ b/gossip/src/crds_value.rs @@ -9,13 +9,13 @@ use { bincode::{serialize, serialized_size}, rand::{CryptoRng, Rng}, serde::de::{Deserialize, Deserializer}, - solana_sdk::sanitize::{Sanitize, SanitizeError}, - solana_sdk::timing::timestamp, solana_sdk::{ clock::Slot, hash::Hash, pubkey::{self, Pubkey}, + sanitize::{Sanitize, SanitizeError}, signature::{Keypair, Signable, Signature, Signer}, + timing::timestamp, transaction::Transaction, }, solana_vote_program::vote_transaction::parse_vote_transaction, diff --git a/gossip/src/duplicate_shred.rs b/gossip/src/duplicate_shred.rs index b018a7c8919fe8..1c9c0ee9951485 100644 --- a/gossip/src/duplicate_shred.rs +++ b/gossip/src/duplicate_shred.rs @@ -280,12 +280,18 @@ impl Sanitize for DuplicateShred { #[cfg(test)] pub(crate) mod tests { - use super::*; - use rand::Rng; - use solana_entry::entry::Entry; - use solana_ledger::shred::Shredder; - use solana_sdk::{hash, signature::Keypair, signature::Signer, system_transaction}; - use std::sync::Arc; + use { + super::*, + rand::Rng, + solana_entry::entry::Entry, + solana_ledger::shred::Shredder, + solana_sdk::{ + hash, + signature::{Keypair, Signer}, + system_transaction, + }, + std::sync::Arc, + }; #[test] fn test_duplicate_shred_header_size() { diff --git a/gossip/src/gossip_service.rs b/gossip/src/gossip_service.rs index b71533bda501fc..db19b3b0ed83b4 100644 --- a/gossip/src/gossip_service.rs +++ b/gossip/src/gossip_service.rs @@ -13,15 +13,14 @@ use { pubkey::Pubkey, signature::{Keypair, Signer}, }, - solana_streamer::socket::SocketAddrSpace, - solana_streamer::streamer, + solana_streamer::{socket::SocketAddrSpace, streamer}, std::{ collections::HashSet, net::{IpAddr, Ipv4Addr, SocketAddr, TcpListener, UdpSocket}, sync::{ atomic::{AtomicBool, Ordering}, mpsc::channel, - {Arc, RwLock}, + Arc, RwLock, }, thread::{self, sleep, JoinHandle}, time::{Duration, Instant}, diff --git a/gossip/src/weighted_shuffle.rs b/gossip/src/weighted_shuffle.rs index 0482396221ad47..ce6aee2c4b7859 100644 --- a/gossip/src/weighted_shuffle.rs +++ b/gossip/src/weighted_shuffle.rs @@ -224,8 +224,10 @@ pub fn weighted_best(weights_and_indexes: &[(u64, usize)], seed: [u8; 32]) -> us #[cfg(test)] mod tests { - use super::*; - use std::{convert::TryInto, iter::repeat_with}; + use { + super::*, + std::{convert::TryInto, iter::repeat_with}, + }; fn weighted_shuffle_slow(rng: &mut R, mut weights: Vec) -> Vec where diff --git a/gossip/tests/gossip.rs b/gossip/tests/gossip.rs index 785cd66f9ed466..c5d5bc12ca19c8 100644 --- a/gossip/tests/gossip.rs +++ b/gossip/tests/gossip.rs @@ -246,11 +246,13 @@ pub fn cluster_info_retransmit() { #[test] #[ignore] pub fn cluster_info_scale() { - use solana_measure::measure::Measure; - use solana_perf::test_tx::test_tx; - use solana_runtime::bank::Bank; - use solana_runtime::genesis_utils::{ - create_genesis_config_with_vote_accounts, ValidatorVoteKeypairs, + use { + solana_measure::measure::Measure, + solana_perf::test_tx::test_tx, + solana_runtime::{ + bank::Bank, + genesis_utils::{create_genesis_config_with_vote_accounts, ValidatorVoteKeypairs}, + }, }; solana_logger::setup(); let exit = Arc::new(AtomicBool::new(false)); diff --git a/install/src/command.rs b/install/src/command.rs index 048abfbb424120..907ca718adafec 100644 --- a/install/src/command.rs +++ b/install/src/command.rs @@ -154,8 +154,7 @@ fn extract_release_archive( archive: &Path, extract_dir: &Path, ) -> Result<(), Box> { - use bzip2::bufread::BzDecoder; - use tar::Archive; + use {bzip2::bufread::BzDecoder, tar::Archive}; let progress_bar = new_spinner_progress_bar(); progress_bar.set_message(format!("{}Extracting...", PACKAGE)); @@ -308,8 +307,7 @@ fn check_env_path_for_bin_dir(config: &Config) { /// Encodes a UTF-8 string as a null-terminated UCS-2 string in bytes #[cfg(windows)] pub fn string_to_winreg_bytes(s: &str) -> Vec { - use std::ffi::OsString; - use std::os::windows::ffi::OsStrExt; + use std::{ffi::OsString, os::windows::ffi::OsStrExt}; let v: Vec<_> = OsString::from(format!("{}\x00", s)).encode_wide().collect(); unsafe { std::slice::from_raw_parts(v.as_ptr() as *const u8, v.len() * 2).to_vec() } } @@ -320,8 +318,7 @@ pub fn string_to_winreg_bytes(s: &str) -> Vec { // conversion. #[cfg(windows)] pub fn string_from_winreg_value(val: &winreg::RegValue) -> Option { - use std::slice; - use winreg::enums::RegType; + use {std::slice, winreg::enums::RegType}; match val.vtype { RegType::REG_SZ | RegType::REG_EXPAND_SZ => { @@ -347,8 +344,10 @@ pub fn string_from_winreg_value(val: &winreg::RegValue) -> Option { // should not mess with it. #[cfg(windows)] fn get_windows_path_var() -> Result, String> { - use winreg::enums::{HKEY_CURRENT_USER, KEY_READ, KEY_WRITE}; - use winreg::RegKey; + use winreg::{ + enums::{HKEY_CURRENT_USER, KEY_READ, KEY_WRITE}, + RegKey, + }; let root = RegKey::predef(HKEY_CURRENT_USER); let environment = root @@ -372,13 +371,19 @@ fn get_windows_path_var() -> Result, String> { #[cfg(windows)] fn add_to_path(new_path: &str) -> bool { - use std::ptr; - use winapi::shared::minwindef::*; - use winapi::um::winuser::{ - SendMessageTimeoutA, HWND_BROADCAST, SMTO_ABORTIFHUNG, WM_SETTINGCHANGE, + use { + std::ptr, + winapi::{ + shared::minwindef::*, + um::winuser::{ + SendMessageTimeoutA, HWND_BROADCAST, SMTO_ABORTIFHUNG, WM_SETTINGCHANGE, + }, + }, + winreg::{ + enums::{RegType, HKEY_CURRENT_USER, KEY_READ, KEY_WRITE}, + RegKey, RegValue, + }, }; - use winreg::enums::{RegType, HKEY_CURRENT_USER, KEY_READ, KEY_WRITE}; - use winreg::{RegKey, RegValue}; let old_path = if let Some(s) = get_windows_path_var().unwrap_or_else(|err| panic!("Unable to get PATH: {}", err)) diff --git a/install/src/config.rs b/install/src/config.rs index db676eb74b3d3e..8ced2420df88aa 100644 --- a/install/src/config.rs +++ b/install/src/config.rs @@ -2,9 +2,11 @@ use { crate::update_manifest::UpdateManifest, serde::{Deserialize, Serialize}, solana_sdk::pubkey::Pubkey, - std::fs::{create_dir_all, File}, - std::io::{self, Write}, - std::path::{Path, PathBuf}, + std::{ + fs::{create_dir_all, File}, + io::{self, Write}, + path::{Path, PathBuf}, + }, }; #[derive(Serialize, Deserialize, Debug, PartialEq)] diff --git a/keygen/src/keygen.rs b/keygen/src/keygen.rs index c7c962a58aa850..951026ce731ae8 100644 --- a/keygen/src/keygen.rs +++ b/keygen/src/keygen.rs @@ -1,37 +1,39 @@ #![allow(clippy::integer_arithmetic)] -use bip39::{Language, Mnemonic, MnemonicType, Seed}; -use clap::{ - crate_description, crate_name, value_t, value_t_or_exit, values_t_or_exit, App, AppSettings, - Arg, ArgMatches, SubCommand, -}; -use solana_clap_utils::{ - input_parsers::STDOUT_OUTFILE_TOKEN, - input_validators::{is_parsable, is_prompt_signer_source}, - keypair::{ - keypair_from_path, keypair_from_seed_phrase, prompt_passphrase, signer_from_path, - SKIP_SEED_PHRASE_VALIDATION_ARG, +use { + bip39::{Language, Mnemonic, MnemonicType, Seed}, + clap::{ + crate_description, crate_name, value_t, value_t_or_exit, values_t_or_exit, App, + AppSettings, Arg, ArgMatches, SubCommand, }, - ArgConstant, DisplayError, -}; -use solana_cli_config::{Config, CONFIG_FILE}; -use solana_remote_wallet::remote_wallet::RemoteWalletManager; -use solana_sdk::{ - instruction::{AccountMeta, Instruction}, - message::Message, - pubkey::{write_pubkey_file, Pubkey}, - signature::{keypair_from_seed, write_keypair, write_keypair_file, Keypair, Signer}, -}; -use std::{ - collections::HashSet, - error, - path::Path, - process::exit, - sync::{ - atomic::{AtomicBool, AtomicU64, Ordering}, - Arc, + solana_clap_utils::{ + input_parsers::STDOUT_OUTFILE_TOKEN, + input_validators::{is_parsable, is_prompt_signer_source}, + keypair::{ + keypair_from_path, keypair_from_seed_phrase, prompt_passphrase, signer_from_path, + SKIP_SEED_PHRASE_VALIDATION_ARG, + }, + ArgConstant, DisplayError, + }, + solana_cli_config::{Config, CONFIG_FILE}, + solana_remote_wallet::remote_wallet::RemoteWalletManager, + solana_sdk::{ + instruction::{AccountMeta, Instruction}, + message::Message, + pubkey::{write_pubkey_file, Pubkey}, + signature::{keypair_from_seed, write_keypair, write_keypair_file, Keypair, Signer}, + }, + std::{ + collections::HashSet, + error, + path::Path, + process::exit, + sync::{ + atomic::{AtomicBool, AtomicU64, Ordering}, + Arc, + }, + thread, + time::Instant, }, - thread, - time::Instant, }; const NO_PASSPHRASE: &str = ""; diff --git a/ledger-tool/tests/basic.rs b/ledger-tool/tests/basic.rs index 4cda481e6ed358..5224c6a34aad39 100644 --- a/ledger-tool/tests/basic.rs +++ b/ledger-tool/tests/basic.rs @@ -1,8 +1,8 @@ -use assert_cmd::prelude::*; -use solana_ledger::create_new_tmp_ledger; -use solana_ledger::genesis_utils::create_genesis_config; -use std::process::Command; -use std::process::Output; +use { + assert_cmd::prelude::*, + solana_ledger::{create_new_tmp_ledger, genesis_utils::create_genesis_config}, + std::process::{Command, Output}, +}; fn run_ledger_tool(args: &[&str]) -> Output { Command::cargo_bin(env!("CARGO_PKG_NAME")) diff --git a/ledger/benches/blockstore.rs b/ledger/benches/blockstore.rs index 42e8c9ca5c7873..ce44f115a64a80 100644 --- a/ledger/benches/blockstore.rs +++ b/ledger/benches/blockstore.rs @@ -3,15 +3,17 @@ extern crate solana_ledger; extern crate test; -use rand::Rng; -use solana_entry::entry::{create_ticks, Entry}; -use solana_ledger::{ - blockstore::{entries_to_test_shreds, Blockstore}, - get_tmp_ledger_path, +use { + rand::Rng, + solana_entry::entry::{create_ticks, Entry}, + solana_ledger::{ + blockstore::{entries_to_test_shreds, Blockstore}, + get_tmp_ledger_path, + }, + solana_sdk::{clock::Slot, hash::Hash}, + std::path::Path, + test::Bencher, }; -use solana_sdk::{clock::Slot, hash::Hash}; -use std::path::Path; -use test::Bencher; // Given some shreds and a ledger at ledger_path, benchmark writing the shreds to the ledger fn bench_write_shreds(bench: &mut Bencher, entries: Vec, ledger_path: &Path) { diff --git a/ledger/benches/protobuf.rs b/ledger/benches/protobuf.rs index e0244efa078684..240674ca012f56 100644 --- a/ledger/benches/protobuf.rs +++ b/ledger/benches/protobuf.rs @@ -2,17 +2,19 @@ #![feature(test)] extern crate test; -use bincode::{deserialize, serialize}; -use solana_ledger::{ - blockstore::Blockstore, - blockstore_db::{columns as cf, LedgerColumn}, - get_tmp_ledger_path, +use { + bincode::{deserialize, serialize}, + solana_ledger::{ + blockstore::Blockstore, + blockstore_db::{columns as cf, LedgerColumn}, + get_tmp_ledger_path, + }, + solana_runtime::bank::RewardType, + solana_sdk::{clock::Slot, pubkey}, + solana_transaction_status::{Reward, Rewards}, + std::path::Path, + test::Bencher, }; -use solana_runtime::bank::RewardType; -use solana_sdk::{clock::Slot, pubkey}; -use solana_transaction_status::{Reward, Rewards}; -use std::path::Path; -use test::Bencher; fn create_rewards() -> Rewards { (0..100) diff --git a/ledger/benches/sigverify_shreds.rs b/ledger/benches/sigverify_shreds.rs index 116e1fd77ae7a4..4a3de44fffe70e 100644 --- a/ledger/benches/sigverify_shreds.rs +++ b/ledger/benches/sigverify_shreds.rs @@ -1,16 +1,19 @@ #![feature(test)] extern crate test; -use solana_ledger::shred::Shred; -use solana_ledger::shred::SIZE_OF_DATA_SHRED_PAYLOAD; -use solana_ledger::sigverify_shreds::{ - sign_shreds_cpu, sign_shreds_gpu, sign_shreds_gpu_pinned_keypair, +use { + solana_ledger::{ + shred::{Shred, SIZE_OF_DATA_SHRED_PAYLOAD}, + sigverify_shreds::{sign_shreds_cpu, sign_shreds_gpu, sign_shreds_gpu_pinned_keypair}, + }, + solana_perf::{ + packet::{Packet, Packets}, + recycler_cache::RecyclerCache, + }, + solana_sdk::signature::Keypair, + std::sync::Arc, + test::Bencher, }; -use solana_perf::packet::{Packet, Packets}; -use solana_perf::recycler_cache::RecyclerCache; -use solana_sdk::signature::Keypair; -use std::sync::Arc; -use test::Bencher; const NUM_PACKETS: usize = 256; const NUM_BATCHES: usize = 1; diff --git a/ledger/src/ancestor_iterator.rs b/ledger/src/ancestor_iterator.rs index e991fd04635fd5..fbc27653776475 100644 --- a/ledger/src/ancestor_iterator.rs +++ b/ledger/src/ancestor_iterator.rs @@ -1,5 +1,7 @@ -use crate::blockstore::*; -use solana_sdk::{clock::Slot, hash::Hash}; +use { + crate::blockstore::*, + solana_sdk::{clock::Slot, hash::Hash}, +}; pub struct AncestorIterator<'a> { current: Option, @@ -74,10 +76,12 @@ impl<'a> Iterator for AncestorIteratorWithHash<'a> { #[cfg(test)] mod tests { - use super::*; - use solana_sdk::hash::Hash; - use std::{collections::HashMap, path::Path}; - use trees::tr; + use { + super::*, + solana_sdk::hash::Hash, + std::{collections::HashMap, path::Path}, + trees::tr, + }; fn setup_forks(ledger_path: &Path) -> Blockstore { let blockstore = Blockstore::open(ledger_path).unwrap(); diff --git a/ledger/src/bank_forks_utils.rs b/ledger/src/bank_forks_utils.rs index e1e9a322cb7c68..ac84e568233b1e 100644 --- a/ledger/src/bank_forks_utils.rs +++ b/ledger/src/bank_forks_utils.rs @@ -1,25 +1,26 @@ -use crate::{ - blockstore::Blockstore, - blockstore_processor::{ - self, BlockstoreProcessorError, BlockstoreProcessorResult, CacheBlockMetaSender, - ProcessOptions, TransactionStatusSender, +use { + crate::{ + blockstore::Blockstore, + blockstore_processor::{ + self, BlockstoreProcessorError, BlockstoreProcessorResult, CacheBlockMetaSender, + ProcessOptions, TransactionStatusSender, + }, + leader_schedule_cache::LeaderScheduleCache, }, - leader_schedule_cache::LeaderScheduleCache, -}; - -use log::*; -use solana_entry::entry::VerifyRecyclers; -use solana_runtime::{ - accounts_update_notifier_interface::AccountsUpdateNotifier, - bank_forks::BankForks, - snapshot_archive_info::SnapshotArchiveInfoGetter, - snapshot_config::SnapshotConfig, - snapshot_hash::{FullSnapshotHash, IncrementalSnapshotHash, StartingSnapshotHashes}, - snapshot_package::AccountsPackageSender, - snapshot_utils, + log::*, + solana_entry::entry::VerifyRecyclers, + solana_runtime::{ + accounts_update_notifier_interface::AccountsUpdateNotifier, + bank_forks::BankForks, + snapshot_archive_info::SnapshotArchiveInfoGetter, + snapshot_config::SnapshotConfig, + snapshot_hash::{FullSnapshotHash, IncrementalSnapshotHash, StartingSnapshotHashes}, + snapshot_package::AccountsPackageSender, + snapshot_utils, + }, + solana_sdk::{clock::Slot, genesis_config::GenesisConfig}, + std::{fs, path::PathBuf, process, result}, }; -use solana_sdk::{clock::Slot, genesis_config::GenesisConfig}; -use std::{fs, path::PathBuf, process, result}; pub type LoadResult = result::Result< ( diff --git a/ledger/src/bigtable_upload.rs b/ledger/src/bigtable_upload.rs index 2288c9c282d984..860a6348bfe43b 100644 --- a/ledger/src/bigtable_upload.rs +++ b/ledger/src/bigtable_upload.rs @@ -1,15 +1,17 @@ -use crate::blockstore::Blockstore; -use log::*; -use solana_measure::measure::Measure; -use solana_sdk::clock::Slot; -use std::{ - collections::HashSet, - result::Result, - sync::{ - atomic::{AtomicBool, Ordering}, - Arc, +use { + crate::blockstore::Blockstore, + log::*, + solana_measure::measure::Measure, + solana_sdk::clock::Slot, + std::{ + collections::HashSet, + result::Result, + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, + }, + time::Duration, }, - time::Duration, }; // Attempt to upload this many blocks in parallel diff --git a/ledger/src/blockstore.rs b/ledger/src/blockstore.rs index eb6d01620f9f96..3c82f70cf4c20d 100644 --- a/ledger/src/blockstore.rs +++ b/ledger/src/blockstore.rs @@ -3914,30 +3914,32 @@ fn adjust_ulimit_nofile(enforce_ulimit_nofile: bool) -> Result<()> { #[cfg(test)] pub mod tests { - use super::*; - use crate::{ - genesis_utils::{create_genesis_config, GenesisConfigInfo}, - leader_schedule::{FixedSchedule, LeaderSchedule}, - shred::{max_ticks_per_n_shreds, DataShredHeader}, - }; - use assert_matches::assert_matches; - use bincode::serialize; - use itertools::Itertools; - use rand::{seq::SliceRandom, thread_rng}; - use solana_account_decoder::parse_token::UiTokenAmount; - use solana_entry::entry::{next_entry, next_entry_mut}; - use solana_runtime::bank::{Bank, RewardType}; - use solana_sdk::{ - hash::{self, hash, Hash}, - instruction::CompiledInstruction, - packet::PACKET_DATA_SIZE, - pubkey::Pubkey, - signature::Signature, - transaction::{Transaction, TransactionError}, + use { + super::*, + crate::{ + genesis_utils::{create_genesis_config, GenesisConfigInfo}, + leader_schedule::{FixedSchedule, LeaderSchedule}, + shred::{max_ticks_per_n_shreds, DataShredHeader}, + }, + assert_matches::assert_matches, + bincode::serialize, + itertools::Itertools, + rand::{seq::SliceRandom, thread_rng}, + solana_account_decoder::parse_token::UiTokenAmount, + solana_entry::entry::{next_entry, next_entry_mut}, + solana_runtime::bank::{Bank, RewardType}, + solana_sdk::{ + hash::{self, hash, Hash}, + instruction::CompiledInstruction, + packet::PACKET_DATA_SIZE, + pubkey::Pubkey, + signature::Signature, + transaction::{Transaction, TransactionError}, + }, + solana_storage_proto::convert::generated, + solana_transaction_status::{InnerInstructions, Reward, Rewards, TransactionTokenBalance}, + std::{sync::mpsc::channel, thread::Builder, time::Duration}, }; - use solana_storage_proto::convert::generated; - use solana_transaction_status::{InnerInstructions, Reward, Rewards, TransactionTokenBalance}; - use std::{sync::mpsc::channel, thread::Builder, time::Duration}; // used for tests only pub(crate) fn make_slot_entries_with_transactions(num_entries: u64) -> Vec { diff --git a/ledger/src/blockstore/blockstore_purge.rs b/ledger/src/blockstore/blockstore_purge.rs index bab308ac16de8e..4daefc53ba3b54 100644 --- a/ledger/src/blockstore/blockstore_purge.rs +++ b/ledger/src/blockstore/blockstore_purge.rs @@ -1,5 +1,4 @@ -use super::*; -use std::time::Instant; +use {super::*, std::time::Instant}; #[derive(Default)] pub struct PurgeStats { @@ -392,16 +391,18 @@ impl Blockstore { #[cfg(test)] pub mod tests { - use super::*; - use crate::{ - blockstore::tests::make_slot_entries_with_transactions, get_tmp_ledger_path_auto_delete, - }; - use bincode::serialize; - use solana_entry::entry::next_entry_mut; - use solana_sdk::{ - hash::{hash, Hash}, - message::Message, - transaction::Transaction, + use { + super::*, + crate::{ + blockstore::tests::make_slot_entries_with_transactions, get_tmp_ledger_path_auto_delete, + }, + bincode::serialize, + solana_entry::entry::next_entry_mut, + solana_sdk::{ + hash::{hash, Hash}, + message::Message, + transaction::Transaction, + }, }; // check that all columns are either empty or start at `min_slot` diff --git a/ledger/src/blockstore_db.rs b/ledger/src/blockstore_db.rs index b81dddd6368160..c7632931f41219 100644 --- a/ledger/src/blockstore_db.rs +++ b/ledger/src/blockstore_db.rs @@ -1,38 +1,38 @@ -use crate::blockstore_meta; -use bincode::{deserialize, serialize}; -use byteorder::{BigEndian, ByteOrder}; -use log::*; -use prost::Message; pub use rocksdb::Direction as IteratorDirection; -use rocksdb::{ - self, - compaction_filter::CompactionFilter, - compaction_filter_factory::{CompactionFilterContext, CompactionFilterFactory}, - ColumnFamily, ColumnFamilyDescriptor, CompactionDecision, DBIterator, DBRawIterator, - DBRecoveryMode, IteratorMode as RocksIteratorMode, Options, WriteBatch as RWriteBatch, DB, -}; - -use serde::de::DeserializeOwned; -use serde::Serialize; -use solana_runtime::hardened_unpack::UnpackError; -use solana_sdk::{ - clock::{Slot, UnixTimestamp}, - pubkey::Pubkey, - signature::Signature, -}; -use solana_storage_proto::convert::generated; -use std::{ - collections::{HashMap, HashSet}, - ffi::{CStr, CString}, - fs, - marker::PhantomData, - path::Path, - sync::{ - atomic::{AtomicU64, Ordering}, - Arc, +use { + crate::blockstore_meta, + bincode::{deserialize, serialize}, + byteorder::{BigEndian, ByteOrder}, + log::*, + prost::Message, + rocksdb::{ + self, + compaction_filter::CompactionFilter, + compaction_filter_factory::{CompactionFilterContext, CompactionFilterFactory}, + ColumnFamily, ColumnFamilyDescriptor, CompactionDecision, DBIterator, DBRawIterator, + DBRecoveryMode, IteratorMode as RocksIteratorMode, Options, WriteBatch as RWriteBatch, DB, + }, + serde::{de::DeserializeOwned, Serialize}, + solana_runtime::hardened_unpack::UnpackError, + solana_sdk::{ + clock::{Slot, UnixTimestamp}, + pubkey::Pubkey, + signature::Signature, + }, + solana_storage_proto::convert::generated, + std::{ + collections::{HashMap, HashSet}, + ffi::{CStr, CString}, + fs, + marker::PhantomData, + path::Path, + sync::{ + atomic::{AtomicU64, Ordering}, + Arc, + }, }, + thiserror::Error, }; -use thiserror::Error; const MAX_WRITE_BUFFER_SIZE: u64 = 256 * 1024 * 1024; // 256MB @@ -1431,8 +1431,7 @@ fn excludes_from_compaction(cf_name: &str) -> bool { #[cfg(test)] pub mod tests { - use super::*; - use crate::blockstore_db::columns::ShredData; + use {super::*, crate::blockstore_db::columns::ShredData}; #[test] fn test_compaction_filter() { diff --git a/ledger/src/blockstore_meta.rs b/ledger/src/blockstore_meta.rs index 323c6f6c4b4a0a..c1b1f4c63494b1 100644 --- a/ledger/src/blockstore_meta.rs +++ b/ledger/src/blockstore_meta.rs @@ -303,9 +303,11 @@ pub struct ProgramCost { #[cfg(test)] mod test { - use super::*; - use rand::{seq::SliceRandom, thread_rng}; - use std::iter::repeat; + use { + super::*, + rand::{seq::SliceRandom, thread_rng}, + std::iter::repeat, + }; #[test] fn test_erasure_meta_status() { diff --git a/ledger/src/blockstore_processor.rs b/ledger/src/blockstore_processor.rs index 9a374d5df9153f..477bc456af4905 100644 --- a/ledger/src/blockstore_processor.rs +++ b/ledger/src/blockstore_processor.rs @@ -1,63 +1,65 @@ -use crate::{ - block_error::BlockError, blockstore::Blockstore, blockstore_db::BlockstoreError, - blockstore_meta::SlotMeta, leader_schedule_cache::LeaderScheduleCache, -}; -use chrono_humanize::{Accuracy, HumanTime, Tense}; -use crossbeam_channel::Sender; -use itertools::Itertools; -use log::*; -use rand::{seq::SliceRandom, thread_rng}; -use rayon::{prelude::*, ThreadPool}; -use solana_entry::entry::{ - self, create_ticks, Entry, EntrySlice, EntryType, EntryVerificationStatus, VerifyRecyclers, -}; -use solana_measure::measure::Measure; -use solana_metrics::{datapoint_error, inc_new_counter_debug}; -use solana_rayon_threadlimit::get_thread_count; -use solana_runtime::{ - accounts_db::{AccountShrinkThreshold, AccountsDbConfig}, - accounts_index::AccountSecondaryIndexes, - accounts_update_notifier_interface::AccountsUpdateNotifier, - bank::{ - Bank, ExecuteTimings, InnerInstructionsList, RentDebits, TransactionBalancesSet, - TransactionExecutionResult, TransactionLogMessages, TransactionResults, +use { + crate::{ + block_error::BlockError, blockstore::Blockstore, blockstore_db::BlockstoreError, + blockstore_meta::SlotMeta, leader_schedule_cache::LeaderScheduleCache, }, - bank_forks::BankForks, - bank_utils, - block_cost_limits::*, - commitment::VOTE_THRESHOLD_SIZE, - snapshot_config::SnapshotConfig, - snapshot_package::{AccountsPackageSender, SnapshotType}, - snapshot_utils::{self, BankFromArchiveTimings}, - transaction_batch::TransactionBatch, - vote_account::VoteAccount, - vote_sender_types::ReplayVoteSender, -}; -use solana_sdk::timing; -use solana_sdk::{ - clock::{Slot, MAX_PROCESSING_AGE}, - feature_set, - genesis_config::GenesisConfig, - hash::Hash, - pubkey::Pubkey, - signature::{Keypair, Signature}, - transaction::{ - Result, SanitizedTransaction, TransactionError, TransactionVerificationMode, - VersionedTransaction, + chrono_humanize::{Accuracy, HumanTime, Tense}, + crossbeam_channel::Sender, + itertools::Itertools, + log::*, + rand::{seq::SliceRandom, thread_rng}, + rayon::{prelude::*, ThreadPool}, + solana_entry::entry::{ + self, create_ticks, Entry, EntrySlice, EntryType, EntryVerificationStatus, VerifyRecyclers, }, + solana_measure::measure::Measure, + solana_metrics::{datapoint_error, inc_new_counter_debug}, + solana_rayon_threadlimit::get_thread_count, + solana_runtime::{ + accounts_db::{AccountShrinkThreshold, AccountsDbConfig}, + accounts_index::AccountSecondaryIndexes, + accounts_update_notifier_interface::AccountsUpdateNotifier, + bank::{ + Bank, ExecuteTimings, InnerInstructionsList, RentDebits, TransactionBalancesSet, + TransactionExecutionResult, TransactionLogMessages, TransactionResults, + }, + bank_forks::BankForks, + bank_utils, + block_cost_limits::*, + commitment::VOTE_THRESHOLD_SIZE, + snapshot_config::SnapshotConfig, + snapshot_package::{AccountsPackageSender, SnapshotType}, + snapshot_utils::{self, BankFromArchiveTimings}, + transaction_batch::TransactionBatch, + vote_account::VoteAccount, + vote_sender_types::ReplayVoteSender, + }, + solana_sdk::{ + clock::{Slot, MAX_PROCESSING_AGE}, + feature_set, + genesis_config::GenesisConfig, + hash::Hash, + pubkey::Pubkey, + signature::{Keypair, Signature}, + timing, + transaction::{ + Result, SanitizedTransaction, TransactionError, TransactionVerificationMode, + VersionedTransaction, + }, + }, + solana_transaction_status::token_balances::{ + collect_token_balances, TransactionTokenBalancesSet, + }, + std::{ + cell::RefCell, + collections::{HashMap, HashSet}, + path::PathBuf, + result, + sync::{Arc, RwLock}, + time::{Duration, Instant}, + }, + thiserror::Error, }; -use solana_transaction_status::token_balances::{ - collect_token_balances, TransactionTokenBalancesSet, -}; -use std::{ - cell::RefCell, - collections::{HashMap, HashSet}, - path::PathBuf, - result, - sync::{Arc, RwLock}, - time::{Duration, Instant}, -}; -use thiserror::Error; // it tracks the block cost available capacity - number of compute-units allowed // by max blockl cost limit @@ -1505,38 +1507,40 @@ pub fn fill_blockstore_slot_with_ticks( #[cfg(test)] pub mod tests { - use super::*; - use crate::genesis_utils::{ - create_genesis_config, create_genesis_config_with_leader, GenesisConfigInfo, - }; - use crossbeam_channel::unbounded; - use matches::assert_matches; - use rand::{thread_rng, Rng}; - use solana_entry::entry::{create_ticks, next_entry, next_entry_mut}; - use solana_runtime::genesis_utils::{ - self, create_genesis_config_with_vote_accounts, ValidatorVoteKeypairs, - }; - use solana_sdk::{ - account::{AccountSharedData, WritableAccount}, - epoch_schedule::EpochSchedule, - hash::Hash, - pubkey::Pubkey, - signature::{Keypair, Signer}, - system_instruction::SystemError, - system_transaction, - transaction::{Transaction, TransactionError}, - }; - use solana_vote_program::{ - self, - vote_state::{VoteState, VoteStateVersions, MAX_LOCKOUT_HISTORY}, - vote_transaction, - }; - use std::{ - collections::BTreeSet, - sync::{mpsc::channel, RwLock}, + use { + super::*, + crate::genesis_utils::{ + create_genesis_config, create_genesis_config_with_leader, GenesisConfigInfo, + }, + crossbeam_channel::unbounded, + matches::assert_matches, + rand::{thread_rng, Rng}, + solana_entry::entry::{create_ticks, next_entry, next_entry_mut}, + solana_runtime::genesis_utils::{ + self, create_genesis_config_with_vote_accounts, ValidatorVoteKeypairs, + }, + solana_sdk::{ + account::{AccountSharedData, WritableAccount}, + epoch_schedule::EpochSchedule, + hash::Hash, + pubkey::Pubkey, + signature::{Keypair, Signer}, + system_instruction::SystemError, + system_transaction, + transaction::{Transaction, TransactionError}, + }, + solana_vote_program::{ + self, + vote_state::{VoteState, VoteStateVersions, MAX_LOCKOUT_HISTORY}, + vote_transaction, + }, + std::{ + collections::BTreeSet, + sync::{mpsc::channel, RwLock}, + }, + tempfile::TempDir, + trees::tr, }; - use tempfile::TempDir; - use trees::tr; fn test_process_blockstore( genesis_config: &GenesisConfig, diff --git a/ledger/src/erasure.rs b/ledger/src/erasure.rs index e2ae7551b92e87..546139812135ec 100644 --- a/ledger/src/erasure.rs +++ b/ledger/src/erasure.rs @@ -109,9 +109,7 @@ impl Session { #[cfg(test)] pub mod test { - use super::*; - use log::*; - use solana_sdk::clock::Slot; + use {super::*, log::*, solana_sdk::clock::Slot}; /// Specifies the contents of a 16-data-shred and 4-coding-shred erasure set /// Exists to be passed to `generate_blockstore_with_coding` diff --git a/ledger/src/leader_schedule.rs b/ledger/src/leader_schedule.rs index 4ba071abcd8408..16d6dcbe72021b 100644 --- a/ledger/src/leader_schedule.rs +++ b/ledger/src/leader_schedule.rs @@ -1,11 +1,10 @@ -use itertools::Itertools; -use rand::distributions::{Distribution, WeightedIndex}; -use rand_chacha::{rand_core::SeedableRng, ChaChaRng}; -use solana_sdk::pubkey::Pubkey; -use std::collections::HashMap; -use std::convert::identity; -use std::ops::Index; -use std::sync::Arc; +use { + itertools::Itertools, + rand::distributions::{Distribution, WeightedIndex}, + rand_chacha::{rand_core::SeedableRng, ChaChaRng}, + solana_sdk::pubkey::Pubkey, + std::{collections::HashMap, convert::identity, ops::Index, sync::Arc}, +}; // Used for testing #[derive(Clone, Debug)] @@ -101,9 +100,7 @@ impl Index for LeaderSchedule { #[cfg(test)] mod tests { - use super::*; - use rand::Rng; - use std::iter::repeat_with; + use {super::*, rand::Rng, std::iter::repeat_with}; #[test] fn test_leader_schedule_index() { diff --git a/ledger/src/leader_schedule_cache.rs b/ledger/src/leader_schedule_cache.rs index e040a95d3560cc..390969e58be329 100644 --- a/ledger/src/leader_schedule_cache.rs +++ b/ledger/src/leader_schedule_cache.rs @@ -1,19 +1,21 @@ -use crate::{ - blockstore::Blockstore, - leader_schedule::{FixedSchedule, LeaderSchedule}, - leader_schedule_utils, -}; -use itertools::Itertools; -use log::*; -use solana_runtime::bank::Bank; -use solana_sdk::{ - clock::{Epoch, Slot}, - epoch_schedule::EpochSchedule, - pubkey::Pubkey, -}; -use std::{ - collections::{hash_map::Entry, HashMap, VecDeque}, - sync::{Arc, RwLock}, +use { + crate::{ + blockstore::Blockstore, + leader_schedule::{FixedSchedule, LeaderSchedule}, + leader_schedule_utils, + }, + itertools::Itertools, + log::*, + solana_runtime::bank::Bank, + solana_sdk::{ + clock::{Epoch, Slot}, + epoch_schedule::EpochSchedule, + pubkey::Pubkey, + }, + std::{ + collections::{hash_map::Entry, HashMap, VecDeque}, + sync::{Arc, RwLock}, + }, }; type CachedSchedules = (HashMap>, VecDeque); @@ -248,24 +250,31 @@ impl LeaderScheduleCache { #[cfg(test)] mod tests { - use super::*; - use crate::{ - blockstore::make_slot_entries, - genesis_utils::{ - bootstrap_validator_stake_lamports, create_genesis_config, - create_genesis_config_with_leader, GenesisConfigInfo, + use { + super::*, + crate::{ + blockstore::make_slot_entries, + genesis_utils::{ + bootstrap_validator_stake_lamports, create_genesis_config, + create_genesis_config_with_leader, GenesisConfigInfo, + }, + get_tmp_ledger_path_auto_delete, + staking_utils::tests::setup_vote_and_stake_accounts, + }, + solana_runtime::bank::Bank, + solana_sdk::{ + clock::NUM_CONSECUTIVE_LEADER_SLOTS, + epoch_schedule::{ + EpochSchedule, DEFAULT_LEADER_SCHEDULE_SLOT_OFFSET, DEFAULT_SLOTS_PER_EPOCH, + MINIMUM_SLOTS_PER_EPOCH, + }, + signature::{Keypair, Signer}, + }, + std::{ + sync::{mpsc::channel, Arc}, + thread::Builder, }, - get_tmp_ledger_path_auto_delete, - staking_utils::tests::setup_vote_and_stake_accounts, - }; - use solana_runtime::bank::Bank; - use solana_sdk::clock::NUM_CONSECUTIVE_LEADER_SLOTS; - use solana_sdk::epoch_schedule::{ - EpochSchedule, DEFAULT_LEADER_SCHEDULE_SLOT_OFFSET, DEFAULT_SLOTS_PER_EPOCH, - MINIMUM_SLOTS_PER_EPOCH, }; - use solana_sdk::signature::{Keypair, Signer}; - use std::{sync::mpsc::channel, sync::Arc, thread::Builder}; #[test] fn test_new_cache() { diff --git a/ledger/src/leader_schedule_utils.rs b/ledger/src/leader_schedule_utils.rs index 3f17dcf5ca39ec..365c3075c3225d 100644 --- a/ledger/src/leader_schedule_utils.rs +++ b/ledger/src/leader_schedule_utils.rs @@ -1,10 +1,11 @@ -use std::collections::HashMap; - -use crate::leader_schedule::LeaderSchedule; -use solana_runtime::bank::Bank; -use solana_sdk::{ - clock::{Epoch, Slot, NUM_CONSECUTIVE_LEADER_SLOTS}, - pubkey::Pubkey, +use { + crate::leader_schedule::LeaderSchedule, + solana_runtime::bank::Bank, + solana_sdk::{ + clock::{Epoch, Slot, NUM_CONSECUTIVE_LEADER_SLOTS}, + pubkey::Pubkey, + }, + std::collections::HashMap, }; /// Return the leader schedule for the given epoch. @@ -78,9 +79,11 @@ fn sort_stakes(stakes: &mut Vec<(Pubkey, u64)>) { #[cfg(test)] mod tests { - use super::*; - use solana_runtime::genesis_utils::{ - bootstrap_validator_stake_lamports, create_genesis_config_with_leader, + use { + super::*, + solana_runtime::genesis_utils::{ + bootstrap_validator_stake_lamports, create_genesis_config_with_leader, + }, }; #[test] diff --git a/ledger/src/next_slots_iterator.rs b/ledger/src/next_slots_iterator.rs index 842fae5cd1f982..5ef9c776ee7c70 100644 --- a/ledger/src/next_slots_iterator.rs +++ b/ledger/src/next_slots_iterator.rs @@ -1,5 +1,7 @@ -use crate::{blockstore::*, blockstore_meta::SlotMeta}; -use solana_sdk::clock::Slot; +use { + crate::{blockstore::*, blockstore_meta::SlotMeta}, + solana_sdk::clock::Slot, +}; pub struct NextSlotsIterator<'a> { pending_slots: Vec, @@ -34,10 +36,10 @@ impl<'a> Iterator for NextSlotsIterator<'a> { #[cfg(test)] mod tests { - use super::*; - use crate::blockstore_processor::fill_blockstore_slot_with_ticks; - use solana_sdk::hash::Hash; - use std::collections::HashSet; + use { + super::*, crate::blockstore_processor::fill_blockstore_slot_with_ticks, + solana_sdk::hash::Hash, std::collections::HashSet, + }; #[test] fn test_next_slots_iterator() { diff --git a/ledger/src/rooted_slot_iterator.rs b/ledger/src/rooted_slot_iterator.rs index 15c2cdb0ecfe5d..5015c7bc536574 100644 --- a/ledger/src/rooted_slot_iterator.rs +++ b/ledger/src/rooted_slot_iterator.rs @@ -1,7 +1,8 @@ -use crate::blockstore_db::Result; -use crate::{blockstore::*, blockstore_meta::SlotMeta}; -use log::*; -use solana_sdk::clock::Slot; +use { + crate::{blockstore::*, blockstore_db::Result, blockstore_meta::SlotMeta}, + log::*, + solana_sdk::clock::Slot, +}; pub struct RootedSlotIterator<'a> { next_slots: Vec, @@ -76,9 +77,10 @@ impl<'a> Iterator for RootedSlotIterator<'a> { #[cfg(test)] mod tests { - use super::*; - use crate::blockstore_processor::fill_blockstore_slot_with_ticks; - use solana_sdk::hash::Hash; + use { + super::*, crate::blockstore_processor::fill_blockstore_slot_with_ticks, + solana_sdk::hash::Hash, + }; #[test] fn test_rooted_slot_iterator() { diff --git a/ledger/src/shred.rs b/ledger/src/shred.rs index 27401d37b67cab..73da3c5da02955 100644 --- a/ledger/src/shred.rs +++ b/ledger/src/shred.rs @@ -1119,15 +1119,17 @@ pub fn verify_test_data_shred( #[cfg(test)] pub mod tests { - use super::*; - use bincode::serialized_size; - use matches::assert_matches; - use rand::{seq::SliceRandom, Rng}; - use solana_sdk::{ - hash::{self, hash}, - shred_version, system_transaction, + use { + super::*, + bincode::serialized_size, + matches::assert_matches, + rand::{seq::SliceRandom, Rng}, + solana_sdk::{ + hash::{self, hash}, + shred_version, system_transaction, + }, + std::{collections::HashSet, convert::TryInto, iter::repeat_with, sync::Arc}, }; - use std::{collections::HashSet, convert::TryInto, iter::repeat_with, sync::Arc}; #[test] fn test_shred_constants() { diff --git a/ledger/src/sigverify_shreds.rs b/ledger/src/sigverify_shreds.rs index d6bf90aaf63a77..0df3d7b6b5cab3 100644 --- a/ledger/src/sigverify_shreds.rs +++ b/ledger/src/sigverify_shreds.rs @@ -1,29 +1,30 @@ #![allow(clippy::implicit_hasher)] -use crate::shred::{ShredType, SIZE_OF_NONCE}; -use rayon::{ - iter::{ - IndexedParallelIterator, IntoParallelIterator, IntoParallelRefMutIterator, ParallelIterator, +use { + crate::shred::{ShredType, SIZE_OF_NONCE}, + rayon::{ + iter::{ + IndexedParallelIterator, IntoParallelIterator, IntoParallelRefMutIterator, + ParallelIterator, + }, + ThreadPool, }, - ThreadPool, -}; -use sha2::{Digest, Sha512}; -use solana_metrics::inc_new_counter_debug; -use solana_perf::{ - cuda_runtime::PinnedVec, - packet::{limited_deserialize, Packet, Packets}, - perf_libs, - recycler_cache::RecyclerCache, - sigverify::{self, batch_size, TxOffset}, -}; -use solana_rayon_threadlimit::get_thread_count; -use solana_sdk::{ - clock::Slot, - pubkey::Pubkey, - signature::Signature, - signature::{Keypair, Signer}, + sha2::{Digest, Sha512}, + solana_metrics::inc_new_counter_debug, + solana_perf::{ + cuda_runtime::PinnedVec, + packet::{limited_deserialize, Packet, Packets}, + perf_libs, + recycler_cache::RecyclerCache, + sigverify::{self, batch_size, TxOffset}, + }, + solana_rayon_threadlimit::get_thread_count, + solana_sdk::{ + clock::Slot, + pubkey::Pubkey, + signature::{Keypair, Signature, Signer}, + }, + std::{collections::HashMap, mem::size_of, sync::Arc}, }; -use std::sync::Arc; -use std::{collections::HashMap, mem::size_of}; pub const SIGN_SHRED_GPU_MIN: usize = 256; @@ -451,9 +452,11 @@ pub fn sign_shreds_gpu( #[cfg(test)] pub mod tests { - use super::*; - use crate::shred::{Shred, Shredder, SIZE_OF_DATA_SHRED_PAYLOAD}; - use solana_sdk::signature::{Keypair, Signer}; + use { + super::*, + crate::shred::{Shred, Shredder, SIZE_OF_DATA_SHRED_PAYLOAD}, + solana_sdk::signature::{Keypair, Signer}, + }; fn run_test_sigverify_shred_cpu(slot: Slot) { solana_logger::setup(); diff --git a/ledger/tests/blockstore.rs b/ledger/tests/blockstore.rs index a645c8fd0cf65e..7f418863d05363 100644 --- a/ledger/tests/blockstore.rs +++ b/ledger/tests/blockstore.rs @@ -1,11 +1,12 @@ -use solana_entry::entry; -use solana_ledger::{ - blockstore::{self, Blockstore}, - get_tmp_ledger_path_auto_delete, +use { + solana_entry::entry, + solana_ledger::{ + blockstore::{self, Blockstore}, + get_tmp_ledger_path_auto_delete, + }, + solana_sdk::hash::Hash, + std::{sync::Arc, thread::Builder}, }; -use solana_sdk::hash::Hash; -use std::sync::Arc; -use std::thread::Builder; #[test] fn test_multiple_threads_insert_shred() { diff --git a/ledger/tests/shred.rs b/ledger/tests/shred.rs index 1d117f275b4967..fe09937734fe8c 100644 --- a/ledger/tests/shred.rs +++ b/ledger/tests/shred.rs @@ -1,19 +1,21 @@ #![allow(clippy::integer_arithmetic)] -use solana_entry::entry::Entry; -use solana_ledger::shred::{ - max_entries_per_n_shred, verify_test_data_shred, Shred, Shredder, - MAX_DATA_SHREDS_PER_FEC_BLOCK, SIZE_OF_DATA_SHRED_PAYLOAD, -}; -use solana_sdk::{ - clock::Slot, - hash::Hash, - signature::{Keypair, Signer}, - system_transaction, -}; -use std::{ - collections::{BTreeMap, HashSet}, - convert::TryInto, - sync::Arc, +use { + solana_entry::entry::Entry, + solana_ledger::shred::{ + max_entries_per_n_shred, verify_test_data_shred, Shred, Shredder, + MAX_DATA_SHREDS_PER_FEC_BLOCK, SIZE_OF_DATA_SHRED_PAYLOAD, + }, + solana_sdk::{ + clock::Slot, + hash::Hash, + signature::{Keypair, Signer}, + system_transaction, + }, + std::{ + collections::{BTreeMap, HashSet}, + convert::TryInto, + sync::Arc, + }, }; type IndexShredsMap = BTreeMap>; diff --git a/local-cluster/src/cluster_tests.rs b/local-cluster/src/cluster_tests.rs index 6730a5084eae8e..1d7892a992175d 100644 --- a/local-cluster/src/cluster_tests.rs +++ b/local-cluster/src/cluster_tests.rs @@ -3,42 +3,44 @@ /// All tests must start from an entry point and a funding keypair and /// discover the rest of the network. use log::*; -use rand::{thread_rng, Rng}; -use rayon::prelude::*; -use solana_client::thin_client::create_client; -use solana_core::consensus::VOTE_THRESHOLD_DEPTH; -use solana_entry::entry::{Entry, EntrySlice}; -use solana_gossip::{ - cluster_info::{self, VALIDATOR_PORT_RANGE}, - contact_info::ContactInfo, - crds_value::{self, CrdsData, CrdsValue}, - gossip_error::GossipError, - gossip_service::discover_cluster, -}; -use solana_ledger::blockstore::Blockstore; -use solana_sdk::{ - client::SyncClient, - clock::{self, Slot, NUM_CONSECUTIVE_LEADER_SLOTS}, - commitment_config::CommitmentConfig, - epoch_schedule::MINIMUM_SLOTS_PER_EPOCH, - exit::Exit, - hash::Hash, - poh_config::PohConfig, - pubkey::Pubkey, - signature::{Keypair, Signature, Signer}, - system_transaction, - timing::{duration_as_ms, timestamp}, - transport::TransportError, -}; -use solana_streamer::socket::SocketAddrSpace; -use solana_vote_program::vote_transaction; -use std::{ - collections::{HashMap, HashSet}, - net::SocketAddr, - path::Path, - sync::{Arc, RwLock}, - thread::sleep, - time::{Duration, Instant}, +use { + rand::{thread_rng, Rng}, + rayon::prelude::*, + solana_client::thin_client::create_client, + solana_core::consensus::VOTE_THRESHOLD_DEPTH, + solana_entry::entry::{Entry, EntrySlice}, + solana_gossip::{ + cluster_info::{self, VALIDATOR_PORT_RANGE}, + contact_info::ContactInfo, + crds_value::{self, CrdsData, CrdsValue}, + gossip_error::GossipError, + gossip_service::discover_cluster, + }, + solana_ledger::blockstore::Blockstore, + solana_sdk::{ + client::SyncClient, + clock::{self, Slot, NUM_CONSECUTIVE_LEADER_SLOTS}, + commitment_config::CommitmentConfig, + epoch_schedule::MINIMUM_SLOTS_PER_EPOCH, + exit::Exit, + hash::Hash, + poh_config::PohConfig, + pubkey::Pubkey, + signature::{Keypair, Signature, Signer}, + system_transaction, + timing::{duration_as_ms, timestamp}, + transport::TransportError, + }, + solana_streamer::socket::SocketAddrSpace, + solana_vote_program::vote_transaction, + std::{ + collections::{HashMap, HashSet}, + net::SocketAddr, + path::Path, + sync::{Arc, RwLock}, + thread::sleep, + time::{Duration, Instant}, + }, }; /// Spend and verify from every node in the network diff --git a/local-cluster/src/local_cluster.rs b/local-cluster/src/local_cluster.rs index 9129773b987548..ba53a3eb140dbd 100644 --- a/local-cluster/src/local_cluster.rs +++ b/local-cluster/src/local_cluster.rs @@ -22,8 +22,7 @@ use { ValidatorVoteKeypairs, }, solana_sdk::{ - account::Account, - account::AccountSharedData, + account::{Account, AccountSharedData}, client::SyncClient, clock::{DEFAULT_DEV_SLOTS_PER_EPOCH, DEFAULT_TICKS_PER_SLOT}, commitment_config::CommitmentConfig, @@ -759,8 +758,7 @@ impl Drop for LocalCluster { #[cfg(test)] mod test { - use super::*; - use solana_sdk::epoch_schedule::MINIMUM_SLOTS_PER_EPOCH; + use {super::*, solana_sdk::epoch_schedule::MINIMUM_SLOTS_PER_EPOCH}; #[test] fn test_local_cluster_start_and_exit() { diff --git a/local-cluster/src/local_cluster_snapshot_utils.rs b/local-cluster/src/local_cluster_snapshot_utils.rs index 7c086d80ea5ae7..1cdf9ef9389b5e 100644 --- a/local-cluster/src/local_cluster_snapshot_utils.rs +++ b/local-cluster/src/local_cluster_snapshot_utils.rs @@ -1,13 +1,15 @@ -use crate::{cluster::Cluster, local_cluster::LocalCluster}; -use log::*; -use solana_runtime::{ - snapshot_archive_info::{ - FullSnapshotArchiveInfo, IncrementalSnapshotArchiveInfo, SnapshotArchiveInfoGetter, +use { + crate::{cluster::Cluster, local_cluster::LocalCluster}, + log::*, + solana_runtime::{ + snapshot_archive_info::{ + FullSnapshotArchiveInfo, IncrementalSnapshotArchiveInfo, SnapshotArchiveInfoGetter, + }, + snapshot_utils, }, - snapshot_utils, + solana_sdk::{client::SyncClient, commitment_config::CommitmentConfig}, + std::{path::Path, thread::sleep, time::Duration}, }; -use solana_sdk::{client::SyncClient, commitment_config::CommitmentConfig}; -use std::{path::Path, thread::sleep, time::Duration}; impl LocalCluster { /// Return the next full snapshot archive info after the cluster's last processed slot diff --git a/local-cluster/src/validator_configs.rs b/local-cluster/src/validator_configs.rs index 3e776116621e33..a38027bc3793c3 100644 --- a/local-cluster/src/validator_configs.rs +++ b/local-cluster/src/validator_configs.rs @@ -1,6 +1,8 @@ -use solana_core::validator::ValidatorConfig; -use solana_sdk::exit::Exit; -use std::sync::{Arc, RwLock}; +use { + solana_core::validator::ValidatorConfig, + solana_sdk::exit::Exit, + std::sync::{Arc, RwLock}, +}; pub fn safe_clone_config(config: &ValidatorConfig) -> ValidatorConfig { ValidatorConfig { diff --git a/local-cluster/tests/local_cluster.rs b/local-cluster/tests/local_cluster.rs index 40a4eff32cc9c0..9df61a5001db5b 100644 --- a/local-cluster/tests/local_cluster.rs +++ b/local-cluster/tests/local_cluster.rs @@ -32,8 +32,7 @@ use { ancestor_iterator::AncestorIterator, blockstore::{Blockstore, PurgeType}, blockstore_db::AccessType, - leader_schedule::FixedSchedule, - leader_schedule::LeaderSchedule, + leader_schedule::{FixedSchedule, LeaderSchedule}, }, solana_local_cluster::{ cluster::{Cluster, ClusterValidatorInfo}, @@ -68,8 +67,10 @@ use { io::Read, iter, path::{Path, PathBuf}, - sync::atomic::{AtomicBool, Ordering}, - sync::Arc, + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, + }, thread::{sleep, Builder, JoinHandle}, time::{Duration, Instant}, }, diff --git a/log-analyzer/src/main.rs b/log-analyzer/src/main.rs index 0b488976b4a626..31ac40fa145df5 100644 --- a/log-analyzer/src/main.rs +++ b/log-analyzer/src/main.rs @@ -1,14 +1,12 @@ #![allow(clippy::integer_arithmetic)] extern crate byte_unit; -use byte_unit::Byte; -use clap::{crate_description, crate_name, value_t_or_exit, App, Arg, ArgMatches, SubCommand}; - -use serde::{Deserialize, Serialize}; -use std::collections::HashMap; -use std::fs; -use std::ops::Sub; -use std::path::PathBuf; +use { + byte_unit::Byte, + clap::{crate_description, crate_name, value_t_or_exit, App, Arg, ArgMatches, SubCommand}, + serde::{Deserialize, Serialize}, + std::{collections::HashMap, fs, ops::Sub, path::PathBuf}, +}; #[derive(Deserialize, Serialize, Debug)] struct IpAddrMapping { diff --git a/logger/src/lib.rs b/logger/src/lib.rs index 9820ea2f8634dc..7977d816a14ba9 100644 --- a/logger/src/lib.rs +++ b/logger/src/lib.rs @@ -1,7 +1,9 @@ //! The `logger` module configures `env_logger` -use lazy_static::lazy_static; -use std::sync::{Arc, RwLock}; +use { + lazy_static::lazy_static, + std::sync::{Arc, RwLock}, +}; lazy_static! { static ref LOGGER: Arc> = diff --git a/measure/src/measure.rs b/measure/src/measure.rs index d64cf61c0ae95c..4e92da4826945a 100644 --- a/measure/src/measure.rs +++ b/measure/src/measure.rs @@ -1,5 +1,7 @@ -use solana_sdk::timing::duration_as_ns; -use std::{fmt, time::Instant}; +use { + solana_sdk::timing::duration_as_ns, + std::{fmt, time::Instant}, +}; #[derive(Debug)] pub struct Measure { @@ -100,9 +102,10 @@ impl fmt::Display for Measure { #[cfg(test)] mod tests { - use super::*; - use std::thread::sleep; - use std::time::Duration; + use { + super::*, + std::{thread::sleep, time::Duration}, + }; #[test] fn test_measure() { diff --git a/merkle-root-bench/src/main.rs b/merkle-root-bench/src/main.rs index 76ec3388dc66fc..26b4d8ffc3edf1 100644 --- a/merkle-root-bench/src/main.rs +++ b/merkle-root-bench/src/main.rs @@ -1,8 +1,10 @@ extern crate log; -use clap::{crate_description, crate_name, value_t, App, Arg}; -use solana_measure::measure::Measure; -use solana_runtime::accounts_hash::AccountsHash; -use solana_sdk::{hash::Hash, pubkey::Pubkey}; +use { + clap::{crate_description, crate_name, value_t, App, Arg}, + solana_measure::measure::Measure, + solana_runtime::accounts_hash::AccountsHash, + solana_sdk::{hash::Hash, pubkey::Pubkey}, +}; fn main() { solana_logger::setup(); diff --git a/metrics/src/counter.rs b/metrics/src/counter.rs index 265cb636f93d62..eb33c25a298d1b 100644 --- a/metrics/src/counter.rs +++ b/metrics/src/counter.rs @@ -211,13 +211,15 @@ impl Counter { } #[cfg(test)] mod tests { - use crate::counter::{Counter, DEFAULT_LOG_RATE, DEFAULT_METRICS_RATE}; - use log::Level; - use log::*; - use serial_test::serial; - use std::env; - use std::sync::atomic::Ordering; - use std::sync::{Once, RwLock}; + use { + crate::counter::{Counter, DEFAULT_LOG_RATE, DEFAULT_METRICS_RATE}, + log::{Level, *}, + serial_test::serial, + std::{ + env, + sync::{atomic::Ordering, Once, RwLock}, + }, + }; fn get_env_lock() -> &'static RwLock<()> { static mut ENV_LOCK: Option> = None; diff --git a/metrics/src/lib.rs b/metrics/src/lib.rs index 01c03a4269d22c..7f5121317ad856 100644 --- a/metrics/src/lib.rs +++ b/metrics/src/lib.rs @@ -3,7 +3,6 @@ pub mod counter; pub mod datapoint; mod metrics; pub use crate::metrics::{flush, query, set_host_id, set_panic_hook, submit}; - use std::sync::Arc; /// A helper that sends the count of created tokens as a datapoint. diff --git a/net-shaper/src/main.rs b/net-shaper/src/main.rs index d5ff9eee2bd4f0..4d47606400c687 100644 --- a/net-shaper/src/main.rs +++ b/net-shaper/src/main.rs @@ -1,14 +1,14 @@ #![allow(clippy::integer_arithmetic)] -use clap::{ - crate_description, crate_name, crate_version, value_t, value_t_or_exit, App, Arg, ArgMatches, - SubCommand, +use { + clap::{ + crate_description, crate_name, crate_version, value_t, value_t_or_exit, App, Arg, + ArgMatches, SubCommand, + }, + rand::{thread_rng, Rng}, + serde::{Deserialize, Serialize}, + std::{fs, io, path::PathBuf}, }; -use rand::{thread_rng, Rng}; -use serde::{Deserialize, Serialize}; -use std::path::PathBuf; -use std::{fs, io}; - #[derive(Deserialize, Serialize, Debug)] struct NetworkInterconnect { pub a: u8, diff --git a/net-utils/src/bin/ip_address_server.rs b/net-utils/src/bin/ip_address_server.rs index dbf55f8edb63a2..4598d248bd110b 100644 --- a/net-utils/src/bin/ip_address_server.rs +++ b/net-utils/src/bin/ip_address_server.rs @@ -1,5 +1,7 @@ -use clap::{App, Arg}; -use std::net::{SocketAddr, TcpListener}; +use { + clap::{App, Arg}, + std::net::{SocketAddr, TcpListener}, +}; fn main() { solana_logger::setup(); diff --git a/net-utils/src/lib.rs b/net-utils/src/lib.rs index 497e08b523c3fe..67efad8aee9417 100644 --- a/net-utils/src/lib.rs +++ b/net-utils/src/lib.rs @@ -380,9 +380,13 @@ fn udp_socket(_reuseaddr: bool) -> io::Result { #[cfg(not(any(windows, target_os = "ios")))] fn udp_socket(reuseaddr: bool) -> io::Result { - use nix::sys::socket::setsockopt; - use nix::sys::socket::sockopt::{ReuseAddr, ReusePort}; - use std::os::unix::io::AsRawFd; + use { + nix::sys::socket::{ + setsockopt, + sockopt::{ReuseAddr, ReusePort}, + }, + std::os::unix::io::AsRawFd, + }; let sock = Socket::new(Domain::IPV4, Type::DGRAM, None)?; let sock_fd = sock.as_raw_fd(); @@ -524,8 +528,7 @@ pub fn find_available_port_in_range(ip_addr: IpAddr, range: PortRange) -> io::Re #[cfg(test)] mod tests { - use super::*; - use std::net::Ipv4Addr; + use {super::*, std::net::Ipv4Addr}; #[test] fn test_response_length() { diff --git a/notifier/src/lib.rs b/notifier/src/lib.rs index 0bb3b0798cc590..274befa89b26f8 100644 --- a/notifier/src/lib.rs +++ b/notifier/src/lib.rs @@ -18,9 +18,11 @@ /// export TWILIO_CONFIG='ACCOUNT=,TOKEN=,TO=,FROM=' /// ``` use log::*; -use reqwest::{blocking::Client, StatusCode}; -use serde_json::json; -use std::{env, str::FromStr, thread::sleep, time::Duration}; +use { + reqwest::{blocking::Client, StatusCode}, + serde_json::json, + std::{env, str::FromStr, thread::sleep, time::Duration}, +}; struct TelegramWebHook { bot_token: String, diff --git a/perf/benches/recycler.rs b/perf/benches/recycler.rs index ed7b36534fe12a..63410ffc856b8d 100644 --- a/perf/benches/recycler.rs +++ b/perf/benches/recycler.rs @@ -2,9 +2,10 @@ extern crate test; -use solana_perf::{packet::PacketsRecycler, recycler::Recycler}; - -use test::Bencher; +use { + solana_perf::{packet::PacketsRecycler, recycler::Recycler}, + test::Bencher, +}; #[bench] fn bench_recycler(bencher: &mut Bencher) { diff --git a/perf/benches/sigverify.rs b/perf/benches/sigverify.rs index bcc487d12dbfc9..a3211cade62b18 100644 --- a/perf/benches/sigverify.rs +++ b/perf/benches/sigverify.rs @@ -2,11 +2,10 @@ extern crate test; -use solana_perf::packet::to_packets_chunked; -use solana_perf::recycler::Recycler; -use solana_perf::sigverify; -use solana_perf::test_tx::test_tx; -use test::Bencher; +use { + solana_perf::{packet::to_packets_chunked, recycler::Recycler, sigverify, test_tx::test_tx}, + test::Bencher, +}; #[bench] fn bench_sigverify(bencher: &mut Bencher) { diff --git a/perf/src/cuda_runtime.rs b/perf/src/cuda_runtime.rs index 8f26529f00e666..81f466c5810377 100644 --- a/perf/src/cuda_runtime.rs +++ b/perf/src/cuda_runtime.rs @@ -5,23 +5,26 @@ // copies from host memory to GPU memory unless the memory is page-pinned and // cannot be paged to disk. The cuda driver provides these interfaces to pin and unpin memory. -use crate::perf_libs; -use crate::recycler::{RecyclerX, Reset}; -use rand::seq::SliceRandom; -use rand::Rng; -use rayon::prelude::*; -use std::ops::{Index, IndexMut}; -use std::slice::{Iter, IterMut, SliceIndex}; -use std::sync::Weak; - -use std::os::raw::c_int; +use { + crate::{ + perf_libs, + recycler::{RecyclerX, Reset}, + }, + rand::{seq::SliceRandom, Rng}, + rayon::prelude::*, + std::{ + ops::{Index, IndexMut}, + os::raw::c_int, + slice::{Iter, IterMut, SliceIndex}, + sync::Weak, + }, +}; const CUDA_SUCCESS: c_int = 0; fn pin(_mem: &mut Vec) { if let Some(api) = perf_libs::api() { - use std::ffi::c_void; - use std::mem::size_of; + use std::{ffi::c_void, mem::size_of}; let ptr = _mem.as_mut_ptr(); let size = _mem.capacity().saturating_mul(size_of::()); diff --git a/perf/src/packet.rs b/perf/src/packet.rs index e73a5ad6b7af25..59f9d8f7dfce34 100644 --- a/perf/src/packet.rs +++ b/perf/src/packet.rs @@ -1,9 +1,11 @@ //! The `packet` module defines data structures and methods to pull data from the network. -use crate::{cuda_runtime::PinnedVec, recycler::Recycler}; -use bincode::config::Options; -use serde::Serialize; pub use solana_sdk::packet::{Meta, Packet, PACKET_DATA_SIZE}; -use std::net::SocketAddr; +use { + crate::{cuda_runtime::PinnedVec, recycler::Recycler}, + bincode::config::Options, + serde::Serialize, + std::net::SocketAddr, +}; pub const NUM_PACKETS: usize = 1024 * 8; @@ -131,10 +133,14 @@ where #[cfg(test)] mod tests { - use super::*; - use solana_sdk::hash::Hash; - use solana_sdk::signature::{Keypair, Signer}; - use solana_sdk::system_transaction; + use { + super::*, + solana_sdk::{ + hash::Hash, + signature::{Keypair, Signer}, + system_transaction, + }, + }; #[test] fn test_to_packets() { diff --git a/perf/src/perf_libs.rs b/perf/src/perf_libs.rs index facb2edd59da97..1f0505b4a4e7dd 100644 --- a/perf/src/perf_libs.rs +++ b/perf/src/perf_libs.rs @@ -1,14 +1,18 @@ -use core::ffi::c_void; -use dlopen::symbor::{Container, SymBorApi, Symbol}; -use dlopen_derive::SymBorApi; -use log::*; -use solana_sdk::packet::Packet; -use std::env; -use std::ffi::OsStr; -use std::fs; -use std::os::raw::{c_int, c_uint}; -use std::path::{Path, PathBuf}; -use std::sync::Once; +use { + core::ffi::c_void, + dlopen::symbor::{Container, SymBorApi, Symbol}, + dlopen_derive::SymBorApi, + log::*, + solana_sdk::packet::Packet, + std::{ + env, + ffi::OsStr, + fs, + os::raw::{c_int, c_uint}, + path::{Path, PathBuf}, + sync::Once, + }, +}; #[repr(C)] pub struct Elems { diff --git a/perf/src/recycler.rs b/perf/src/recycler.rs index 3d394bccf0d1d2..154d8832802f6b 100644 --- a/perf/src/recycler.rs +++ b/perf/src/recycler.rs @@ -1,7 +1,10 @@ -use rand::{thread_rng, Rng}; -use std::sync::atomic::AtomicBool; -use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::{Arc, Mutex, Weak}; +use { + rand::{thread_rng, Rng}, + std::sync::{ + atomic::{AtomicBool, AtomicUsize, Ordering}, + Arc, Mutex, Weak, + }, +}; // A temporary burst in the workload can cause a large number of allocations, // after which they will be recycled and still reside in memory. If the number @@ -179,9 +182,7 @@ impl RecyclerX { #[cfg(test)] mod tests { - use super::*; - use crate::packet::PacketsRecycler; - use std::iter::repeat_with; + use {super::*, crate::packet::PacketsRecycler, std::iter::repeat_with}; impl Reset for u64 { fn reset(&mut self) { diff --git a/perf/src/recycler_cache.rs b/perf/src/recycler_cache.rs index 5dcf77723090f3..cbd723120bc707 100644 --- a/perf/src/recycler_cache.rs +++ b/perf/src/recycler_cache.rs @@ -1,6 +1,4 @@ -use crate::cuda_runtime::PinnedVec; -use crate::recycler::Recycler; -use crate::sigverify::TxOffset; +use crate::{cuda_runtime::PinnedVec, recycler::Recycler, sigverify::TxOffset}; #[derive(Default, Clone)] pub struct RecyclerCache { diff --git a/perf/src/sigverify.rs b/perf/src/sigverify.rs index dc4814e4912b7e..6102c69af1d05f 100644 --- a/perf/src/sigverify.rs +++ b/perf/src/sigverify.rs @@ -4,22 +4,27 @@ //! to the GPU. //! -use crate::cuda_runtime::PinnedVec; -use crate::packet::{Packet, Packets}; -use crate::perf_libs; -use crate::recycler::Recycler; -use rayon::ThreadPool; -use solana_metrics::inc_new_counter_debug; -use solana_rayon_threadlimit::get_thread_count; -use solana_sdk::hash::Hash; -use solana_sdk::message::{MESSAGE_HEADER_LENGTH, MESSAGE_VERSION_PREFIX}; -use solana_sdk::pubkey::Pubkey; -use solana_sdk::short_vec::decode_shortu16_len; -use solana_sdk::signature::Signature; #[cfg(test)] use solana_sdk::transaction::Transaction; -use std::convert::TryFrom; -use std::mem::size_of; +use { + crate::{ + cuda_runtime::PinnedVec, + packet::{Packet, Packets}, + perf_libs, + recycler::Recycler, + }, + rayon::ThreadPool, + solana_metrics::inc_new_counter_debug, + solana_rayon_threadlimit::get_thread_count, + solana_sdk::{ + hash::Hash, + message::{MESSAGE_HEADER_LENGTH, MESSAGE_VERSION_PREFIX}, + pubkey::Pubkey, + short_vec::decode_shortu16_len, + signature::Signature, + }, + std::{convert::TryFrom, mem::size_of}, +}; // Representing key tKeYE4wtowRb8yRroZShTipE18YVnqwXjsSAoNsFU6g const TRACER_KEY_BYTES: [u8; 32] = [ @@ -587,16 +592,21 @@ pub fn make_packet_from_transaction(tx: Transaction) -> Packet { #[cfg(test)] #[allow(clippy::integer_arithmetic)] mod tests { - use super::*; - use crate::packet::{Packet, Packets}; - use crate::sigverify; - use crate::sigverify::PacketOffsets; - use crate::test_tx::{test_multisig_tx, test_tx, vote_tx}; - use bincode::{deserialize, serialize}; - use solana_sdk::instruction::CompiledInstruction; - use solana_sdk::message::{Message, MessageHeader}; - use solana_sdk::signature::{Keypair, Signature}; - use solana_sdk::transaction::Transaction; + use { + super::*, + crate::{ + packet::{Packet, Packets}, + sigverify::{self, PacketOffsets}, + test_tx::{test_multisig_tx, test_tx, vote_tx}, + }, + bincode::{deserialize, serialize}, + solana_sdk::{ + instruction::CompiledInstruction, + message::{Message, MessageHeader}, + signature::{Keypair, Signature}, + transaction::Transaction, + }, + }; const SIG_OFFSET: usize = 1; @@ -1084,10 +1094,12 @@ mod tests { #[test] fn test_get_checked_scalar() { solana_logger::setup(); - use curve25519_dalek::scalar::Scalar; - use rand::{thread_rng, Rng}; - use rayon::prelude::*; - use std::sync::atomic::{AtomicU64, Ordering}; + use { + curve25519_dalek::scalar::Scalar, + rand::{thread_rng, Rng}, + rayon::prelude::*, + std::sync::atomic::{AtomicU64, Ordering}, + }; if perf_libs::api().is_none() { return; @@ -1124,10 +1136,12 @@ mod tests { #[test] fn test_ge_small_order() { solana_logger::setup(); - use curve25519_dalek::edwards::CompressedEdwardsY; - use rand::{thread_rng, Rng}; - use rayon::prelude::*; - use std::sync::atomic::{AtomicU64, Ordering}; + use { + curve25519_dalek::edwards::CompressedEdwardsY, + rand::{thread_rng, Rng}, + rayon::prelude::*, + std::sync::atomic::{AtomicU64, Ordering}, + }; if perf_libs::api().is_none() { return; diff --git a/poh-bench/src/main.rs b/poh-bench/src/main.rs index ec84960af96a53..0cac2074acb8aa 100644 --- a/poh-bench/src/main.rs +++ b/poh-bench/src/main.rs @@ -1,12 +1,14 @@ #![allow(clippy::integer_arithmetic)] -use clap::{crate_description, crate_name, value_t, App, Arg}; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] use solana_entry::entry::{self, create_ticks, init_poh, EntrySlice, VerifyRecyclers}; #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))] use solana_entry::entry::{create_ticks, init_poh, EntrySlice, VerifyRecyclers}; -use solana_measure::measure::Measure; -use solana_perf::perf_libs; -use solana_sdk::hash::hash; +use { + clap::{crate_description, crate_name, value_t, App, Arg}, + solana_measure::measure::Measure, + solana_perf::perf_libs, + solana_sdk::hash::hash, +}; fn main() { solana_logger::setup(); diff --git a/poh/src/poh_recorder.rs b/poh/src/poh_recorder.rs index 581bebc1129eaf..611eaa5cce4dc9 100644 --- a/poh/src/poh_recorder.rs +++ b/poh/src/poh_recorder.rs @@ -33,7 +33,7 @@ use { sync::{ atomic::{AtomicBool, Ordering}, mpsc::{channel, Receiver, SendError, Sender, SyncSender}, - {Arc, Mutex}, + Arc, Mutex, }, time::{Duration, Instant}, }, diff --git a/program-runtime/benches/pre_account.rs b/program-runtime/benches/pre_account.rs index 3252db61898619..11569baf7774e9 100644 --- a/program-runtime/benches/pre_account.rs +++ b/program-runtime/benches/pre_account.rs @@ -2,10 +2,12 @@ extern crate test; -use log::*; -use solana_program_runtime::{pre_account::PreAccount, timings::ExecuteDetailsTimings}; -use solana_sdk::{account::AccountSharedData, pubkey, rent::Rent}; -use test::Bencher; +use { + log::*, + solana_program_runtime::{pre_account::PreAccount, timings::ExecuteDetailsTimings}, + solana_sdk::{account::AccountSharedData, pubkey, rent::Rent}, + test::Bencher, +}; #[bench] fn bench_verify_account_changes_data(bencher: &mut Bencher) { diff --git a/program-runtime/src/instruction_recorder.rs b/program-runtime/src/instruction_recorder.rs index 944b086e6396a5..cdeae6bc0e8323 100644 --- a/program-runtime/src/instruction_recorder.rs +++ b/program-runtime/src/instruction_recorder.rs @@ -1,8 +1,9 @@ -use std::{cell::RefCell, rc::Rc}; - -use solana_sdk::{ - instruction::{CompiledInstruction, Instruction}, - message::SanitizedMessage, +use { + solana_sdk::{ + instruction::{CompiledInstruction, Instruction}, + message::SanitizedMessage, + }, + std::{cell::RefCell, rc::Rc}, }; /// Records and compiles cross-program invoked instructions diff --git a/program-runtime/src/invoke_context.rs b/program-runtime/src/invoke_context.rs index ec4dca5a36a6ba..3d2ec0d5e936db 100644 --- a/program-runtime/src/invoke_context.rs +++ b/program-runtime/src/invoke_context.rs @@ -1,26 +1,29 @@ -use crate::{ - ic_logger_msg, ic_msg, instruction_recorder::InstructionRecorder, log_collector::LogCollector, - native_loader::NativeLoader, pre_account::PreAccount, timings::ExecuteDetailsTimings, -}; -use solana_sdk::{ - account::{AccountSharedData, ReadableAccount}, - account_utils::StateMut, - bpf_loader_upgradeable::{self, UpgradeableLoaderState}, - compute_budget::ComputeBudget, - feature_set::{ - demote_program_write_locks, do_support_realloc, neon_evm_compute_budget, - reject_empty_instruction_without_program, remove_native_loader, requestable_heap_size, - tx_wide_compute_cap, FeatureSet, +use { + crate::{ + ic_logger_msg, ic_msg, instruction_recorder::InstructionRecorder, + log_collector::LogCollector, native_loader::NativeLoader, pre_account::PreAccount, + timings::ExecuteDetailsTimings, + }, + solana_sdk::{ + account::{AccountSharedData, ReadableAccount}, + account_utils::StateMut, + bpf_loader_upgradeable::{self, UpgradeableLoaderState}, + compute_budget::ComputeBudget, + feature_set::{ + demote_program_write_locks, do_support_realloc, neon_evm_compute_budget, + reject_empty_instruction_without_program, remove_native_loader, requestable_heap_size, + tx_wide_compute_cap, FeatureSet, + }, + hash::Hash, + instruction::{AccountMeta, CompiledInstruction, Instruction, InstructionError}, + keyed_account::{create_keyed_accounts_unified, keyed_account_at_index, KeyedAccount}, + message::Message, + pubkey::Pubkey, + rent::Rent, + sysvar::Sysvar, }, - hash::Hash, - instruction::{AccountMeta, CompiledInstruction, Instruction, InstructionError}, - keyed_account::{create_keyed_accounts_unified, keyed_account_at_index, KeyedAccount}, - message::Message, - pubkey::Pubkey, - rent::Rent, - sysvar::Sysvar, + std::{cell::RefCell, collections::HashMap, fmt::Debug, rc::Rc, sync::Arc}, }; -use std::{cell::RefCell, collections::HashMap, fmt::Debug, rc::Rc, sync::Arc}; pub type ProcessInstructionWithContext = fn(usize, &[u8], &mut InvokeContext) -> Result<(), InstructionError>; @@ -936,13 +939,15 @@ pub fn mock_process_instruction( #[cfg(test)] mod tests { - use super::*; - use serde::{Deserialize, Serialize}; - use solana_sdk::{ - account::{ReadableAccount, WritableAccount}, - instruction::{AccountMeta, Instruction, InstructionError}, - message::Message, - native_loader, + use { + super::*, + serde::{Deserialize, Serialize}, + solana_sdk::{ + account::{ReadableAccount, WritableAccount}, + instruction::{AccountMeta, Instruction, InstructionError}, + message::Message, + native_loader, + }, }; #[derive(Debug, Serialize, Deserialize)] diff --git a/program-runtime/src/native_loader.rs b/program-runtime/src/native_loader.rs index 820ed72bb5bbf0..10b4085cc08b1b 100644 --- a/program-runtime/src/native_loader.rs +++ b/program-runtime/src/native_loader.rs @@ -1,28 +1,30 @@ //! Native loader -use crate::invoke_context::InvokeContext; #[cfg(unix)] use libloading::os::unix::*; #[cfg(windows)] use libloading::os::windows::*; -use log::*; -use num_derive::{FromPrimitive, ToPrimitive}; -use serde::Serialize; -use solana_sdk::{ - account::ReadableAccount, - decode_error::DecodeError, - instruction::InstructionError, - keyed_account::{keyed_account_at_index, KeyedAccount}, - native_loader, - pubkey::Pubkey, +use { + crate::invoke_context::InvokeContext, + log::*, + num_derive::{FromPrimitive, ToPrimitive}, + serde::Serialize, + solana_sdk::{ + account::ReadableAccount, + decode_error::DecodeError, + instruction::InstructionError, + keyed_account::{keyed_account_at_index, KeyedAccount}, + native_loader, + pubkey::Pubkey, + }, + std::{ + collections::HashMap, + env, + path::{Path, PathBuf}, + str, + sync::RwLock, + }, + thiserror::Error, }; -use std::{ - collections::HashMap, - env, - path::{Path, PathBuf}, - str, - sync::RwLock, -}; -use thiserror::Error; /// Prototype of a native loader entry point /// diff --git a/program-runtime/src/pre_account.rs b/program-runtime/src/pre_account.rs index 88139bb9840933..93fa2e88fe3c70 100644 --- a/program-runtime/src/pre_account.rs +++ b/program-runtime/src/pre_account.rs @@ -1,16 +1,18 @@ -use crate::timings::ExecuteDetailsTimings; -use solana_sdk::{ - account::{AccountSharedData, ReadableAccount, WritableAccount}, - instruction::InstructionError, - pubkey::Pubkey, - rent::Rent, - system_instruction::MAX_PERMITTED_DATA_LENGTH, - system_program, -}; -use std::{ - cell::{Ref, RefCell}, - fmt::Debug, - rc::Rc, +use { + crate::timings::ExecuteDetailsTimings, + solana_sdk::{ + account::{AccountSharedData, ReadableAccount, WritableAccount}, + instruction::InstructionError, + pubkey::Pubkey, + rent::Rent, + system_instruction::MAX_PERMITTED_DATA_LENGTH, + system_program, + }, + std::{ + cell::{Ref, RefCell}, + fmt::Debug, + rc::Rc, + }, }; // The relevant state of an account before an Instruction executes, used @@ -192,8 +194,10 @@ impl PreAccount { #[cfg(test)] mod tests { - use super::*; - use solana_sdk::{account::Account, instruction::InstructionError, system_program}; + use { + super::*, + solana_sdk::{account::Account, instruction::InstructionError, system_program}, + }; #[test] fn test_is_zeroed() { diff --git a/program-runtime/src/stable_log.rs b/program-runtime/src/stable_log.rs index bd484d555a0275..4806562f29dd7b 100644 --- a/program-runtime/src/stable_log.rs +++ b/program-runtime/src/stable_log.rs @@ -2,10 +2,12 @@ //! //! The format of these log messages should not be modified to avoid breaking downstream consumers //! of program logging -use crate::{ic_logger_msg, log_collector::LogCollector}; -use itertools::Itertools; -use solana_sdk::{instruction::InstructionError, pubkey::Pubkey}; -use std::{cell::RefCell, rc::Rc}; +use { + crate::{ic_logger_msg, log_collector::LogCollector}, + itertools::Itertools, + solana_sdk::{instruction::InstructionError, pubkey::Pubkey}, + std::{cell::RefCell, rc::Rc}, +}; /// Log a program invoke. /// diff --git a/program-runtime/src/timings.rs b/program-runtime/src/timings.rs index 37653616c36a70..a61b621e1a7af4 100644 --- a/program-runtime/src/timings.rs +++ b/program-runtime/src/timings.rs @@ -1,5 +1,4 @@ -use solana_sdk::pubkey::Pubkey; -use std::collections::HashMap; +use {solana_sdk::pubkey::Pubkey, std::collections::HashMap}; #[derive(Default, Debug)] pub struct ProgramTiming { diff --git a/program-test/src/lib.rs b/program-test/src/lib.rs index a9f4753390aeaa..77c4ffdefd241d 100644 --- a/program-test/src/lib.rs +++ b/program-test/src/lib.rs @@ -3,6 +3,8 @@ #[allow(deprecated)] use solana_sdk::sysvar::fees::Fees; +// Export tokio for test clients +pub use tokio; use { async_trait::async_trait, chrono_humanize::{Accuracy, HumanTime, Tense}, @@ -28,8 +30,7 @@ use { fee_calculator::{FeeCalculator, FeeRateGovernor}, genesis_config::{ClusterType, GenesisConfig}, hash::Hash, - instruction::Instruction, - instruction::InstructionError, + instruction::{Instruction, InstructionError}, message::Message, native_token::sol_to_lamports, poh_config::PohConfig, @@ -62,13 +63,8 @@ use { thiserror::Error, tokio::task::JoinHandle, }; - // Export types so test clients can limit their solana crate dependencies -pub use solana_banks_client::BanksClient; -pub use solana_program_runtime::invoke_context::InvokeContext; - -// Export tokio for test clients -pub use tokio; +pub use {solana_banks_client::BanksClient, solana_program_runtime::invoke_context::InvokeContext}; pub mod programs; diff --git a/program-test/tests/builtins.rs b/program-test/tests/builtins.rs index a3505064301a69..1da1b1a3f4b3a6 100644 --- a/program-test/tests/builtins.rs +++ b/program-test/tests/builtins.rs @@ -1,11 +1,12 @@ -use solana_sdk::{ - bpf_loader_upgradeable::{self, UpgradeableLoaderState}, - signature::{Keypair, Signer}, - transaction::Transaction, +use { + solana_program_test::ProgramTest, + solana_sdk::{ + bpf_loader_upgradeable::{self, UpgradeableLoaderState}, + signature::{Keypair, Signer}, + transaction::Transaction, + }, }; -use solana_program_test::ProgramTest; - #[tokio::test] async fn test_bpf_loader_upgradable_present() { // Arrange diff --git a/program-test/tests/fuzz.rs b/program-test/tests/fuzz.rs index 20b0f018b5b5cf..83bb603cc959cd 100644 --- a/program-test/tests/fuzz.rs +++ b/program-test/tests/fuzz.rs @@ -2,8 +2,15 @@ use { solana_banks_client::BanksClient, solana_program_test::{processor, ProgramTest}, solana_sdk::{ - account_info::AccountInfo, entrypoint::ProgramResult, hash::Hash, instruction::Instruction, - msg, pubkey::Pubkey, rent::Rent, signature::Keypair, signature::Signer, system_instruction, + account_info::AccountInfo, + entrypoint::ProgramResult, + hash::Hash, + instruction::Instruction, + msg, + pubkey::Pubkey, + rent::Rent, + signature::{Keypair, Signer}, + system_instruction, transaction::Transaction, }, }; diff --git a/programs/bpf_loader/benches/serialization.rs b/programs/bpf_loader/benches/serialization.rs index 472c7953053aa2..1287f518ee0757 100644 --- a/programs/bpf_loader/benches/serialization.rs +++ b/programs/bpf_loader/benches/serialization.rs @@ -2,16 +2,19 @@ extern crate test; -use solana_bpf_loader_program::serialization::{ - serialize_parameters_aligned, serialize_parameters_unaligned, +use { + solana_bpf_loader_program::serialization::{ + serialize_parameters_aligned, serialize_parameters_unaligned, + }, + solana_sdk::{ + account::{Account, AccountSharedData}, + bpf_loader, + keyed_account::KeyedAccount, + pubkey::Pubkey, + }, + std::cell::RefCell, + test::Bencher, }; -use solana_sdk::{ - account::{Account, AccountSharedData}, - bpf_loader, -}; -use solana_sdk::{keyed_account::KeyedAccount, pubkey::Pubkey}; -use std::cell::RefCell; -use test::Bencher; fn create_inputs() -> ( Pubkey, diff --git a/programs/bpf_loader/build.rs b/programs/bpf_loader/build.rs index e0a09cf7f3c730..1ac6f087f259d2 100644 --- a/programs/bpf_loader/build.rs +++ b/programs/bpf_loader/build.rs @@ -1,10 +1,12 @@ -use regex::Regex; -use std::{ - fs::File, - io::{prelude::*, BufWriter, Read}, - path::PathBuf, - process::exit, - str, +use { + regex::Regex, + std::{ + fs::File, + io::{prelude::*, BufWriter, Read}, + path::PathBuf, + process::exit, + str, + }, }; /** diff --git a/programs/bpf_loader/src/allocator_bump.rs b/programs/bpf_loader/src/allocator_bump.rs index 7d00ced6bb792d..227c88f47cbf37 100644 --- a/programs/bpf_loader/src/allocator_bump.rs +++ b/programs/bpf_loader/src/allocator_bump.rs @@ -1,8 +1,9 @@ -use crate::alloc; - -use alloc::{Alloc, AllocErr}; -use solana_rbpf::aligned_memory::AlignedMemory; -use std::alloc::Layout; +use { + crate::alloc, + alloc::{Alloc, AllocErr}, + solana_rbpf::aligned_memory::AlignedMemory, + std::alloc::Layout, +}; #[derive(Debug)] pub struct BpfAllocator { diff --git a/programs/bpf_loader/src/lib.rs b/programs/bpf_loader/src/lib.rs index c76207f8e61be7..b468b6a27cb4b1 100644 --- a/programs/bpf_loader/src/lib.rs +++ b/programs/bpf_loader/src/lib.rs @@ -8,51 +8,53 @@ pub mod upgradeable; pub mod upgradeable_with_jit; pub mod with_jit; -use crate::{ - serialization::{deserialize_parameters, serialize_parameters}, - syscalls::SyscallError, -}; -use log::{log_enabled, trace, Level::Trace}; -use solana_measure::measure::Measure; -use solana_program_runtime::{ - ic_logger_msg, ic_msg, - invoke_context::{ComputeMeter, Executor, InvokeContext}, - log_collector::LogCollector, - stable_log, -}; -use solana_rbpf::{ - aligned_memory::AlignedMemory, - ebpf::HOST_ALIGN, - elf::Executable, - error::{EbpfError, UserDefinedError}, - static_analysis::Analysis, - verifier::{self, VerifierError}, - vm::{Config, EbpfVm, InstructionMeter}, -}; -use solana_sdk::{ - account::{ReadableAccount, WritableAccount}, - account_utils::State, - bpf_loader, bpf_loader_deprecated, - bpf_loader_upgradeable::{self, UpgradeableLoaderState}, - clock::Clock, - entrypoint::{HEAP_LENGTH, SUCCESS}, - feature_set::{ - do_support_realloc, reduce_required_deploy_balance, - reject_deployment_of_unresolved_syscalls, - reject_section_virtual_address_file_offset_mismatch, requestable_heap_size, - start_verify_shift32_imm, stop_verify_mul64_imm_nonzero, +use { + crate::{ + serialization::{deserialize_parameters, serialize_parameters}, + syscalls::SyscallError, + }, + log::{log_enabled, trace, Level::Trace}, + solana_measure::measure::Measure, + solana_program_runtime::{ + ic_logger_msg, ic_msg, + invoke_context::{ComputeMeter, Executor, InvokeContext}, + log_collector::LogCollector, + stable_log, + }, + solana_rbpf::{ + aligned_memory::AlignedMemory, + ebpf::HOST_ALIGN, + elf::Executable, + error::{EbpfError, UserDefinedError}, + static_analysis::Analysis, + verifier::{self, VerifierError}, + vm::{Config, EbpfVm, InstructionMeter}, + }, + solana_sdk::{ + account::{ReadableAccount, WritableAccount}, + account_utils::State, + bpf_loader, bpf_loader_deprecated, + bpf_loader_upgradeable::{self, UpgradeableLoaderState}, + clock::Clock, + entrypoint::{HEAP_LENGTH, SUCCESS}, + feature_set::{ + do_support_realloc, reduce_required_deploy_balance, + reject_deployment_of_unresolved_syscalls, + reject_section_virtual_address_file_offset_mismatch, requestable_heap_size, + start_verify_shift32_imm, stop_verify_mul64_imm_nonzero, + }, + instruction::{AccountMeta, InstructionError}, + keyed_account::{from_keyed_account, keyed_account_at_index, KeyedAccount}, + loader_instruction::LoaderInstruction, + loader_upgradeable_instruction::UpgradeableLoaderInstruction, + program_utils::limited_deserialize, + pubkey::Pubkey, + rent::Rent, + system_instruction::{self, MAX_PERMITTED_DATA_LENGTH}, }, - instruction::{AccountMeta, InstructionError}, - keyed_account::{from_keyed_account, keyed_account_at_index, KeyedAccount}, - loader_instruction::LoaderInstruction, - loader_upgradeable_instruction::UpgradeableLoaderInstruction, - program_utils::limited_deserialize, - pubkey::Pubkey, - rent::Rent, - system_instruction::{self, MAX_PERMITTED_DATA_LENGTH}, + std::{cell::RefCell, fmt::Debug, rc::Rc, sync::Arc}, + thiserror::Error, }; -use std::{cell::RefCell, fmt::Debug, rc::Rc, sync::Arc}; -use thiserror::Error; solana_sdk::declare_builtin!( solana_sdk::bpf_loader::ID, @@ -1083,30 +1085,32 @@ impl Executor for BpfExecutor { #[cfg(test)] mod tests { - use super::*; - use rand::Rng; - use solana_program_runtime::invoke_context::mock_process_instruction; - use solana_rbpf::vm::SyscallRegistry; - use solana_runtime::{bank::Bank, bank_client::BankClient}; - use solana_sdk::{ - account::{ - create_account_shared_data_for_test as create_account_for_test, AccountSharedData, + use { + super::*, + rand::Rng, + solana_program_runtime::invoke_context::mock_process_instruction, + solana_rbpf::vm::SyscallRegistry, + solana_runtime::{bank::Bank, bank_client::BankClient}, + solana_sdk::{ + account::{ + create_account_shared_data_for_test as create_account_for_test, AccountSharedData, + }, + account_utils::StateMut, + client::SyncClient, + clock::Clock, + feature_set::FeatureSet, + genesis_config::create_genesis_config, + instruction::{AccountMeta, Instruction, InstructionError}, + message::Message, + native_token::LAMPORTS_PER_SOL, + pubkey::Pubkey, + rent::Rent, + signature::{Keypair, Signer}, + system_program, sysvar, + transaction::TransactionError, }, - account_utils::StateMut, - client::SyncClient, - clock::Clock, - feature_set::FeatureSet, - genesis_config::create_genesis_config, - instruction::{AccountMeta, Instruction, InstructionError}, - message::Message, - native_token::LAMPORTS_PER_SOL, - pubkey::Pubkey, - rent::Rent, - signature::{Keypair, Signer}, - system_program, sysvar, - transaction::TransactionError, + std::{cell::RefCell, fs::File, io::Read, ops::Range, rc::Rc, sync::Arc}, }; - use std::{cell::RefCell, fs::File, io::Read, ops::Range, rc::Rc, sync::Arc}; struct TestInstructionMeter { remaining: u64, diff --git a/programs/bpf_loader/src/serialization.rs b/programs/bpf_loader/src/serialization.rs index f3113f855c9d1c..cfde48561aa4ad 100644 --- a/programs/bpf_loader/src/serialization.rs +++ b/programs/bpf_loader/src/serialization.rs @@ -1,15 +1,17 @@ -use byteorder::{ByteOrder, LittleEndian, WriteBytesExt}; -use solana_rbpf::{aligned_memory::AlignedMemory, ebpf::HOST_ALIGN}; -use solana_sdk::{ - account::{ReadableAccount, WritableAccount}, - bpf_loader_deprecated, - entrypoint::{BPF_ALIGN_OF_U128, MAX_PERMITTED_DATA_INCREASE}, - instruction::InstructionError, - keyed_account::KeyedAccount, - pubkey::Pubkey, - system_instruction::MAX_PERMITTED_DATA_LENGTH, +use { + byteorder::{ByteOrder, LittleEndian, WriteBytesExt}, + solana_rbpf::{aligned_memory::AlignedMemory, ebpf::HOST_ALIGN}, + solana_sdk::{ + account::{ReadableAccount, WritableAccount}, + bpf_loader_deprecated, + entrypoint::{BPF_ALIGN_OF_U128, MAX_PERMITTED_DATA_INCREASE}, + instruction::InstructionError, + keyed_account::KeyedAccount, + pubkey::Pubkey, + system_instruction::MAX_PERMITTED_DATA_LENGTH, + }, + std::{io::prelude::*, mem::size_of}, }; -use std::{io::prelude::*, mem::size_of}; /// Look for a duplicate account and return its position if found pub fn is_dup(accounts: &[KeyedAccount], keyed_account: &KeyedAccount) -> (bool, usize) { @@ -312,19 +314,20 @@ pub fn deserialize_parameters_aligned( #[cfg(test)] mod tests { - use super::*; - use solana_program_runtime::invoke_context::{prepare_mock_invoke_context, InvokeContext}; - use solana_sdk::{ - account::{Account, AccountSharedData}, - account_info::AccountInfo, - bpf_loader, - entrypoint::deserialize, - }; - use std::{ - cell::RefCell, - rc::Rc, - // Hide Result from bindgen gets confused about generics in non-generic type declarations - slice::{from_raw_parts, from_raw_parts_mut}, + use { + super::*, + solana_program_runtime::invoke_context::{prepare_mock_invoke_context, InvokeContext}, + solana_sdk::{ + account::{Account, AccountSharedData}, + account_info::AccountInfo, + bpf_loader, + entrypoint::deserialize, + }, + std::{ + cell::RefCell, + rc::Rc, + slice::{from_raw_parts, from_raw_parts_mut}, + }, }; #[test] diff --git a/programs/bpf_loader/src/syscalls.rs b/programs/bpf_loader/src/syscalls.rs index 658f265fe26083..a9aa33f3c54236 100644 --- a/programs/bpf_loader/src/syscalls.rs +++ b/programs/bpf_loader/src/syscalls.rs @@ -1,56 +1,58 @@ -use crate::{alloc, BpfError}; -use alloc::Alloc; -use solana_program_runtime::{ - ic_logger_msg, ic_msg, - invoke_context::{ComputeMeter, InvokeContext}, - stable_log, -}; -use solana_rbpf::{ - aligned_memory::AlignedMemory, - ebpf, - error::EbpfError, - memory_region::{AccessType, MemoryMapping}, - question_mark, - vm::{EbpfVm, SyscallObject, SyscallRegistry}, -}; #[allow(deprecated)] use solana_sdk::sysvar::fees::Fees; -use solana_sdk::{ - account::{AccountSharedData, ReadableAccount, WritableAccount}, - account_info::AccountInfo, - blake3, bpf_loader, bpf_loader_deprecated, bpf_loader_upgradeable, - clock::Clock, - entrypoint::{BPF_ALIGN_OF_U128, MAX_PERMITTED_DATA_INCREASE, SUCCESS}, - epoch_schedule::EpochSchedule, - feature_set::{ - blake3_syscall_enabled, demote_program_write_locks, disable_fees_sysvar, - do_support_realloc, libsecp256k1_0_5_upgrade_enabled, - prevent_calling_precompiles_as_programs, return_data_syscall_enabled, - secp256k1_recover_syscall_enabled, sol_log_data_syscall_enabled, +use { + crate::{alloc, BpfError}, + alloc::Alloc, + solana_program_runtime::{ + ic_logger_msg, ic_msg, + invoke_context::{ComputeMeter, InvokeContext}, + stable_log, }, - hash::{Hasher, HASH_BYTES}, - instruction::{AccountMeta, Instruction, InstructionError}, - keccak, - message::Message, - native_loader, - precompiles::is_precompile, - program::MAX_RETURN_DATA, - pubkey::{Pubkey, PubkeyError, MAX_SEEDS, MAX_SEED_LEN}, - rent::Rent, - secp256k1_recover::{ - Secp256k1RecoverError, SECP256K1_PUBLIC_KEY_LENGTH, SECP256K1_SIGNATURE_LENGTH, + solana_rbpf::{ + aligned_memory::AlignedMemory, + ebpf, + error::EbpfError, + memory_region::{AccessType, MemoryMapping}, + question_mark, + vm::{EbpfVm, SyscallObject, SyscallRegistry}, }, - sysvar::{self, Sysvar, SysvarId}, -}; -use std::{ - alloc::Layout, - cell::{RefCell, RefMut}, - mem::{align_of, size_of}, - rc::Rc, - slice::from_raw_parts_mut, - str::{from_utf8, Utf8Error}, + solana_sdk::{ + account::{AccountSharedData, ReadableAccount, WritableAccount}, + account_info::AccountInfo, + blake3, bpf_loader, bpf_loader_deprecated, bpf_loader_upgradeable, + clock::Clock, + entrypoint::{BPF_ALIGN_OF_U128, MAX_PERMITTED_DATA_INCREASE, SUCCESS}, + epoch_schedule::EpochSchedule, + feature_set::{ + blake3_syscall_enabled, demote_program_write_locks, disable_fees_sysvar, + do_support_realloc, libsecp256k1_0_5_upgrade_enabled, + prevent_calling_precompiles_as_programs, return_data_syscall_enabled, + secp256k1_recover_syscall_enabled, sol_log_data_syscall_enabled, + }, + hash::{Hasher, HASH_BYTES}, + instruction::{AccountMeta, Instruction, InstructionError}, + keccak, + message::Message, + native_loader, + precompiles::is_precompile, + program::MAX_RETURN_DATA, + pubkey::{Pubkey, PubkeyError, MAX_SEEDS, MAX_SEED_LEN}, + rent::Rent, + secp256k1_recover::{ + Secp256k1RecoverError, SECP256K1_PUBLIC_KEY_LENGTH, SECP256K1_SIGNATURE_LENGTH, + }, + sysvar::{self, Sysvar, SysvarId}, + }, + std::{ + alloc::Layout, + cell::{RefCell, RefMut}, + mem::{align_of, size_of}, + rc::Rc, + slice::from_raw_parts_mut, + str::{from_utf8, Utf8Error}, + }, + thiserror::Error as ThisError, }; -use thiserror::Error as ThisError; /// Maximum signers pub const MAX_SIGNERS: usize = 16; @@ -2641,13 +2643,15 @@ impl<'a, 'b> SyscallObject for SyscallLogData<'a, 'b> { #[cfg(test)] mod tests { - use super::*; - use solana_program_runtime::invoke_context::InvokeContext; - use solana_rbpf::{ - ebpf::HOST_ALIGN, memory_region::MemoryRegion, user_error::UserError, vm::Config, + use { + super::*, + solana_program_runtime::invoke_context::InvokeContext, + solana_rbpf::{ + ebpf::HOST_ALIGN, memory_region::MemoryRegion, user_error::UserError, vm::Config, + }, + solana_sdk::{bpf_loader, fee_calculator::FeeCalculator, hash::hashv}, + std::str::FromStr, }; - use solana_sdk::{bpf_loader, fee_calculator::FeeCalculator, hash::hashv}; - use std::str::FromStr; macro_rules! assert_access_violation { ($result:expr, $va:expr, $len:expr) => { diff --git a/programs/compute-budget/src/lib.rs b/programs/compute-budget/src/lib.rs index 872ce1da62c01e..e4636eb7bebef9 100644 --- a/programs/compute-budget/src/lib.rs +++ b/programs/compute-budget/src/lib.rs @@ -1,5 +1,7 @@ -use solana_program_runtime::invoke_context::InvokeContext; -use solana_sdk::instruction::InstructionError; +use { + solana_program_runtime::invoke_context::InvokeContext, + solana_sdk::instruction::InstructionError, +}; pub fn process_instruction( _first_instruction_account: usize, diff --git a/programs/config/src/config_instruction.rs b/programs/config/src/config_instruction.rs index b1869b5d4feb71..773f360973a1fa 100644 --- a/programs/config/src/config_instruction.rs +++ b/programs/config/src/config_instruction.rs @@ -1,9 +1,10 @@ -use crate::id; -use crate::{ConfigKeys, ConfigState}; -use solana_sdk::{ - instruction::{AccountMeta, Instruction}, - pubkey::Pubkey, - system_instruction, +use { + crate::{id, ConfigKeys, ConfigState}, + solana_sdk::{ + instruction::{AccountMeta, Instruction}, + pubkey::Pubkey, + system_instruction, + }, }; fn initialize_account(config_pubkey: &Pubkey) -> Instruction { diff --git a/programs/config/src/config_processor.rs b/programs/config/src/config_processor.rs index 65fe7e2e56a848..bac1f5d407a184 100644 --- a/programs/config/src/config_processor.rs +++ b/programs/config/src/config_processor.rs @@ -1,17 +1,19 @@ //! Config program -use crate::ConfigKeys; -use bincode::deserialize; -use solana_program_runtime::{ic_msg, invoke_context::InvokeContext}; -use solana_sdk::{ - account::{ReadableAccount, WritableAccount}, - feature_set, - instruction::InstructionError, - keyed_account::keyed_account_at_index, - program_utils::limited_deserialize, - pubkey::Pubkey, +use { + crate::ConfigKeys, + bincode::deserialize, + solana_program_runtime::{ic_msg, invoke_context::InvokeContext}, + solana_sdk::{ + account::{ReadableAccount, WritableAccount}, + feature_set, + instruction::InstructionError, + keyed_account::keyed_account_at_index, + program_utils::limited_deserialize, + pubkey::Pubkey, + }, + std::collections::BTreeSet, }; -use std::collections::BTreeSet; pub fn process_instruction( first_instruction_account: usize, @@ -137,18 +139,20 @@ pub fn process_instruction( #[cfg(test)] mod tests { - use super::*; - use crate::{config_instruction, get_config_data, id, ConfigKeys, ConfigState}; - use bincode::serialized_size; - use serde_derive::{Deserialize, Serialize}; - use solana_program_runtime::invoke_context::mock_process_instruction; - use solana_sdk::{ - account::AccountSharedData, - pubkey::Pubkey, - signature::{Keypair, Signer}, - system_instruction::SystemInstruction, + use { + super::*, + crate::{config_instruction, get_config_data, id, ConfigKeys, ConfigState}, + bincode::serialized_size, + serde_derive::{Deserialize, Serialize}, + solana_program_runtime::invoke_context::mock_process_instruction, + solana_sdk::{ + account::AccountSharedData, + pubkey::Pubkey, + signature::{Keypair, Signer}, + system_instruction::SystemInstruction, + }, + std::{cell::RefCell, rc::Rc}, }; - use std::{cell::RefCell, rc::Rc}; fn process_instruction( instruction_data: &[u8], diff --git a/programs/config/src/date_instruction.rs b/programs/config/src/date_instruction.rs index 7bc4ae41450658..4151ed48062b8c 100644 --- a/programs/config/src/date_instruction.rs +++ b/programs/config/src/date_instruction.rs @@ -1,14 +1,16 @@ -use crate::{config_instruction, ConfigState}; /// /// A library for creating a trusted date oracle. /// use bincode::{deserialize, serialized_size}; -use chrono::{ - prelude::{Date, DateTime, TimeZone, Utc}, - serde::ts_seconds, +use { + crate::{config_instruction, ConfigState}, + chrono::{ + prelude::{Date, DateTime, TimeZone, Utc}, + serde::ts_seconds, + }, + serde_derive::{Deserialize, Serialize}, + solana_sdk::{instruction::Instruction, pubkey::Pubkey}, }; -use serde_derive::{Deserialize, Serialize}; -use solana_sdk::{instruction::Instruction, pubkey::Pubkey}; #[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)] pub struct DateConfig { diff --git a/programs/config/src/lib.rs b/programs/config/src/lib.rs index 5658232c36720f..912c69ab2395d8 100644 --- a/programs/config/src/lib.rs +++ b/programs/config/src/lib.rs @@ -3,16 +3,17 @@ pub mod config_instruction; pub mod config_processor; pub mod date_instruction; -use bincode::{deserialize, serialize, serialized_size}; -use serde_derive::{Deserialize, Serialize}; -use solana_sdk::{ - account::{Account, AccountSharedData}, - pubkey::Pubkey, - short_vec, - stake::config::Config as StakeConfig, -}; - pub use solana_sdk::config::program::id; +use { + bincode::{deserialize, serialize, serialized_size}, + serde_derive::{Deserialize, Serialize}, + solana_sdk::{ + account::{Account, AccountSharedData}, + pubkey::Pubkey, + short_vec, + stake::config::Config as StakeConfig, + }, +}; pub trait ConfigState: serde::Serialize + Default { /// Maximum space that the serialized representation will require diff --git a/programs/stake/src/config.rs b/programs/stake/src/config.rs index 7e595a09c02941..d5e48893d36320 100644 --- a/programs/stake/src/config.rs +++ b/programs/stake/src/config.rs @@ -1,20 +1,21 @@ //! config for staking //! carries variables that the stake program cares about -use bincode::deserialize; -use solana_config_program::{create_config_account, get_config_data}; -use solana_sdk::{ - account::{AccountSharedData, ReadableAccount, WritableAccount}, - genesis_config::GenesisConfig, - instruction::InstructionError, - keyed_account::KeyedAccount, - stake::config::{self, Config}, -}; - #[deprecated( since = "1.8.0", note = "Please use `solana_sdk::stake::config` or `solana_program::stake::config` instead" )] pub use solana_sdk::stake::config::*; +use { + bincode::deserialize, + solana_config_program::{create_config_account, get_config_data}, + solana_sdk::{ + account::{AccountSharedData, ReadableAccount, WritableAccount}, + genesis_config::GenesisConfig, + instruction::InstructionError, + keyed_account::KeyedAccount, + stake::config::{self, Config}, + }, +}; pub fn from(account: &T) -> Option { get_config_data(account.data()) @@ -46,9 +47,7 @@ pub fn add_genesis_account(genesis_config: &mut GenesisConfig) -> u64 { #[cfg(test)] mod tests { - use super::*; - use solana_sdk::pubkey::Pubkey; - use std::cell::RefCell; + use {super::*, solana_sdk::pubkey::Pubkey, std::cell::RefCell}; #[test] fn test() { diff --git a/programs/stake/src/lib.rs b/programs/stake/src/lib.rs index 1de5e41071f634..59cbe78232b392 100644 --- a/programs/stake/src/lib.rs +++ b/programs/stake/src/lib.rs @@ -1,7 +1,6 @@ #![cfg_attr(RUSTC_WITH_SPECIALIZATION, feature(min_specialization))] #![allow(clippy::integer_arithmetic)] use solana_sdk::genesis_config::GenesisConfig; - #[deprecated( since = "1.8.0", note = "Please use `solana_sdk::stake::program::id` or `solana_program::stake::program::id` instead" diff --git a/programs/stake/src/stake_instruction.rs b/programs/stake/src/stake_instruction.rs index edfea7e5fba90e..fc2e530f32a797 100644 --- a/programs/stake/src/stake_instruction.rs +++ b/programs/stake/src/stake_instruction.rs @@ -1,3 +1,8 @@ +#[deprecated( + since = "1.8.0", + note = "Please use `solana_sdk::stake::instruction` or `solana_program::stake::instruction` instead" +)] +pub use solana_sdk::stake::instruction::*; use { crate::{config, stake_state::StakeAccount}, log::*, @@ -16,12 +21,6 @@ use { }, }; -#[deprecated( - since = "1.8.0", - note = "Please use `solana_sdk::stake::instruction` or `solana_program::stake::instruction` instead" -)] -pub use solana_sdk::stake::instruction::*; - pub fn process_instruction( first_instruction_account: usize, data: &[u8], @@ -338,25 +337,27 @@ pub fn process_instruction( #[cfg(test)] mod tests { - use super::*; - use crate::stake_state::{Meta, StakeState}; - use bincode::serialize; - use solana_program_runtime::invoke_context::{ - mock_process_instruction, prepare_mock_invoke_context, InvokeContext, - }; - use solana_sdk::{ - account::{self, AccountSharedData}, - instruction::{AccountMeta, Instruction}, - pubkey::Pubkey, - rent::Rent, - stake::{ - config as stake_config, - instruction::{self, LockupArgs}, - state::{Authorized, Lockup, StakeAuthorize}, + use { + super::*, + crate::stake_state::{Meta, StakeState}, + bincode::serialize, + solana_program_runtime::invoke_context::{ + mock_process_instruction, prepare_mock_invoke_context, InvokeContext, + }, + solana_sdk::{ + account::{self, AccountSharedData}, + instruction::{AccountMeta, Instruction}, + pubkey::Pubkey, + rent::Rent, + stake::{ + config as stake_config, + instruction::{self, LockupArgs}, + state::{Authorized, Lockup, StakeAuthorize}, + }, + sysvar::{stake_history::StakeHistory, Sysvar}, }, - sysvar::{stake_history::StakeHistory, Sysvar}, + std::{cell::RefCell, rc::Rc, str::FromStr}, }; - use std::{cell::RefCell, rc::Rc, str::FromStr}; fn create_default_account() -> Rc> { AccountSharedData::new_ref(0, 0, &Pubkey::new_unique()) diff --git a/programs/stake/src/stake_state.rs b/programs/stake/src/stake_state.rs index be02be49ab4014..213c2e70b8039e 100644 --- a/programs/stake/src/stake_state.rs +++ b/programs/stake/src/stake_state.rs @@ -3,6 +3,11 @@ //! * keep track of rewards //! * own mining pools +#[deprecated( + since = "1.8.0", + note = "Please use `solana_sdk::stake::state` or `solana_program::stake::state` instead" +)] +pub use solana_sdk::stake::state::*; use { solana_program_runtime::{ic_msg, invoke_context::InvokeContext}, solana_sdk::{ @@ -25,12 +30,6 @@ use { std::{collections::HashSet, convert::TryFrom}, }; -#[deprecated( - since = "1.8.0", - note = "Please use `solana_sdk::stake::state` or `solana_program::stake::state` instead" -)] -pub use solana_sdk::stake::state::*; - #[derive(Debug)] pub enum SkippedReason { ZeroPoints, @@ -1374,18 +1373,20 @@ fn do_create_account( #[cfg(test)] mod tests { - use super::*; - use proptest::prelude::*; - use solana_program_runtime::invoke_context::InvokeContext; - use solana_sdk::{ - account::{AccountSharedData, WritableAccount}, - clock::UnixTimestamp, - native_token, - pubkey::Pubkey, - system_program, + use { + super::*, + proptest::prelude::*, + solana_program_runtime::invoke_context::InvokeContext, + solana_sdk::{ + account::{AccountSharedData, WritableAccount}, + clock::UnixTimestamp, + native_token, + pubkey::Pubkey, + system_program, + }, + solana_vote_program::vote_state, + std::{cell::RefCell, iter::FromIterator}, }; - use solana_vote_program::vote_state; - use std::{cell::RefCell, iter::FromIterator}; #[test] fn test_authorized_authorize() { diff --git a/programs/vote/src/authorized_voters.rs b/programs/vote/src/authorized_voters.rs index 134d06b6b48ff3..1951e354503f08 100644 --- a/programs/vote/src/authorized_voters.rs +++ b/programs/vote/src/authorized_voters.rs @@ -1,7 +1,9 @@ -use log::*; -use serde_derive::{Deserialize, Serialize}; -use solana_sdk::{clock::Epoch, pubkey::Pubkey}; -use std::collections::BTreeMap; +use { + log::*, + serde_derive::{Deserialize, Serialize}, + solana_sdk::{clock::Epoch, pubkey::Pubkey}, + std::collections::BTreeMap, +}; #[derive(Debug, Default, Serialize, Deserialize, PartialEq, Eq, Clone, AbiExample)] pub struct AuthorizedVoters { diff --git a/programs/vote/src/vote_instruction.rs b/programs/vote/src/vote_instruction.rs index 18a8c88b14c48a..e9bd4a7cf49132 100644 --- a/programs/vote/src/vote_instruction.rs +++ b/programs/vote/src/vote_instruction.rs @@ -1,28 +1,30 @@ //! Vote program //! Receive and processes votes from validators -use crate::{ - id, - vote_state::{self, Vote, VoteAuthorize, VoteInit, VoteState}, +use { + crate::{ + id, + vote_state::{self, Vote, VoteAuthorize, VoteInit, VoteState}, + }, + log::*, + num_derive::{FromPrimitive, ToPrimitive}, + serde_derive::{Deserialize, Serialize}, + solana_metrics::inc_new_counter_info, + solana_program_runtime::invoke_context::InvokeContext, + solana_sdk::{ + decode_error::DecodeError, + feature_set, + hash::Hash, + instruction::{AccountMeta, Instruction, InstructionError}, + keyed_account::{from_keyed_account, get_signers, keyed_account_at_index, KeyedAccount}, + program_utils::limited_deserialize, + pubkey::Pubkey, + system_instruction, + sysvar::{self, clock::Clock, slot_hashes::SlotHashes}, + }, + std::collections::HashSet, + thiserror::Error, }; -use log::*; -use num_derive::{FromPrimitive, ToPrimitive}; -use serde_derive::{Deserialize, Serialize}; -use solana_metrics::inc_new_counter_info; -use solana_program_runtime::invoke_context::InvokeContext; -use solana_sdk::{ - decode_error::DecodeError, - feature_set, - hash::Hash, - instruction::{AccountMeta, Instruction, InstructionError}, - keyed_account::{from_keyed_account, get_signers, keyed_account_at_index, KeyedAccount}, - program_utils::limited_deserialize, - pubkey::Pubkey, - system_instruction, - sysvar::{self, clock::Clock, slot_hashes::SlotHashes}, -}; -use std::collections::HashSet; -use thiserror::Error; /// Reasons the stake might have had an error #[derive(Error, Debug, Clone, PartialEq, FromPrimitive, ToPrimitive)] @@ -405,15 +407,16 @@ pub fn process_instruction( #[cfg(test)] mod tests { - use super::*; - use bincode::serialize; - use solana_program_runtime::invoke_context::mock_process_instruction; - use solana_sdk::{ - account::{self, Account, AccountSharedData}, - rent::Rent, + use { + super::*, + bincode::serialize, + solana_program_runtime::invoke_context::mock_process_instruction, + solana_sdk::{ + account::{self, Account, AccountSharedData}, + rent::Rent, + }, + std::{cell::RefCell, rc::Rc, str::FromStr}, }; - use std::str::FromStr; - use std::{cell::RefCell, rc::Rc}; fn create_default_account() -> Rc> { AccountSharedData::new_ref(0, 0, &Pubkey::new_unique()) diff --git a/programs/vote/src/vote_state/mod.rs b/programs/vote/src/vote_state/mod.rs index f4219d5a7bb694..8b5d63265c969f 100644 --- a/programs/vote/src/vote_state/mod.rs +++ b/programs/vote/src/vote_state/mod.rs @@ -1,26 +1,29 @@ //! Vote state, vote program //! Receive and processes votes from validators -use crate::authorized_voters::AuthorizedVoters; -use crate::{id, vote_instruction::VoteError}; -use bincode::{deserialize, serialize_into, serialized_size, ErrorKind}; -use log::*; -use serde_derive::{Deserialize, Serialize}; -use solana_sdk::{ - account::{AccountSharedData, ReadableAccount, WritableAccount}, - account_utils::State, - clock::{Epoch, Slot, UnixTimestamp}, - epoch_schedule::MAX_LEADER_SCHEDULE_EPOCH_OFFSET, - hash::Hash, - instruction::InstructionError, - keyed_account::KeyedAccount, - pubkey::Pubkey, - rent::Rent, - slot_hashes::SlotHash, - sysvar::clock::Clock, +use { + crate::{authorized_voters::AuthorizedVoters, id, vote_instruction::VoteError}, + bincode::{deserialize, serialize_into, serialized_size, ErrorKind}, + log::*, + serde_derive::{Deserialize, Serialize}, + solana_sdk::{ + account::{AccountSharedData, ReadableAccount, WritableAccount}, + account_utils::State, + clock::{Epoch, Slot, UnixTimestamp}, + epoch_schedule::MAX_LEADER_SCHEDULE_EPOCH_OFFSET, + hash::Hash, + instruction::InstructionError, + keyed_account::KeyedAccount, + pubkey::Pubkey, + rent::Rent, + slot_hashes::SlotHash, + sysvar::clock::Clock, + }, + std::{ + boxed::Box, + cmp::Ordering, + collections::{HashSet, VecDeque}, + }, }; -use std::boxed::Box; -use std::cmp::Ordering; -use std::collections::{HashSet, VecDeque}; mod vote_state_0_23_5; pub mod vote_state_versions; @@ -793,15 +796,17 @@ pub fn create_account( #[cfg(test)] mod tests { - use super::*; - use crate::vote_state; - use solana_sdk::{ - account::AccountSharedData, - account_utils::StateMut, - hash::hash, - keyed_account::{get_signers, keyed_account_at_index}, + use { + super::*, + crate::vote_state, + solana_sdk::{ + account::AccountSharedData, + account_utils::StateMut, + hash::hash, + keyed_account::{get_signers, keyed_account_at_index}, + }, + std::cell::RefCell, }; - use std::cell::RefCell; const MAX_RECENT_VOTES: usize = 16; diff --git a/programs/vote/src/vote_state/vote_state_versions.rs b/programs/vote/src/vote_state/vote_state_versions.rs index f00cc6535473e5..3f6b9ec14d9820 100644 --- a/programs/vote/src/vote_state/vote_state_versions.rs +++ b/programs/vote/src/vote_state/vote_state_versions.rs @@ -1,5 +1,4 @@ -use super::*; -use crate::vote_state::vote_state_0_23_5::VoteState0_23_5; +use {super::*, crate::vote_state::vote_state_0_23_5::VoteState0_23_5}; #[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)] pub enum VoteStateVersions { diff --git a/programs/vote/src/vote_transaction.rs b/programs/vote/src/vote_transaction.rs index 217c6ed862a2fd..8b5198cb154a67 100644 --- a/programs/vote/src/vote_transaction.rs +++ b/programs/vote/src/vote_transaction.rs @@ -1,16 +1,17 @@ -use solana_sdk::{ - clock::Slot, - hash::Hash, - instruction::CompiledInstruction, - program_utils::limited_deserialize, - pubkey::Pubkey, - signature::{Keypair, Signer}, - transaction::{SanitizedTransaction, Transaction}, -}; - -use crate::{ - vote_instruction::{self, VoteInstruction}, - vote_state::Vote, +use { + crate::{ + vote_instruction::{self, VoteInstruction}, + vote_state::Vote, + }, + solana_sdk::{ + clock::Slot, + hash::Hash, + instruction::CompiledInstruction, + program_utils::limited_deserialize, + pubkey::Pubkey, + signature::{Keypair, Signer}, + transaction::{SanitizedTransaction, Transaction}, + }, }; pub type ParsedVote = (Pubkey, Vote, Option); @@ -104,8 +105,7 @@ pub fn new_vote_transaction( #[cfg(test)] mod test { - use super::*; - use solana_sdk::hash::hash; + use {super::*, solana_sdk::hash::hash}; fn run_test_parse_vote_transaction(input_hash: Option) { let node_keypair = Keypair::new(); diff --git a/rbpf-cli/src/main.rs b/rbpf-cli/src/main.rs index 77b8322c98b9d2..92a59c70a62b4f 100644 --- a/rbpf-cli/src/main.rs +++ b/rbpf-cli/src/main.rs @@ -1,21 +1,27 @@ -use clap::{crate_version, App, Arg}; -use serde::{Deserialize, Serialize}; -use serde_json::Result; -use solana_bpf_loader_program::{ - create_vm, serialization::serialize_parameters, syscalls::register_syscalls, BpfError, - ThisInstructionMeter, +use { + clap::{crate_version, App, Arg}, + serde::{Deserialize, Serialize}, + serde_json::Result, + solana_bpf_loader_program::{ + create_vm, serialization::serialize_parameters, syscalls::register_syscalls, BpfError, + ThisInstructionMeter, + }, + solana_program_runtime::invoke_context::{prepare_mock_invoke_context, InvokeContext}, + solana_rbpf::{ + assembler::assemble, + elf::Executable, + static_analysis::Analysis, + verifier::check, + vm::{Config, DynamicAnalysis}, + }, + solana_sdk::{account::AccountSharedData, bpf_loader, pubkey::Pubkey}, + std::{ + fs::File, + io::{Read, Seek, SeekFrom}, + path::Path, + }, + time::Instant, }; -use solana_program_runtime::invoke_context::{prepare_mock_invoke_context, InvokeContext}; -use solana_rbpf::{ - assembler::assemble, - elf::Executable, - static_analysis::Analysis, - verifier::check, - vm::{Config, DynamicAnalysis}, -}; -use solana_sdk::{account::AccountSharedData, bpf_loader, pubkey::Pubkey}; -use std::{fs::File, io::Read, io::Seek, io::SeekFrom, path::Path}; -use time::Instant; #[derive(Serialize, Deserialize, Debug)] struct Account { diff --git a/rpc-test/tests/rpc.rs b/rpc-test/tests/rpc.rs index 51918b6402a01d..1c9fb9fdcb273a 100644 --- a/rpc-test/tests/rpc.rs +++ b/rpc-test/tests/rpc.rs @@ -1,40 +1,40 @@ -use bincode::serialize; -use jsonrpc_core::futures::StreamExt; -use jsonrpc_core_client::transports::ws; - -use log::*; -use reqwest::{self, header::CONTENT_TYPE}; -use serde_json::{json, Value}; -use solana_account_decoder::UiAccount; -use solana_client::{ - client_error::{ClientErrorKind, Result as ClientResult}, - rpc_client::RpcClient, - rpc_config::{RpcAccountInfoConfig, RpcSignatureSubscribeConfig}, - rpc_request::RpcError, - rpc_response::{Response as RpcResponse, RpcSignatureResult, SlotUpdate}, - tpu_client::{TpuClient, TpuClientConfig}, +use { + bincode::serialize, + jsonrpc_core::futures::StreamExt, + jsonrpc_core_client::transports::ws, + log::*, + reqwest::{self, header::CONTENT_TYPE}, + serde_json::{json, Value}, + solana_account_decoder::UiAccount, + solana_client::{ + client_error::{ClientErrorKind, Result as ClientResult}, + rpc_client::RpcClient, + rpc_config::{RpcAccountInfoConfig, RpcSignatureSubscribeConfig}, + rpc_request::RpcError, + rpc_response::{Response as RpcResponse, RpcSignatureResult, SlotUpdate}, + tpu_client::{TpuClient, TpuClientConfig}, + }, + solana_rpc::rpc_pubsub::gen_client::Client as PubsubClient, + solana_sdk::{ + commitment_config::CommitmentConfig, + hash::Hash, + pubkey::Pubkey, + signature::{Keypair, Signer}, + system_transaction, + transaction::Transaction, + }, + solana_streamer::socket::SocketAddrSpace, + solana_test_validator::TestValidator, + solana_transaction_status::TransactionStatus, + std::{ + collections::HashSet, + net::UdpSocket, + sync::{mpsc::channel, Arc}, + thread::sleep, + time::{Duration, Instant}, + }, + tokio::runtime::Runtime, }; -use solana_rpc::rpc_pubsub::gen_client::Client as PubsubClient; -use solana_test_validator::TestValidator; - -use solana_sdk::{ - commitment_config::CommitmentConfig, - hash::Hash, - pubkey::Pubkey, - signature::{Keypair, Signer}, - system_transaction, - transaction::Transaction, -}; -use solana_streamer::socket::SocketAddrSpace; -use solana_transaction_status::TransactionStatus; -use std::{ - collections::HashSet, - net::UdpSocket, - sync::{mpsc::channel, Arc}, - thread::sleep, - time::{Duration, Instant}, -}; -use tokio::runtime::Runtime; macro_rules! json_req { ($method: expr, $params: expr) => {{ @@ -108,8 +108,9 @@ fn test_rpc_send_tx() { assert!(confirmed_tx); - use solana_account_decoder::UiAccountEncoding; - use solana_client::rpc_config::RpcAccountInfoConfig; + use { + solana_account_decoder::UiAccountEncoding, solana_client::rpc_config::RpcAccountInfoConfig, + }; let config = RpcAccountInfoConfig { encoding: Some(UiAccountEncoding::Base64), commitment: None, diff --git a/rpc/src/rpc.rs b/rpc/src/rpc.rs index 2fc558d6bf3391..e73e9d2b18b87a 100644 --- a/rpc/src/rpc.rs +++ b/rpc/src/rpc.rs @@ -26,8 +26,7 @@ use { MAX_GET_SIGNATURE_STATUSES_QUERY_ITEMS, MAX_GET_SLOT_LEADERS, MAX_MULTIPLE_ACCOUNTS, NUM_LARGEST_ACCOUNTS, }, - rpc_response::Response as RpcResponse, - rpc_response::*, + rpc_response::{Response as RpcResponse, *}, }, solana_faucet::faucet::request_airdrop_transaction, solana_gossip::{cluster_info::ClusterInfo, contact_info::ContactInfo}, @@ -4338,8 +4337,7 @@ pub mod tests { }, spl_token::{ solana_program::{program_option::COption, pubkey::Pubkey as SplTokenPubkey}, - state::AccountState as TokenAccountState, - state::Mint, + state::{AccountState as TokenAccountState, Mint}, }, std::collections::HashMap, }; diff --git a/rpc/src/rpc_health.rs b/rpc/src/rpc_health.rs index 94dff94fccaf45..8f4b4dfc4c53d8 100644 --- a/rpc/src/rpc_health.rs +++ b/rpc/src/rpc_health.rs @@ -3,8 +3,10 @@ use { solana_sdk::{clock::Slot, pubkey::Pubkey}, std::{ collections::HashSet, - sync::atomic::{AtomicBool, Ordering}, - sync::Arc, + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, + }, }, }; diff --git a/rpc/src/rpc_pubsub_service.rs b/rpc/src/rpc_pubsub_service.rs index b124a40f58423e..a8f6c3745782d7 100644 --- a/rpc/src/rpc_pubsub_service.rs +++ b/rpc/src/rpc_pubsub_service.rs @@ -187,9 +187,13 @@ pub struct TestBroadcastReceiver { #[cfg(test)] impl TestBroadcastReceiver { pub fn recv(&mut self) -> String { - use std::thread::sleep; - use std::time::{Duration, Instant}; - use tokio::sync::broadcast::error::TryRecvError; + use { + std::{ + thread::sleep, + time::{Duration, Instant}, + }, + tokio::sync::broadcast::error::TryRecvError, + }; let timeout = Duration::from_secs(5); let started = Instant::now(); diff --git a/rpc/src/rpc_service.rs b/rpc/src/rpc_service.rs index 7e900294896520..14e167de402a93 100644 --- a/rpc/src/rpc_service.rs +++ b/rpc/src/rpc_service.rs @@ -40,8 +40,11 @@ use { collections::HashSet, net::SocketAddr, path::{Path, PathBuf}, - sync::atomic::{AtomicBool, AtomicU64, Ordering}, - sync::{mpsc::channel, Arc, Mutex, RwLock}, + sync::{ + atomic::{AtomicBool, AtomicU64, Ordering}, + mpsc::channel, + Arc, Mutex, RwLock, + }, thread::{self, Builder, JoinHandle}, }, tokio_util::codec::{BytesCodec, FramedRead}, diff --git a/rpc/src/rpc_subscription_tracker.rs b/rpc/src/rpc_subscription_tracker.rs index 911fdbd1bcc352..36ef4d5e99710b 100644 --- a/rpc/src/rpc_subscription_tracker.rs +++ b/rpc/src/rpc_subscription_tracker.rs @@ -535,11 +535,13 @@ impl SubscriptionToken { #[cfg(test)] mod tests { - use super::*; - use crate::rpc_pubsub_service::PubSubConfig; - use solana_ledger::genesis_utils::{create_genesis_config, GenesisConfigInfo}; - use solana_runtime::bank::Bank; - use std::str::FromStr; + use { + super::*, + crate::rpc_pubsub_service::PubSubConfig, + solana_ledger::genesis_utils::{create_genesis_config, GenesisConfigInfo}, + solana_runtime::bank::Bank, + std::str::FromStr, + }; struct ControlWrapper { control: SubscriptionControl, diff --git a/rpc/src/rpc_subscriptions.rs b/rpc/src/rpc_subscriptions.rs index d34d2dcc2c2447..35256667815891 100644 --- a/rpc/src/rpc_subscriptions.rs +++ b/rpc/src/rpc_subscriptions.rs @@ -48,8 +48,7 @@ use { Arc, Mutex, RwLock, Weak, }, thread::{Builder, JoinHandle}, - time::Duration, - time::Instant, + time::{Duration, Instant}, }, tokio::sync::broadcast, }; diff --git a/runtime/benches/accounts.rs b/runtime/benches/accounts.rs index 8f8385887aabf1..2d63763c7bca80 100644 --- a/runtime/benches/accounts.rs +++ b/runtime/benches/accounts.rs @@ -3,30 +3,32 @@ extern crate test; -use dashmap::DashMap; -use rand::Rng; -use rayon::iter::{IntoParallelRefIterator, ParallelIterator}; -use solana_runtime::{ - accounts::{create_test_accounts, AccountAddressFilter, Accounts}, - accounts_db::AccountShrinkThreshold, - accounts_index::{AccountSecondaryIndexes, ScanConfig}, - ancestors::Ancestors, - bank::*, +use { + dashmap::DashMap, + rand::Rng, + rayon::iter::{IntoParallelRefIterator, ParallelIterator}, + solana_runtime::{ + accounts::{create_test_accounts, AccountAddressFilter, Accounts}, + accounts_db::AccountShrinkThreshold, + accounts_index::{AccountSecondaryIndexes, ScanConfig}, + ancestors::Ancestors, + bank::*, + }, + solana_sdk::{ + account::{AccountSharedData, ReadableAccount}, + genesis_config::{create_genesis_config, ClusterType}, + hash::Hash, + lamports::LamportsError, + pubkey::Pubkey, + }, + std::{ + collections::{HashMap, HashSet}, + path::PathBuf, + sync::{Arc, RwLock}, + thread::Builder, + }, + test::Bencher, }; -use solana_sdk::{ - account::{AccountSharedData, ReadableAccount}, - genesis_config::{create_genesis_config, ClusterType}, - hash::Hash, - lamports::LamportsError, - pubkey::Pubkey, -}; -use std::{ - collections::{HashMap, HashSet}, - path::PathBuf, - sync::{Arc, RwLock}, - thread::Builder, -}; -use test::Bencher; fn deposit_many(bank: &Bank, pubkeys: &mut Vec, num: usize) -> Result<(), LamportsError> { for t in 0..num { diff --git a/runtime/benches/accounts_index.rs b/runtime/benches/accounts_index.rs index 4aa378a4e871c2..322e6674640144 100644 --- a/runtime/benches/accounts_index.rs +++ b/runtime/benches/accounts_index.rs @@ -2,15 +2,17 @@ extern crate test; -use rand::{thread_rng, Rng}; -use solana_runtime::{ - accounts_db::AccountInfo, - accounts_index::{ - AccountSecondaryIndexes, AccountsIndex, ACCOUNTS_INDEX_CONFIG_FOR_BENCHMARKS, +use { + rand::{thread_rng, Rng}, + solana_runtime::{ + accounts_db::AccountInfo, + accounts_index::{ + AccountSecondaryIndexes, AccountsIndex, ACCOUNTS_INDEX_CONFIG_FOR_BENCHMARKS, + }, }, + solana_sdk::pubkey::{self, Pubkey}, + test::Bencher, }; -use solana_sdk::pubkey::{self, Pubkey}; -use test::Bencher; #[bench] fn bench_accounts_index(bencher: &mut Bencher) { diff --git a/runtime/benches/append_vec.rs b/runtime/benches/append_vec.rs index 17e7eaf63d5e04..a7bf8896d34ae1 100644 --- a/runtime/benches/append_vec.rs +++ b/runtime/benches/append_vec.rs @@ -1,19 +1,20 @@ #![feature(test)] extern crate test; -use rand::{thread_rng, Rng}; -use solana_runtime::append_vec::{ - test_utils::{create_test_account, get_append_vec_path}, - AppendVec, +use { + rand::{thread_rng, Rng}, + solana_runtime::append_vec::{ + test_utils::{create_test_account, get_append_vec_path}, + AppendVec, + }, + solana_sdk::{account::ReadableAccount, hash::Hash}, + std::{ + sync::{Arc, Mutex}, + thread::{sleep, spawn}, + time::Duration, + }, + test::Bencher, }; -use solana_sdk::{account::ReadableAccount, hash::Hash}; -use std::{ - sync::{Arc, Mutex}, - thread::sleep, - thread::spawn, - time::Duration, -}; -use test::Bencher; #[bench] fn append_vec_append(bencher: &mut Bencher) { diff --git a/runtime/benches/bank.rs b/runtime/benches/bank.rs index b2994501b16c98..b4fa9962fc131c 100644 --- a/runtime/benches/bank.rs +++ b/runtime/benches/bank.rs @@ -3,22 +3,23 @@ extern crate test; -use log::*; -use solana_program_runtime::invoke_context::InvokeContext; -use solana_runtime::{bank::*, bank_client::BankClient, loader_utils::create_invoke_instruction}; -use solana_sdk::{ - client::AsyncClient, - client::SyncClient, - clock::MAX_RECENT_BLOCKHASHES, - genesis_config::create_genesis_config, - instruction::InstructionError, - message::Message, - pubkey::Pubkey, - signature::{Keypair, Signer}, - transaction::Transaction, +use { + log::*, + solana_program_runtime::invoke_context::InvokeContext, + solana_runtime::{bank::*, bank_client::BankClient, loader_utils::create_invoke_instruction}, + solana_sdk::{ + client::{AsyncClient, SyncClient}, + clock::MAX_RECENT_BLOCKHASHES, + genesis_config::create_genesis_config, + instruction::InstructionError, + message::Message, + pubkey::Pubkey, + signature::{Keypair, Signer}, + transaction::Transaction, + }, + std::{sync::Arc, thread::sleep, time::Duration}, + test::Bencher, }; -use std::{sync::Arc, thread::sleep, time::Duration}; -use test::Bencher; const BUILTIN_PROGRAM_ID: [u8; 32] = [ 98, 117, 105, 108, 116, 105, 110, 95, 112, 114, 111, 103, 114, 97, 109, 95, 105, 100, 0, 0, 0, diff --git a/runtime/benches/bloom.rs b/runtime/benches/bloom.rs index 2a964e55cffc32..ca2ed9de773b33 100644 --- a/runtime/benches/bloom.rs +++ b/runtime/benches/bloom.rs @@ -1,17 +1,18 @@ #![feature(test)] extern crate test; -use bv::BitVec; -use fnv::FnvHasher; -use rand::Rng; -use solana_runtime::bloom::{AtomicBloom, Bloom, BloomHashIndex}; -use solana_sdk::{ - hash::{hash, Hash}, - signature::Signature, +use { + bv::BitVec, + fnv::FnvHasher, + rand::Rng, + solana_runtime::bloom::{AtomicBloom, Bloom, BloomHashIndex}, + solana_sdk::{ + hash::{hash, Hash}, + signature::Signature, + }, + std::{collections::HashSet, hash::Hasher}, + test::Bencher, }; -use std::collections::HashSet; -use std::hash::Hasher; -use test::Bencher; #[bench] #[ignore] diff --git a/runtime/benches/status_cache.rs b/runtime/benches/status_cache.rs index 66c4ec7883be87..bced5d55b78e1f 100644 --- a/runtime/benches/status_cache.rs +++ b/runtime/benches/status_cache.rs @@ -2,13 +2,15 @@ extern crate test; -use bincode::serialize; -use solana_runtime::status_cache::*; -use solana_sdk::{ - hash::{hash, Hash}, - signature::Signature, +use { + bincode::serialize, + solana_runtime::status_cache::*, + solana_sdk::{ + hash::{hash, Hash}, + signature::Signature, + }, + test::Bencher, }; -use test::Bencher; type BankStatusCache = StatusCache<()>; diff --git a/runtime/src/accounts.rs b/runtime/src/accounts.rs index 6705ad6cec5842..ee78fabbe2703d 100644 --- a/runtime/src/accounts.rs +++ b/runtime/src/accounts.rs @@ -1,48 +1,53 @@ -use crate::{ - accounts_db::{ - AccountShrinkThreshold, AccountsAddRootTiming, AccountsDb, AccountsDbConfig, BankHashInfo, - ErrorCounters, LoadHint, LoadedAccount, ScanStorageResult, - ACCOUNTS_DB_CONFIG_FOR_BENCHMARKS, ACCOUNTS_DB_CONFIG_FOR_TESTING, +use { + crate::{ + accounts_db::{ + AccountShrinkThreshold, AccountsAddRootTiming, AccountsDb, AccountsDbConfig, + BankHashInfo, ErrorCounters, LoadHint, LoadedAccount, ScanStorageResult, + ACCOUNTS_DB_CONFIG_FOR_BENCHMARKS, ACCOUNTS_DB_CONFIG_FOR_TESTING, + }, + accounts_index::{AccountSecondaryIndexes, IndexKey, ScanConfig, ScanError, ScanResult}, + accounts_update_notifier_interface::AccountsUpdateNotifier, + ancestors::Ancestors, + bank::{ + Bank, NonceFull, NonceInfo, RentDebits, TransactionCheckResult, + TransactionExecutionResult, + }, + blockhash_queue::BlockhashQueue, + rent_collector::RentCollector, + system_instruction_processor::{get_system_account_kind, SystemAccountKind}, }, - accounts_index::{AccountSecondaryIndexes, IndexKey, ScanConfig, ScanError, ScanResult}, - accounts_update_notifier_interface::AccountsUpdateNotifier, - ancestors::Ancestors, - bank::{ - Bank, NonceFull, NonceInfo, RentDebits, TransactionCheckResult, TransactionExecutionResult, + dashmap::{ + mapref::entry::Entry::{Occupied, Vacant}, + DashMap, + }, + log::*, + rand::{thread_rng, Rng}, + solana_sdk::{ + account::{Account, AccountSharedData, ReadableAccount, WritableAccount}, + account_utils::StateMut, + bpf_loader_upgradeable::{self, UpgradeableLoaderState}, + clock::{BankId, Slot, INITIAL_RENT_EPOCH}, + feature_set::{self, FeatureSet}, + genesis_config::ClusterType, + hash::Hash, + message::SanitizedMessage, + native_loader, + nonce::{state::Versions as NonceVersions, State as NonceState}, + pubkey::Pubkey, + system_program, + sysvar::{self, instructions::construct_instructions_data}, + transaction::{Result, SanitizedTransaction, TransactionError}, + }, + std::{ + cmp::Reverse, + collections::{hash_map, BinaryHeap, HashMap, HashSet}, + ops::RangeBounds, + path::PathBuf, + sync::{ + atomic::{AtomicUsize, Ordering}, + Arc, Mutex, + }, }, - blockhash_queue::BlockhashQueue, - rent_collector::RentCollector, - system_instruction_processor::{get_system_account_kind, SystemAccountKind}, -}; -use dashmap::{ - mapref::entry::Entry::{Occupied, Vacant}, - DashMap, -}; -use log::*; -use rand::{thread_rng, Rng}; -use solana_sdk::{ - account::{Account, AccountSharedData, ReadableAccount, WritableAccount}, - account_utils::StateMut, - bpf_loader_upgradeable::{self, UpgradeableLoaderState}, - clock::{BankId, Slot, INITIAL_RENT_EPOCH}, - feature_set::{self, FeatureSet}, - genesis_config::ClusterType, - hash::Hash, - message::SanitizedMessage, - native_loader, - nonce::{state::Versions as NonceVersions, State as NonceState}, - pubkey::Pubkey, - system_program, sysvar, - sysvar::instructions::construct_instructions_data, - transaction::{Result, SanitizedTransaction, TransactionError}, -}; -use std::{ - cmp::Reverse, - collections::{hash_map, BinaryHeap, HashMap, HashSet}, - ops::RangeBounds, - path::PathBuf, - sync::atomic::{AtomicUsize, Ordering}, - sync::{Arc, Mutex}, }; #[derive(Debug, Default, AbiExample)] @@ -1227,25 +1232,27 @@ pub fn update_accounts_bench(accounts: &Accounts, pubkeys: &[Pubkey], slot: u64) #[cfg(test)] mod tests { - use super::*; - use crate::rent_collector::RentCollector; - use solana_sdk::{ - account::{AccountSharedData, WritableAccount}, - epoch_schedule::EpochSchedule, - genesis_config::ClusterType, - hash::Hash, - instruction::{CompiledInstruction, InstructionError}, - message::Message, - nonce, nonce_account, - rent::Rent, - signature::{keypair_from_seed, signers::Signers, Keypair, Signer}, - system_instruction, system_program, - transaction::Transaction, - }; - use std::{ - convert::TryFrom, - sync::atomic::{AtomicBool, AtomicU64, Ordering}, - {thread, time}, + use { + super::*, + crate::rent_collector::RentCollector, + solana_sdk::{ + account::{AccountSharedData, WritableAccount}, + epoch_schedule::EpochSchedule, + genesis_config::ClusterType, + hash::Hash, + instruction::{CompiledInstruction, InstructionError}, + message::Message, + nonce, nonce_account, + rent::Rent, + signature::{keypair_from_seed, signers::Signers, Keypair, Signer}, + system_instruction, system_program, + transaction::Transaction, + }, + std::{ + convert::TryFrom, + sync::atomic::{AtomicBool, AtomicU64, Ordering}, + thread, time, + }, }; fn new_sanitized_tx( diff --git a/runtime/src/accounts_background_service.rs b/runtime/src/accounts_background_service.rs index a679174c883714..33770dab0e71c4 100644 --- a/runtime/src/accounts_background_service.rs +++ b/runtime/src/accounts_background_service.rs @@ -2,30 +2,32 @@ // // This can be expensive since we have to walk the append vecs being cleaned up. -use crate::{ - bank::{Bank, BankSlotDelta, DropCallback}, - bank_forks::BankForks, - snapshot_config::SnapshotConfig, - snapshot_package::{AccountsPackageSender, SnapshotType}, - snapshot_utils::{self, SnapshotError}, -}; -use crossbeam_channel::{Receiver, SendError, Sender}; -use log::*; -use rand::{thread_rng, Rng}; -use solana_measure::measure::Measure; -use solana_sdk::{ - clock::{BankId, Slot}, - hash::Hash, -}; -use std::{ - boxed::Box, - fmt::{Debug, Formatter}, - sync::{ - atomic::{AtomicBool, Ordering}, - Arc, RwLock, +use { + crate::{ + bank::{Bank, BankSlotDelta, DropCallback}, + bank_forks::BankForks, + snapshot_config::SnapshotConfig, + snapshot_package::{AccountsPackageSender, SnapshotType}, + snapshot_utils::{self, SnapshotError}, + }, + crossbeam_channel::{Receiver, SendError, Sender}, + log::*, + rand::{thread_rng, Rng}, + solana_measure::measure::Measure, + solana_sdk::{ + clock::{BankId, Slot}, + hash::Hash, + }, + std::{ + boxed::Box, + fmt::{Debug, Formatter}, + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, RwLock, + }, + thread::{self, sleep, Builder, JoinHandle}, + time::{Duration, Instant}, }, - thread::{self, sleep, Builder, JoinHandle}, - time::{Duration, Instant}, }; const INTERVAL_MS: u64 = 100; @@ -520,10 +522,12 @@ impl AccountsBackgroundService { #[cfg(test)] mod test { - use super::*; - use crate::genesis_utils::create_genesis_config; - use crossbeam_channel::unbounded; - use solana_sdk::{account::AccountSharedData, pubkey::Pubkey}; + use { + super::*, + crate::genesis_utils::create_genesis_config, + crossbeam_channel::unbounded, + solana_sdk::{account::AccountSharedData, pubkey::Pubkey}, + }; #[test] fn test_accounts_background_service_remove_dead_slots() { diff --git a/runtime/src/accounts_cache.rs b/runtime/src/accounts_cache.rs index 1aec6a5c61291e..4c04da38eef9f8 100644 --- a/runtime/src/accounts_cache.rs +++ b/runtime/src/accounts_cache.rs @@ -1,17 +1,19 @@ -use dashmap::DashMap; -use solana_sdk::{ - account::{AccountSharedData, ReadableAccount}, - clock::Slot, - hash::Hash, - pubkey::Pubkey, -}; -use std::{ - borrow::Borrow, - collections::BTreeSet, - ops::Deref, - sync::{ - atomic::{AtomicBool, AtomicU64, Ordering}, - Arc, RwLock, +use { + dashmap::DashMap, + solana_sdk::{ + account::{AccountSharedData, ReadableAccount}, + clock::Slot, + hash::Hash, + pubkey::Pubkey, + }, + std::{ + borrow::Borrow, + collections::BTreeSet, + ops::Deref, + sync::{ + atomic::{AtomicBool, AtomicU64, Ordering}, + Arc, RwLock, + }, }, }; diff --git a/runtime/src/accounts_db.rs b/runtime/src/accounts_db.rs index 96d0192f560df1..df9078bd64a12e 100644 --- a/runtime/src/accounts_db.rs +++ b/runtime/src/accounts_db.rs @@ -18,68 +18,70 @@ //! tracks the number of commits to the entire data store. So the latest //! commit for each slot entry would be indexed. -use crate::{ - accounts_background_service::{DroppedSlotsSender, SendDroppedBankCallback}, - accounts_cache::{AccountsCache, CachedAccount, SlotCache}, - accounts_hash::{AccountsHash, CalculateHashIntermediate, HashStats, PreviousPass}, - accounts_index::{ - AccountIndexGetResult, AccountSecondaryIndexes, AccountsIndex, AccountsIndexConfig, - AccountsIndexRootsStats, IndexKey, IndexValue, IsCached, RefCount, ScanConfig, ScanResult, - SlotList, SlotSlice, ZeroLamport, ACCOUNTS_INDEX_CONFIG_FOR_BENCHMARKS, - ACCOUNTS_INDEX_CONFIG_FOR_TESTING, - }, - accounts_update_notifier_interface::AccountsUpdateNotifier, - ancestors::Ancestors, - append_vec::{AppendVec, StoredAccountMeta, StoredMeta, StoredMetaWriteVersion}, - cache_hash_data::CacheHashData, - contains::Contains, - pubkey_bins::PubkeyBinCalculator24, - read_only_accounts_cache::ReadOnlyAccountsCache, - rent_collector::RentCollector, - sorted_storages::SortedStorages, -}; -use blake3::traits::digest::Digest; -use crossbeam_channel::{unbounded, Receiver, Sender}; -use dashmap::{ - mapref::entry::Entry::{Occupied, Vacant}, - DashMap, DashSet, -}; -use log::*; -use rand::{prelude::SliceRandom, thread_rng, Rng}; -use rayon::{prelude::*, ThreadPool}; -use serde::{Deserialize, Serialize}; -use solana_measure::measure::Measure; -use solana_rayon_threadlimit::get_thread_count; -use solana_sdk::genesis_config::GenesisConfig; -use solana_sdk::{ - account::{AccountSharedData, ReadableAccount}, - clock::{BankId, Epoch, Slot, SlotCount}, - epoch_schedule::EpochSchedule, - genesis_config::ClusterType, - hash::Hash, - pubkey::Pubkey, - timing::AtomicInterval, -}; -use solana_vote_program::vote_state::MAX_LOCKOUT_HISTORY; -use std::{ - borrow::{Borrow, Cow}, - boxed::Box, - collections::{hash_map::Entry, BTreeSet, HashMap, HashSet}, - convert::TryFrom, - hash::{Hash as StdHash, Hasher as StdHasher}, - io::{Error as IoError, Result as IoResult}, - ops::{Range, RangeBounds}, - path::{Path, PathBuf}, - str::FromStr, - sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}, - sync::{Arc, Condvar, Mutex, MutexGuard, RwLock}, - thread::Builder, - time::Instant, -}; -use tempfile::TempDir; - #[cfg(test)] use std::{thread::sleep, time::Duration}; +use { + crate::{ + accounts_background_service::{DroppedSlotsSender, SendDroppedBankCallback}, + accounts_cache::{AccountsCache, CachedAccount, SlotCache}, + accounts_hash::{AccountsHash, CalculateHashIntermediate, HashStats, PreviousPass}, + accounts_index::{ + AccountIndexGetResult, AccountSecondaryIndexes, AccountsIndex, AccountsIndexConfig, + AccountsIndexRootsStats, IndexKey, IndexValue, IsCached, RefCount, ScanConfig, + ScanResult, SlotList, SlotSlice, ZeroLamport, ACCOUNTS_INDEX_CONFIG_FOR_BENCHMARKS, + ACCOUNTS_INDEX_CONFIG_FOR_TESTING, + }, + accounts_update_notifier_interface::AccountsUpdateNotifier, + ancestors::Ancestors, + append_vec::{AppendVec, StoredAccountMeta, StoredMeta, StoredMetaWriteVersion}, + cache_hash_data::CacheHashData, + contains::Contains, + pubkey_bins::PubkeyBinCalculator24, + read_only_accounts_cache::ReadOnlyAccountsCache, + rent_collector::RentCollector, + sorted_storages::SortedStorages, + }, + blake3::traits::digest::Digest, + crossbeam_channel::{unbounded, Receiver, Sender}, + dashmap::{ + mapref::entry::Entry::{Occupied, Vacant}, + DashMap, DashSet, + }, + log::*, + rand::{prelude::SliceRandom, thread_rng, Rng}, + rayon::{prelude::*, ThreadPool}, + serde::{Deserialize, Serialize}, + solana_measure::measure::Measure, + solana_rayon_threadlimit::get_thread_count, + solana_sdk::{ + account::{AccountSharedData, ReadableAccount}, + clock::{BankId, Epoch, Slot, SlotCount}, + epoch_schedule::EpochSchedule, + genesis_config::{ClusterType, GenesisConfig}, + hash::Hash, + pubkey::Pubkey, + timing::AtomicInterval, + }, + solana_vote_program::vote_state::MAX_LOCKOUT_HISTORY, + std::{ + borrow::{Borrow, Cow}, + boxed::Box, + collections::{hash_map::Entry, BTreeSet, HashMap, HashSet}, + convert::TryFrom, + hash::{Hash as StdHash, Hasher as StdHasher}, + io::{Error as IoError, Result as IoResult}, + ops::{Range, RangeBounds}, + path::{Path, PathBuf}, + str::FromStr, + sync::{ + atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}, + Arc, Condvar, Mutex, MutexGuard, RwLock, + }, + thread::Builder, + time::Instant, + }, + tempfile::TempDir, +}; const PAGE_SIZE: u64 = 4 * 1024; const MAX_RECYCLE_STORES: usize = 1000; @@ -7343,26 +7345,29 @@ impl AccountsDb { #[cfg(test)] pub mod tests { - use super::*; - use crate::{ - accounts_hash::MERKLE_FANOUT, - accounts_index::RefCount, - accounts_index::{tests::*, AccountSecondaryIndexesIncludeExclude}, - append_vec::{test_utils::TempFile, AccountMeta}, - inline_spl_token, - }; - use assert_matches::assert_matches; - use rand::{thread_rng, Rng}; - use solana_sdk::{ - account::{accounts_equal, Account, AccountSharedData, ReadableAccount, WritableAccount}, - hash::HASH_BYTES, - pubkey::PUBKEY_BYTES, - }; - use std::{ - iter::FromIterator, - str::FromStr, - thread::{self, sleep, Builder, JoinHandle}, - time::Duration, + use { + super::*, + crate::{ + accounts_hash::MERKLE_FANOUT, + accounts_index::{tests::*, AccountSecondaryIndexesIncludeExclude, RefCount}, + append_vec::{test_utils::TempFile, AccountMeta}, + inline_spl_token, + }, + assert_matches::assert_matches, + rand::{thread_rng, Rng}, + solana_sdk::{ + account::{ + accounts_equal, Account, AccountSharedData, ReadableAccount, WritableAccount, + }, + hash::HASH_BYTES, + pubkey::PUBKEY_BYTES, + }, + std::{ + iter::FromIterator, + str::FromStr, + thread::{self, sleep, Builder, JoinHandle}, + time::Duration, + }, }; fn linear_ancestors(end_slot: u64) -> Ancestors { diff --git a/runtime/src/accounts_hash.rs b/runtime/src/accounts_hash.rs index 4f9a1fe6baf82b..8195963645c08d 100644 --- a/runtime/src/accounts_hash.rs +++ b/runtime/src/accounts_hash.rs @@ -1,12 +1,13 @@ -use log::*; -use rayon::prelude::*; -use solana_measure::measure::Measure; -use solana_sdk::{ - hash::{Hash, Hasher}, - pubkey::Pubkey, +use { + log::*, + rayon::prelude::*, + solana_measure::measure::Measure, + solana_sdk::{ + hash::{Hash, Hasher}, + pubkey::Pubkey, + }, + std::{borrow::Borrow, convert::TryInto, sync::Mutex}, }; -use std::borrow::Borrow; -use std::{convert::TryInto, sync::Mutex}; pub const ZERO_RAW_LAMPORTS_SENTINEL: u64 = std::u64::MAX; pub const MERKLE_FANOUT: usize = 16; @@ -832,8 +833,7 @@ impl AccountsHash { #[cfg(test)] pub mod tests { - use super::*; - use std::str::FromStr; + use {super::*, std::str::FromStr}; #[test] fn test_accountsdb_div_ceil() { diff --git a/runtime/src/accounts_index.rs b/runtime/src/accounts_index.rs index 85360381a63329..18b03c8c0a385a 100644 --- a/runtime/src/accounts_index.rs +++ b/runtime/src/accounts_index.rs @@ -1,38 +1,39 @@ -use crate::{ - accounts_index_storage::AccountsIndexStorage, - ancestors::Ancestors, - bucket_map_holder::{Age, BucketMapHolder}, - contains::Contains, - in_mem_accounts_index::{InMemAccountsIndex, InsertNewEntryResults}, - inline_spl_token::{self, SPL_TOKEN_ACCOUNT_MINT_OFFSET, SPL_TOKEN_ACCOUNT_OWNER_OFFSET}, - pubkey_bins::PubkeyBinCalculator24, - secondary_index::*, -}; -use bv::BitVec; -use log::*; -use ouroboros::self_referencing; -use rand::thread_rng; -use rand::Rng; -use solana_measure::measure::Measure; -use solana_sdk::{ - clock::{BankId, Slot}, - pubkey::{Pubkey, PUBKEY_BYTES}, -}; -use std::{ - collections::{btree_map::BTreeMap, HashSet}, - fmt::Debug, - ops::{ - Bound, - Bound::{Excluded, Included, Unbounded}, - Range, RangeBounds, +use { + crate::{ + accounts_index_storage::AccountsIndexStorage, + ancestors::Ancestors, + bucket_map_holder::{Age, BucketMapHolder}, + contains::Contains, + in_mem_accounts_index::{InMemAccountsIndex, InsertNewEntryResults}, + inline_spl_token::{self, SPL_TOKEN_ACCOUNT_MINT_OFFSET, SPL_TOKEN_ACCOUNT_OWNER_OFFSET}, + pubkey_bins::PubkeyBinCalculator24, + secondary_index::*, + }, + bv::BitVec, + log::*, + ouroboros::self_referencing, + rand::{thread_rng, Rng}, + solana_measure::measure::Measure, + solana_sdk::{ + clock::{BankId, Slot}, + pubkey::{Pubkey, PUBKEY_BYTES}, }, - path::PathBuf, - sync::{ - atomic::{AtomicBool, AtomicU64, AtomicU8, Ordering}, - Arc, Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard, + std::{ + collections::{btree_map::BTreeMap, HashSet}, + fmt::Debug, + ops::{ + Bound, + Bound::{Excluded, Included, Unbounded}, + Range, RangeBounds, + }, + path::PathBuf, + sync::{ + atomic::{AtomicBool, AtomicU64, AtomicU8, Ordering}, + Arc, Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard, + }, }, + thiserror::Error, }; -use thiserror::Error; pub const ITER_BATCH_SIZE: usize = 1000; pub const BINS_DEFAULT: usize = 8192; @@ -1979,9 +1980,11 @@ impl AccountsIndex { #[cfg(test)] pub mod tests { - use super::*; - use solana_sdk::signature::{Keypair, Signer}; - use std::ops::RangeInclusive; + use { + super::*, + solana_sdk::signature::{Keypair, Signer}, + std::ops::RangeInclusive, + }; pub enum SecondaryIndexTypes<'a> { RwLock(&'a SecondaryIndex), diff --git a/runtime/src/accounts_index_storage.rs b/runtime/src/accounts_index_storage.rs index ca0199c2781736..f13b4327a9081c 100644 --- a/runtime/src/accounts_index_storage.rs +++ b/runtime/src/accounts_index_storage.rs @@ -1,14 +1,18 @@ -use crate::accounts_index::{AccountsIndexConfig, IndexValue}; -use crate::bucket_map_holder::BucketMapHolder; -use crate::in_mem_accounts_index::InMemAccountsIndex; -use crate::waitable_condvar::WaitableCondvar; -use std::fmt::Debug; -use std::{ - sync::{ - atomic::{AtomicBool, Ordering}, - Arc, Mutex, +use { + crate::{ + accounts_index::{AccountsIndexConfig, IndexValue}, + bucket_map_holder::BucketMapHolder, + in_mem_accounts_index::InMemAccountsIndex, + waitable_condvar::WaitableCondvar, + }, + std::{ + fmt::Debug, + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, Mutex, + }, + thread::{Builder, JoinHandle}, }, - thread::{Builder, JoinHandle}, }; /// Manages the lifetime of the background processing threads. diff --git a/runtime/src/ancestors.rs b/runtime/src/ancestors.rs index 5c5e16bcea8be0..7960018cdf54bd 100644 --- a/runtime/src/ancestors.rs +++ b/runtime/src/ancestors.rs @@ -1,6 +1,4 @@ -use crate::accounts_index::RollingBitField; -use solana_sdk::clock::Slot; -use std::collections::HashMap; +use {crate::accounts_index::RollingBitField, solana_sdk::clock::Slot, std::collections::HashMap}; pub type AncestorsForSerialization = HashMap; @@ -82,11 +80,10 @@ impl Ancestors { } #[cfg(test)] pub mod tests { - use super::*; - use crate::contains::Contains; - use log::*; - use solana_measure::measure::Measure; - use std::collections::HashSet; + use { + super::*, crate::contains::Contains, log::*, solana_measure::measure::Measure, + std::collections::HashSet, + }; impl std::iter::FromIterator<(Slot, usize)> for Ancestors { fn from_iter(iter: I) -> Self diff --git a/runtime/src/append_vec.rs b/runtime/src/append_vec.rs index c754d3735a4e0f..1f49dfe111f6f2 100644 --- a/runtime/src/append_vec.rs +++ b/runtime/src/append_vec.rs @@ -4,25 +4,28 @@ //! //! -use log::*; -use memmap2::MmapMut; -use serde::{Deserialize, Serialize}; -use solana_sdk::{ - account::{Account, AccountSharedData, ReadableAccount}, - clock::{Epoch, Slot}, - hash::Hash, - pubkey::Pubkey, -}; -use std::{ - borrow::Borrow, - convert::TryFrom, - fs::{remove_file, OpenOptions}, - io, - io::{Seek, SeekFrom, Write}, - mem, - path::{Path, PathBuf}, - sync::atomic::{AtomicUsize, Ordering}, - sync::Mutex, +use { + log::*, + memmap2::MmapMut, + serde::{Deserialize, Serialize}, + solana_sdk::{ + account::{Account, AccountSharedData, ReadableAccount}, + clock::{Epoch, Slot}, + hash::Hash, + pubkey::Pubkey, + }, + std::{ + borrow::Borrow, + convert::TryFrom, + fs::{remove_file, OpenOptions}, + io::{self, Seek, SeekFrom, Write}, + mem, + path::{Path, PathBuf}, + sync::{ + atomic::{AtomicUsize, Ordering}, + Mutex, + }, + }, }; // Data placement should be aligned at the next boundary. Without alignment accessing the memory may @@ -533,13 +536,12 @@ impl AppendVec { } pub mod test_utils { - use super::StoredMeta; - use rand::distributions::Alphanumeric; - use rand::{thread_rng, Rng}; - use solana_sdk::account::AccountSharedData; - use solana_sdk::pubkey::Pubkey; - use std::fs::create_dir_all; - use std::path::PathBuf; + use { + super::StoredMeta, + rand::{distributions::Alphanumeric, thread_rng, Rng}, + solana_sdk::{account::AccountSharedData, pubkey::Pubkey}, + std::{fs::create_dir_all, path::PathBuf}, + }; pub struct TempFile { pub path: PathBuf, @@ -582,12 +584,13 @@ pub mod test_utils { #[cfg(test)] pub mod tests { - use super::test_utils::*; - use super::*; - use assert_matches::assert_matches; - use rand::{thread_rng, Rng}; - use solana_sdk::{account::WritableAccount, timing::duration_as_ms}; - use std::time::Instant; + use { + super::{test_utils::*, *}, + assert_matches::assert_matches, + rand::{thread_rng, Rng}, + solana_sdk::{account::WritableAccount, timing::duration_as_ms}, + std::time::Instant, + }; impl AppendVec { fn append_account_test(&self, data: &(StoredMeta, AccountSharedData)) -> Option { diff --git a/runtime/src/bank.rs b/runtime/src/bank.rs index b75b3f20a9c799..5da7084854523a 100644 --- a/runtime/src/bank.rs +++ b/runtime/src/bank.rs @@ -33,120 +33,121 @@ //! It offers a high-level API that signs transactions //! on behalf of the caller, and a low-level API for when they have //! already been signed and verified. -use crate::{ - accounts::{AccountAddressFilter, Accounts, TransactionAccounts, TransactionLoadResult}, - accounts_db::{ - AccountShrinkThreshold, AccountsDbConfig, ErrorCounters, SnapshotStorages, - ACCOUNTS_DB_CONFIG_FOR_BENCHMARKS, ACCOUNTS_DB_CONFIG_FOR_TESTING, - }, - accounts_index::{AccountSecondaryIndexes, IndexKey, ScanConfig, ScanResult}, - accounts_update_notifier_interface::AccountsUpdateNotifier, - ancestors::{Ancestors, AncestorsForSerialization}, - blockhash_queue::BlockhashQueue, - builtins::{self, ActivationType, Builtin, Builtins}, - cost_tracker::CostTracker, - epoch_stakes::{EpochStakes, NodeVoteAccounts}, - inline_spl_token, - message_processor::MessageProcessor, - rent_collector::RentCollector, - stake_weighted_timestamp::{ - calculate_stake_weighted_timestamp, MaxAllowableDrift, MAX_ALLOWABLE_DRIFT_PERCENTAGE, - MAX_ALLOWABLE_DRIFT_PERCENTAGE_FAST, MAX_ALLOWABLE_DRIFT_PERCENTAGE_SLOW, - }, - stakes::Stakes, - status_cache::{SlotDelta, StatusCache}, - system_instruction_processor::{get_system_account_kind, SystemAccountKind}, - transaction_batch::TransactionBatch, - vote_account::VoteAccount, -}; -use byteorder::{ByteOrder, LittleEndian}; -use dashmap::DashMap; -use itertools::Itertools; -use log::*; -use rayon::{ - iter::{IntoParallelIterator, IntoParallelRefIterator, ParallelIterator}, - ThreadPool, ThreadPoolBuilder, -}; -use solana_measure::measure::Measure; -use solana_metrics::{inc_new_counter_debug, inc_new_counter_info}; -use solana_program_runtime::{ - instruction_recorder::InstructionRecorder, - invoke_context::{BuiltinProgram, Executor, Executors, ProcessInstructionWithContext}, - log_collector::LogCollector, - timings::ExecuteDetailsTimings, -}; #[allow(deprecated)] use solana_sdk::recent_blockhashes_account; -use solana_sdk::{ - account::{ - create_account_shared_data_with_fields as create_account, from_account, Account, - AccountSharedData, InheritableAccountFields, ReadableAccount, WritableAccount, +use { + crate::{ + accounts::{AccountAddressFilter, Accounts, TransactionAccounts, TransactionLoadResult}, + accounts_db::{ + AccountShrinkThreshold, AccountsDbConfig, ErrorCounters, SnapshotStorages, + ACCOUNTS_DB_CONFIG_FOR_BENCHMARKS, ACCOUNTS_DB_CONFIG_FOR_TESTING, + }, + accounts_index::{AccountSecondaryIndexes, IndexKey, ScanConfig, ScanResult}, + accounts_update_notifier_interface::AccountsUpdateNotifier, + ancestors::{Ancestors, AncestorsForSerialization}, + blockhash_queue::BlockhashQueue, + builtins::{self, ActivationType, Builtin, Builtins}, + cost_tracker::CostTracker, + epoch_stakes::{EpochStakes, NodeVoteAccounts}, + inline_spl_token, + message_processor::MessageProcessor, + rent_collector::RentCollector, + stake_weighted_timestamp::{ + calculate_stake_weighted_timestamp, MaxAllowableDrift, MAX_ALLOWABLE_DRIFT_PERCENTAGE, + MAX_ALLOWABLE_DRIFT_PERCENTAGE_FAST, MAX_ALLOWABLE_DRIFT_PERCENTAGE_SLOW, + }, + stakes::Stakes, + status_cache::{SlotDelta, StatusCache}, + system_instruction_processor::{get_system_account_kind, SystemAccountKind}, + transaction_batch::TransactionBatch, + vote_account::VoteAccount, }, - account_utils::StateMut, - clock::{ - BankId, Epoch, Slot, SlotCount, SlotIndex, UnixTimestamp, DEFAULT_TICKS_PER_SECOND, - INITIAL_RENT_EPOCH, MAX_PROCESSING_AGE, MAX_RECENT_BLOCKHASHES, - MAX_TRANSACTION_FORWARDING_DELAY, SECONDS_PER_DAY, + byteorder::{ByteOrder, LittleEndian}, + dashmap::DashMap, + itertools::Itertools, + log::*, + rayon::{ + iter::{IntoParallelIterator, IntoParallelRefIterator, ParallelIterator}, + ThreadPool, ThreadPoolBuilder, }, - compute_budget::ComputeBudget, - ed25519_program, - epoch_info::EpochInfo, - epoch_schedule::EpochSchedule, - feature, - feature_set::{ - self, disable_fee_calculator, nonce_must_be_writable, tx_wide_compute_cap, FeatureSet, + solana_measure::measure::Measure, + solana_metrics::{inc_new_counter_debug, inc_new_counter_info}, + solana_program_runtime::{ + instruction_recorder::InstructionRecorder, + invoke_context::{BuiltinProgram, Executor, Executors, ProcessInstructionWithContext}, + log_collector::LogCollector, + timings::ExecuteDetailsTimings, }, - fee_calculator::{FeeCalculator, FeeRateGovernor}, - genesis_config::{ClusterType, GenesisConfig}, - hard_forks::HardForks, - hash::{extend_and_hash, hashv, Hash}, - incinerator, - inflation::Inflation, - instruction::CompiledInstruction, - lamports::LamportsError, - message::SanitizedMessage, - native_loader, - native_token::sol_to_lamports, - nonce, nonce_account, - packet::PACKET_DATA_SIZE, - precompiles::get_precompiles, - program_utils::limited_deserialize, - pubkey::Pubkey, - secp256k1_program, - signature::{Keypair, Signature}, - slot_hashes::SlotHashes, - slot_history::SlotHistory, - system_transaction, - sysvar::{self}, - timing::years_as_slots, - transaction::{ - Result, SanitizedTransaction, Transaction, TransactionError, TransactionVerificationMode, - VersionedTransaction, + solana_sdk::{ + account::{ + create_account_shared_data_with_fields as create_account, from_account, Account, + AccountSharedData, InheritableAccountFields, ReadableAccount, WritableAccount, + }, + account_utils::StateMut, + clock::{ + BankId, Epoch, Slot, SlotCount, SlotIndex, UnixTimestamp, DEFAULT_TICKS_PER_SECOND, + INITIAL_RENT_EPOCH, MAX_PROCESSING_AGE, MAX_RECENT_BLOCKHASHES, + MAX_TRANSACTION_FORWARDING_DELAY, SECONDS_PER_DAY, + }, + compute_budget::ComputeBudget, + ed25519_program, + epoch_info::EpochInfo, + epoch_schedule::EpochSchedule, + feature, + feature_set::{ + self, disable_fee_calculator, nonce_must_be_writable, tx_wide_compute_cap, FeatureSet, + }, + fee_calculator::{FeeCalculator, FeeRateGovernor}, + genesis_config::{ClusterType, GenesisConfig}, + hard_forks::HardForks, + hash::{extend_and_hash, hashv, Hash}, + incinerator, + inflation::Inflation, + instruction::CompiledInstruction, + lamports::LamportsError, + message::SanitizedMessage, + native_loader, + native_token::sol_to_lamports, + nonce, nonce_account, + packet::PACKET_DATA_SIZE, + precompiles::get_precompiles, + program_utils::limited_deserialize, + pubkey::Pubkey, + secp256k1_program, + signature::{Keypair, Signature}, + slot_hashes::SlotHashes, + slot_history::SlotHistory, + system_transaction, + sysvar::{self}, + timing::years_as_slots, + transaction::{ + Result, SanitizedTransaction, Transaction, TransactionError, + TransactionVerificationMode, VersionedTransaction, + }, }, -}; -use solana_stake_program::stake_state::{ - self, InflationPointCalculationEvent, PointValue, StakeState, -}; -use solana_vote_program::{ - vote_instruction::VoteInstruction, - vote_state::{VoteState, VoteStateVersions}, -}; -use std::{ - borrow::Cow, - cell::RefCell, - collections::{HashMap, HashSet}, - convert::{TryFrom, TryInto}, - fmt, mem, - ops::RangeInclusive, - path::PathBuf, - ptr, - rc::Rc, - sync::{ - atomic::{AtomicBool, AtomicU64, Ordering::Relaxed}, - LockResult, RwLockWriteGuard, {Arc, RwLock, RwLockReadGuard}, + solana_stake_program::stake_state::{ + self, InflationPointCalculationEvent, PointValue, StakeState, + }, + solana_vote_program::{ + vote_instruction::VoteInstruction, + vote_state::{VoteState, VoteStateVersions}, + }, + std::{ + borrow::Cow, + cell::RefCell, + collections::{HashMap, HashSet}, + convert::{TryFrom, TryInto}, + fmt, mem, + ops::RangeInclusive, + path::PathBuf, + ptr, + rc::Rc, + sync::{ + atomic::{AtomicBool, AtomicU64, Ordering::Relaxed}, + Arc, LockResult, RwLock, RwLockReadGuard, RwLockWriteGuard, + }, + time::{Duration, Instant}, }, - time::Duration, - time::Instant, }; pub const SECONDS_PER_YEAR: f64 = 365.25 * 24.0 * 60.0 * 60.0; @@ -6478,56 +6479,59 @@ pub fn is_simple_vote_transaction(transaction: &SanitizedTransaction) -> bool { #[cfg(test)] pub(crate) mod tests { - use super::*; - use crate::{ - accounts_background_service::{AbsRequestHandler, SendDroppedBankCallback}, - accounts_db::DEFAULT_ACCOUNTS_SHRINK_RATIO, - accounts_index::{AccountIndex, AccountSecondaryIndexes, ScanError, ITER_BATCH_SIZE}, - ancestors::Ancestors, - genesis_utils::{ - activate_all_features, bootstrap_validator_stake_lamports, - create_genesis_config_with_leader, create_genesis_config_with_vote_accounts, - GenesisConfigInfo, ValidatorVoteKeypairs, - }, - stake_delegations::StakeDelegations, - status_cache::MAX_CACHE_ENTRIES, - }; - use crossbeam_channel::{bounded, unbounded}; - use solana_program_runtime::invoke_context::InvokeContext; #[allow(deprecated)] use solana_sdk::sysvar::fees::Fees; - use solana_sdk::{ - account::Account, - clock::{DEFAULT_SLOTS_PER_EPOCH, DEFAULT_TICKS_PER_SLOT}, - compute_budget::ComputeBudgetInstruction, - epoch_schedule::MINIMUM_SLOTS_PER_EPOCH, - feature::Feature, - feature_set::reject_empty_instruction_without_program, - genesis_config::create_genesis_config, - hash, - instruction::{AccountMeta, CompiledInstruction, Instruction, InstructionError}, - keyed_account::keyed_account_at_index, - message::{Message, MessageHeader}, - nonce, - poh_config::PohConfig, - rent::Rent, - signature::{keypair_from_seed, Keypair, Signer}, - stake::{ - instruction as stake_instruction, - state::{Authorized, Delegation, Lockup, Stake}, + use { + super::*, + crate::{ + accounts_background_service::{AbsRequestHandler, SendDroppedBankCallback}, + accounts_db::DEFAULT_ACCOUNTS_SHRINK_RATIO, + accounts_index::{AccountIndex, AccountSecondaryIndexes, ScanError, ITER_BATCH_SIZE}, + ancestors::Ancestors, + genesis_utils::{ + activate_all_features, bootstrap_validator_stake_lamports, + create_genesis_config_with_leader, create_genesis_config_with_vote_accounts, + GenesisConfigInfo, ValidatorVoteKeypairs, + }, + stake_delegations::StakeDelegations, + status_cache::MAX_CACHE_ENTRIES, }, - system_instruction::{self, SystemError}, - system_program, - sysvar::rewards::Rewards, - timing::duration_as_s, - }; - use solana_vote_program::{ - vote_instruction, - vote_state::{ - self, BlockTimestamp, Vote, VoteInit, VoteState, VoteStateVersions, MAX_LOCKOUT_HISTORY, + crossbeam_channel::{bounded, unbounded}, + solana_program_runtime::invoke_context::InvokeContext, + solana_sdk::{ + account::Account, + clock::{DEFAULT_SLOTS_PER_EPOCH, DEFAULT_TICKS_PER_SLOT}, + compute_budget::ComputeBudgetInstruction, + epoch_schedule::MINIMUM_SLOTS_PER_EPOCH, + feature::Feature, + feature_set::reject_empty_instruction_without_program, + genesis_config::create_genesis_config, + hash, + instruction::{AccountMeta, CompiledInstruction, Instruction, InstructionError}, + keyed_account::keyed_account_at_index, + message::{Message, MessageHeader}, + nonce, + poh_config::PohConfig, + rent::Rent, + signature::{keypair_from_seed, Keypair, Signer}, + stake::{ + instruction as stake_instruction, + state::{Authorized, Delegation, Lockup, Stake}, + }, + system_instruction::{self, SystemError}, + system_program, + sysvar::rewards::Rewards, + timing::duration_as_s, + }, + solana_vote_program::{ + vote_instruction, + vote_state::{ + self, BlockTimestamp, Vote, VoteInit, VoteState, VoteStateVersions, + MAX_LOCKOUT_HISTORY, + }, }, + std::{result, thread::Builder, time::Duration}, }; - use std::{result, thread::Builder, time::Duration}; impl Bank { fn cloned_stake_delegations(&self) -> StakeDelegations { diff --git a/runtime/src/bank_client.rs b/runtime/src/bank_client.rs index 543ec0fba039a7..8a8731810c4a78 100644 --- a/runtime/src/bank_client.rs +++ b/runtime/src/bank_client.rs @@ -1,29 +1,31 @@ -use crate::bank::Bank; -use solana_sdk::{ - account::Account, - client::{AsyncClient, Client, SyncClient}, - commitment_config::CommitmentConfig, - epoch_info::EpochInfo, - fee_calculator::{FeeCalculator, FeeRateGovernor}, - hash::Hash, - instruction::Instruction, - message::{Message, SanitizedMessage}, - pubkey::Pubkey, - signature::{Keypair, Signature, Signer}, - signers::Signers, - system_instruction, - transaction::{self, Transaction}, - transport::{Result, TransportError}, -}; -use std::{ - convert::TryFrom, - io, - sync::{ - mpsc::{channel, Receiver, Sender}, - Arc, Mutex, +use { + crate::bank::Bank, + solana_sdk::{ + account::Account, + client::{AsyncClient, Client, SyncClient}, + commitment_config::CommitmentConfig, + epoch_info::EpochInfo, + fee_calculator::{FeeCalculator, FeeRateGovernor}, + hash::Hash, + instruction::Instruction, + message::{Message, SanitizedMessage}, + pubkey::Pubkey, + signature::{Keypair, Signature, Signer}, + signers::Signers, + system_instruction, + transaction::{self, Transaction}, + transport::{Result, TransportError}, + }, + std::{ + convert::TryFrom, + io, + sync::{ + mpsc::{channel, Receiver, Sender}, + Arc, Mutex, + }, + thread::{sleep, Builder}, + time::{Duration, Instant}, }, - thread::{sleep, Builder}, - time::{Duration, Instant}, }; pub struct BankClient { @@ -359,8 +361,10 @@ impl BankClient { #[cfg(test)] mod tests { - use super::*; - use solana_sdk::{genesis_config::create_genesis_config, instruction::AccountMeta}; + use { + super::*, + solana_sdk::{genesis_config::create_genesis_config, instruction::AccountMeta}, + }; #[test] fn test_bank_client_new_with_keypairs() { diff --git a/runtime/src/bank_forks.rs b/runtime/src/bank_forks.rs index a2d9cfb1e3a717..a0b119b6307d76 100644 --- a/runtime/src/bank_forks.rs +++ b/runtime/src/bank_forks.rs @@ -1,18 +1,20 @@ //! The `bank_forks` module implements BankForks a DAG of checkpointed Banks -use crate::{ - accounts_background_service::{AbsRequestSender, SnapshotRequest}, - bank::Bank, - snapshot_config::SnapshotConfig, -}; -use log::*; -use solana_measure::measure::Measure; -use solana_sdk::{clock::Slot, hash::Hash, timing}; -use std::{ - collections::{hash_map::Entry, HashMap, HashSet}, - ops::Index, - sync::Arc, - time::Instant, +use { + crate::{ + accounts_background_service::{AbsRequestSender, SnapshotRequest}, + bank::Bank, + snapshot_config::SnapshotConfig, + }, + log::*, + solana_measure::measure::Measure, + solana_sdk::{clock::Slot, hash::Hash, timing}, + std::{ + collections::{hash_map::Entry, HashMap, HashSet}, + ops::Index, + sync::Arc, + time::Instant, + }, }; struct SetRootTimings { @@ -492,21 +494,23 @@ impl BankForks { #[cfg(test)] mod tests { - use super::*; - use crate::{ - bank::tests::update_vote_account_timestamp, - genesis_utils::{ - create_genesis_config, create_genesis_config_with_leader, GenesisConfigInfo, + use { + super::*, + crate::{ + bank::tests::update_vote_account_timestamp, + genesis_utils::{ + create_genesis_config, create_genesis_config_with_leader, GenesisConfigInfo, + }, }, + solana_sdk::{ + clock::UnixTimestamp, + hash::Hash, + pubkey::Pubkey, + signature::{Keypair, Signer}, + sysvar::epoch_schedule::EpochSchedule, + }, + solana_vote_program::vote_state::BlockTimestamp, }; - use solana_sdk::hash::Hash; - use solana_sdk::{ - clock::UnixTimestamp, - pubkey::Pubkey, - signature::{Keypair, Signer}, - sysvar::epoch_schedule::EpochSchedule, - }; - use solana_vote_program::vote_state::BlockTimestamp; #[test] fn test_bank_forks_new() { diff --git a/runtime/src/bank_utils.rs b/runtime/src/bank_utils.rs index b8db53fbe31f05..c1021030dd9c6f 100644 --- a/runtime/src/bank_utils.rs +++ b/runtime/src/bank_utils.rs @@ -1,10 +1,12 @@ -use crate::{ - bank::{Bank, TransactionResults}, - genesis_utils::{self, GenesisConfigInfo, ValidatorVoteKeypairs}, - vote_sender_types::ReplayVoteSender, +use { + crate::{ + bank::{Bank, TransactionResults}, + genesis_utils::{self, GenesisConfigInfo, ValidatorVoteKeypairs}, + vote_sender_types::ReplayVoteSender, + }, + solana_sdk::{pubkey::Pubkey, signature::Signer, transaction::SanitizedTransaction}, + solana_vote_program::vote_transaction, }; -use solana_sdk::{pubkey::Pubkey, signature::Signer, transaction::SanitizedTransaction}; -use solana_vote_program::vote_transaction; pub fn setup_bank_and_vote_pubkeys_for_tests( num_vote_accounts: usize, diff --git a/runtime/src/block_cost_limits.rs b/runtime/src/block_cost_limits.rs index 11243fc3fd94cf..97be8a062d9c2f 100644 --- a/runtime/src/block_cost_limits.rs +++ b/runtime/src/block_cost_limits.rs @@ -1,10 +1,12 @@ //! defines block cost related limits //! -use lazy_static::lazy_static; -use solana_sdk::{ - feature, incinerator, native_loader, pubkey::Pubkey, secp256k1_program, system_program, +use { + lazy_static::lazy_static, + solana_sdk::{ + feature, incinerator, native_loader, pubkey::Pubkey, secp256k1_program, system_program, + }, + std::collections::HashMap, }; -use std::collections::HashMap; /// Static configurations: /// diff --git a/runtime/src/blockhash_queue.rs b/runtime/src/blockhash_queue.rs index c903b7afbc23a8..ea8010ed43f0fa 100644 --- a/runtime/src/blockhash_queue.rs +++ b/runtime/src/blockhash_queue.rs @@ -1,8 +1,10 @@ -use serde::{Deserialize, Serialize}; #[allow(deprecated)] use solana_sdk::sysvar::recent_blockhashes; -use solana_sdk::{fee_calculator::FeeCalculator, hash::Hash, timing::timestamp}; -use std::collections::HashMap; +use { + serde::{Deserialize, Serialize}, + solana_sdk::{fee_calculator::FeeCalculator, hash::Hash, timing::timestamp}, + std::collections::HashMap, +}; #[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize, AbiExample)] struct HashAge { @@ -139,11 +141,13 @@ impl BlockhashQueue { } #[cfg(test)] mod tests { - use super::*; - use bincode::serialize; #[allow(deprecated)] use solana_sdk::sysvar::recent_blockhashes::IterItem; - use solana_sdk::{clock::MAX_RECENT_BLOCKHASHES, hash::hash}; + use { + super::*, + bincode::serialize, + solana_sdk::{clock::MAX_RECENT_BLOCKHASHES, hash::hash}, + }; #[test] fn test_register_hash() { diff --git a/runtime/src/bloom.rs b/runtime/src/bloom.rs index ae160a30af00a9..c3bbf1f4b5ae98 100644 --- a/runtime/src/bloom.rs +++ b/runtime/src/bloom.rs @@ -1,12 +1,17 @@ //! Simple Bloom Filter -use bv::BitVec; -use fnv::FnvHasher; -use rand::{self, Rng}; -use serde::{Deserialize, Serialize}; -use solana_sdk::sanitize::{Sanitize, SanitizeError}; -use std::fmt; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::{cmp, hash::Hasher, marker::PhantomData}; +use { + bv::BitVec, + fnv::FnvHasher, + rand::{self, Rng}, + serde::{Deserialize, Serialize}, + solana_sdk::sanitize::{Sanitize, SanitizeError}, + std::{ + cmp, fmt, + hash::Hasher, + marker::PhantomData, + sync::atomic::{AtomicU64, Ordering}, + }, +}; /// Generate a stable hash of `self` for each `hash_index` /// Best effort can be made for uniqueness of each hash. @@ -219,9 +224,11 @@ impl From> for Bloom { #[cfg(test)] mod test { - use super::*; - use rayon::prelude::*; - use solana_sdk::hash::{hash, Hash}; + use { + super::*, + rayon::prelude::*, + solana_sdk::hash::{hash, Hash}, + }; #[test] fn test_bloom_filter() { diff --git a/runtime/src/bucket_map_holder.rs b/runtime/src/bucket_map_holder.rs index f5493d036178e8..f0b4d269e7f7d2 100644 --- a/runtime/src/bucket_map_holder.rs +++ b/runtime/src/bucket_map_holder.rs @@ -1,15 +1,22 @@ -use crate::accounts_index::{AccountsIndexConfig, IndexValue}; -use crate::bucket_map_holder_stats::BucketMapHolderStats; -use crate::in_mem_accounts_index::{InMemAccountsIndex, SlotT}; -use crate::waitable_condvar::WaitableCondvar; -use solana_bucket_map::bucket_map::{BucketMap, BucketMapConfig}; -use solana_measure::measure::Measure; -use solana_sdk::clock::SLOT_MS; -use solana_sdk::timing::AtomicInterval; -use std::fmt::Debug; -use std::sync::atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering}; -use std::sync::{Arc, Mutex}; -use std::time::Duration; +use { + crate::{ + accounts_index::{AccountsIndexConfig, IndexValue}, + bucket_map_holder_stats::BucketMapHolderStats, + in_mem_accounts_index::{InMemAccountsIndex, SlotT}, + waitable_condvar::WaitableCondvar, + }, + solana_bucket_map::bucket_map::{BucketMap, BucketMapConfig}, + solana_measure::measure::Measure, + solana_sdk::{clock::SLOT_MS, timing::AtomicInterval}, + std::{ + fmt::Debug, + sync::{ + atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering}, + Arc, Mutex, + }, + time::Duration, + }, +}; pub type Age = u8; const AGE_MS: u64 = SLOT_MS; // match one age per slot time @@ -287,10 +294,14 @@ impl BucketMapHolder { #[cfg(test)] pub mod tests { - use super::*; - use rayon::prelude::*; - use std::sync::atomic::{AtomicUsize, Ordering}; - use std::time::Instant; + use { + super::*, + rayon::prelude::*, + std::{ + sync::atomic::{AtomicUsize, Ordering}, + time::Instant, + }, + }; #[test] fn test_next_bucket_to_flush() { diff --git a/runtime/src/bucket_map_holder_stats.rs b/runtime/src/bucket_map_holder_stats.rs index 77d4760fb370cb..b2dfffb8618328 100644 --- a/runtime/src/bucket_map_holder_stats.rs +++ b/runtime/src/bucket_map_holder_stats.rs @@ -1,8 +1,11 @@ -use crate::accounts_index::IndexValue; -use crate::bucket_map_holder::BucketMapHolder; -use solana_sdk::timing::AtomicInterval; -use std::fmt::Debug; -use std::sync::atomic::{AtomicBool, AtomicU64, AtomicU8, AtomicUsize, Ordering}; +use { + crate::{accounts_index::IndexValue, bucket_map_holder::BucketMapHolder}, + solana_sdk::timing::AtomicInterval, + std::{ + fmt::Debug, + sync::atomic::{AtomicBool, AtomicU64, AtomicU8, AtomicUsize, Ordering}, + }, +}; // stats logged every 10 s const STATS_INTERVAL_MS: u64 = 10_000; diff --git a/runtime/src/builtins.rs b/runtime/src/builtins.rs index 27ee8eabbbc3db..3299820cf9c93c 100644 --- a/runtime/src/builtins.rs +++ b/runtime/src/builtins.rs @@ -1,15 +1,16 @@ -use crate::system_instruction_processor; -use solana_program_runtime::{ - invoke_context::{InvokeContext, ProcessInstructionWithContext}, - stable_log, -}; -use solana_sdk::{ - feature_set, instruction::InstructionError, pubkey::Pubkey, stake, system_program, -}; -use std::fmt; - #[cfg(RUSTC_WITH_SPECIALIZATION)] use solana_frozen_abi::abi_example::AbiExample; +use { + crate::system_instruction_processor, + solana_program_runtime::{ + invoke_context::{InvokeContext, ProcessInstructionWithContext}, + stable_log, + }, + solana_sdk::{ + feature_set, instruction::InstructionError, pubkey::Pubkey, stake, system_program, + }, + std::fmt, +}; fn process_instruction_with_program_logging( process_instruction: ProcessInstructionWithContext, diff --git a/runtime/src/cache_hash_data.rs b/runtime/src/cache_hash_data.rs index 758f095fd6f356..90ff2a7a550f07 100644 --- a/runtime/src/cache_hash_data.rs +++ b/runtime/src/cache_hash_data.rs @@ -1,19 +1,20 @@ //! Cached data for hashing accounts -use crate::accounts_hash::CalculateHashIntermediate; -use crate::cache_hash_data_stats::CacheHashDataStats; -use crate::pubkey_bins::PubkeyBinCalculator24; -use log::*; -use memmap2::MmapMut; -use solana_measure::measure::Measure; -use std::collections::HashSet; -use std::fs::{self}; -use std::fs::{remove_file, OpenOptions}; -use std::io::Seek; -use std::io::SeekFrom; -use std::io::Write; -use std::path::Path; -use std::path::PathBuf; -use std::sync::{Arc, Mutex}; +use { + crate::{ + accounts_hash::CalculateHashIntermediate, cache_hash_data_stats::CacheHashDataStats, + pubkey_bins::PubkeyBinCalculator24, + }, + log::*, + memmap2::MmapMut, + solana_measure::measure::Measure, + std::{ + collections::HashSet, + fs::{self, remove_file, OpenOptions}, + io::{Seek, SeekFrom, Write}, + path::{Path, PathBuf}, + sync::{Arc, Mutex}, + }, +}; pub type EntryType = CalculateHashIntermediate; pub type SavedType = Vec>; @@ -302,8 +303,7 @@ impl CacheHashData { #[cfg(test)] pub mod tests { - use super::*; - use rand::Rng; + use {super::*, rand::Rng}; #[test] fn test_read_write() { diff --git a/runtime/src/commitment.rs b/runtime/src/commitment.rs index 603bfc2352bebf..cb420e05bb9119 100644 --- a/runtime/src/commitment.rs +++ b/runtime/src/commitment.rs @@ -1,6 +1,8 @@ -use solana_sdk::{clock::Slot, commitment_config::CommitmentLevel}; -use solana_vote_program::vote_state::MAX_LOCKOUT_HISTORY; -use std::collections::HashMap; +use { + solana_sdk::{clock::Slot, commitment_config::CommitmentLevel}, + solana_vote_program::vote_state::MAX_LOCKOUT_HISTORY, + std::collections::HashMap, +}; pub const VOTE_THRESHOLD_SIZE: f64 = 2f64 / 3f64; diff --git a/runtime/src/cost_model.rs b/runtime/src/cost_model.rs index 60b6adc54bf19b..a69b4c9f41ec09 100644 --- a/runtime/src/cost_model.rs +++ b/runtime/src/cost_model.rs @@ -4,12 +4,15 @@ //! //! The main function is `calculate_cost` which returns &TransactionCost. //! -use crate::{ - bank::is_simple_vote_transaction, block_cost_limits::*, execute_cost_table::ExecuteCostTable, +use { + crate::{ + bank::is_simple_vote_transaction, block_cost_limits::*, + execute_cost_table::ExecuteCostTable, + }, + log::*, + solana_sdk::{pubkey::Pubkey, transaction::SanitizedTransaction}, + std::collections::HashMap, }; -use log::*; -use solana_sdk::{pubkey::Pubkey, transaction::SanitizedTransaction}; -use std::collections::HashMap; const MAX_WRITABLE_ACCOUNTS: usize = 256; @@ -210,26 +213,28 @@ impl CostModel { #[cfg(test)] mod tests { - use super::*; - use crate::{ - bank::Bank, - genesis_utils::{create_genesis_config, GenesisConfigInfo}, - }; - use solana_sdk::{ - bpf_loader, - hash::Hash, - instruction::CompiledInstruction, - message::Message, - signature::{Keypair, Signer}, - system_instruction::{self}, - system_program, system_transaction, - transaction::Transaction, - }; - use solana_vote_program::vote_transaction; - use std::{ - str::FromStr, - sync::{Arc, RwLock}, - thread::{self, JoinHandle}, + use { + super::*, + crate::{ + bank::Bank, + genesis_utils::{create_genesis_config, GenesisConfigInfo}, + }, + solana_sdk::{ + bpf_loader, + hash::Hash, + instruction::CompiledInstruction, + message::Message, + signature::{Keypair, Signer}, + system_instruction::{self}, + system_program, system_transaction, + transaction::Transaction, + }, + solana_vote_program::vote_transaction, + std::{ + str::FromStr, + sync::{Arc, RwLock}, + thread::{self, JoinHandle}, + }, }; fn test_setup() -> (Keypair, Hash) { diff --git a/runtime/src/cost_tracker.rs b/runtime/src/cost_tracker.rs index 1a2765c3a6406b..4ad4525fe384cb 100644 --- a/runtime/src/cost_tracker.rs +++ b/runtime/src/cost_tracker.rs @@ -3,9 +3,11 @@ //! - would_transaction_fit(&tx_cost), immutable function to test if tx with tx_cost would fit into current block //! - add_transaction_cost(&tx_cost), mutable function to accumulate tx_cost to tracker. //! -use crate::{block_cost_limits::*, cost_model::TransactionCost}; -use solana_sdk::{clock::Slot, pubkey::Pubkey, transaction::SanitizedTransaction}; -use std::collections::HashMap; +use { + crate::{block_cost_limits::*, cost_model::TransactionCost}, + solana_sdk::{clock::Slot, pubkey::Pubkey, transaction::SanitizedTransaction}, + std::collections::HashMap, +}; const WRITABLE_ACCOUNTS_PER_BLOCK: usize = 512; @@ -156,18 +158,20 @@ impl CostTracker { #[cfg(test)] mod tests { - use super::*; - use crate::{ - bank::Bank, - genesis_utils::{create_genesis_config, GenesisConfigInfo}, + use { + super::*, + crate::{ + bank::Bank, + genesis_utils::{create_genesis_config, GenesisConfigInfo}, + }, + solana_sdk::{ + hash::Hash, + signature::{Keypair, Signer}, + system_transaction, + transaction::Transaction, + }, + std::{cmp, sync::Arc}, }; - use solana_sdk::{ - hash::Hash, - signature::{Keypair, Signer}, - system_transaction, - transaction::Transaction, - }; - use std::{cmp, sync::Arc}; fn test_setup() -> (Keypair, Hash) { solana_logger::setup(); diff --git a/runtime/src/epoch_stakes.rs b/runtime/src/epoch_stakes.rs index e9f81514719de4..b569c1aed95aa4 100644 --- a/runtime/src/epoch_stakes.rs +++ b/runtime/src/epoch_stakes.rs @@ -118,10 +118,10 @@ impl EpochStakes { #[cfg(test)] pub(crate) mod tests { - use super::*; - use solana_sdk::account::AccountSharedData; - use solana_vote_program::vote_state::create_account_with_authorized; - use std::iter; + use { + super::*, solana_sdk::account::AccountSharedData, + solana_vote_program::vote_state::create_account_with_authorized, std::iter, + }; struct VoteAccountInfo { vote_account: Pubkey, diff --git a/runtime/src/execute_cost_table.rs b/runtime/src/execute_cost_table.rs index 4e0c2026722ed2..c1ef3449cb0927 100644 --- a/runtime/src/execute_cost_table.rs +++ b/runtime/src/execute_cost_table.rs @@ -4,8 +4,7 @@ /// When its capacity limit is reached, it prunes old and less-used programs /// to make room for new ones. use log::*; -use solana_sdk::pubkey::Pubkey; -use std::collections::HashMap; +use {solana_sdk::pubkey::Pubkey, std::collections::HashMap}; // prune is rather expensive op, free up bulk space in each operation // would be more efficient. PRUNE_RATIO defines the after prune table diff --git a/runtime/src/genesis_utils.rs b/runtime/src/genesis_utils.rs index eea539905cb834..71222fdf441b31 100644 --- a/runtime/src/genesis_utils.rs +++ b/runtime/src/genesis_utils.rs @@ -1,19 +1,20 @@ -use solana_sdk::{ - account::Account, - account::AccountSharedData, - feature::{self, Feature}, - feature_set::FeatureSet, - fee_calculator::FeeRateGovernor, - genesis_config::{ClusterType, GenesisConfig}, - pubkey::Pubkey, - rent::Rent, - signature::{Keypair, Signer}, - stake::state::StakeState, - system_program, +use { + solana_sdk::{ + account::{Account, AccountSharedData}, + feature::{self, Feature}, + feature_set::FeatureSet, + fee_calculator::FeeRateGovernor, + genesis_config::{ClusterType, GenesisConfig}, + pubkey::Pubkey, + rent::Rent, + signature::{Keypair, Signer}, + stake::state::StakeState, + system_program, + }, + solana_stake_program::stake_state, + solana_vote_program::vote_state, + std::borrow::Borrow, }; -use solana_stake_program::stake_state; -use solana_vote_program::vote_state; -use std::borrow::Borrow; // Default amount received by the validator const VALIDATOR_LAMPORTS: u64 = 42; diff --git a/runtime/src/hardened_unpack.rs b/runtime/src/hardened_unpack.rs index f56c20808f71cf..a88908597019db 100644 --- a/runtime/src/hardened_unpack.rs +++ b/runtime/src/hardened_unpack.rs @@ -1,9 +1,8 @@ -use solana_sdk::genesis_config::{DEFAULT_GENESIS_ARCHIVE, DEFAULT_GENESIS_FILE}; use { bzip2::bufread::BzDecoder, log::*, rand::{thread_rng, Rng}, - solana_sdk::genesis_config::GenesisConfig, + solana_sdk::genesis_config::{GenesisConfig, DEFAULT_GENESIS_ARCHIVE, DEFAULT_GENESIS_FILE}, std::{ collections::HashMap, fs::{self, File}, @@ -474,9 +473,11 @@ fn is_valid_genesis_archive_entry(parts: &[&str], kind: tar::EntryType) -> bool #[cfg(test)] mod tests { - use super::*; - use assert_matches::assert_matches; - use tar::{Builder, Header}; + use { + super::*, + assert_matches::assert_matches, + tar::{Builder, Header}, + }; #[test] fn test_archive_is_valid_entry() { diff --git a/runtime/src/in_mem_accounts_index.rs b/runtime/src/in_mem_accounts_index.rs index 5c3e1c77f68caf..fde34132f1af02 100644 --- a/runtime/src/in_mem_accounts_index.rs +++ b/runtime/src/in_mem_accounts_index.rs @@ -1,23 +1,29 @@ -use crate::accounts_index::{ - AccountMapEntry, AccountMapEntryInner, AccountMapEntryMeta, IndexValue, - PreAllocatedAccountMapEntry, RefCount, SlotList, SlotSlice, ZeroLamport, +use { + crate::{ + accounts_index::{ + AccountMapEntry, AccountMapEntryInner, AccountMapEntryMeta, IndexValue, + PreAllocatedAccountMapEntry, RefCount, SlotList, SlotSlice, ZeroLamport, + }, + bucket_map_holder::{Age, BucketMapHolder}, + bucket_map_holder_stats::BucketMapHolderStats, + }, + rand::{thread_rng, Rng}, + solana_bucket_map::bucket_api::BucketApi, + solana_measure::measure::Measure, + solana_sdk::{clock::Slot, pubkey::Pubkey}, + std::{ + collections::{ + hash_map::{Entry, VacantEntry}, + HashMap, + }, + fmt::Debug, + ops::{Bound, RangeBounds, RangeInclusive}, + sync::{ + atomic::{AtomicBool, AtomicU64, AtomicU8, Ordering}, + Arc, RwLock, RwLockWriteGuard, + }, + }, }; -use crate::bucket_map_holder::{Age, BucketMapHolder}; -use crate::bucket_map_holder_stats::BucketMapHolderStats; -use rand::thread_rng; -use rand::Rng; -use solana_bucket_map::bucket_api::BucketApi; -use solana_measure::measure::Measure; -use solana_sdk::{clock::Slot, pubkey::Pubkey}; -use std::collections::{ - hash_map::{Entry, VacantEntry}, - HashMap, -}; -use std::ops::{Bound, RangeBounds, RangeInclusive}; -use std::sync::atomic::{AtomicBool, AtomicU64, AtomicU8, Ordering}; -use std::sync::{Arc, RwLock, RwLockWriteGuard}; - -use std::fmt::Debug; type K = Pubkey; type CacheRangesHeld = RwLock>>>; pub type SlotT = (Slot, T); @@ -918,8 +924,10 @@ impl InMemAccountsIndex { #[cfg(test)] mod tests { - use super::*; - use crate::accounts_index::{AccountsIndexConfig, BINS_FOR_TESTING}; + use { + super::*, + crate::accounts_index::{AccountsIndexConfig, BINS_FOR_TESTING}, + }; fn new_for_test() -> InMemAccountsIndex { let holder = Arc::new(BucketMapHolder::new( diff --git a/runtime/src/loader_utils.rs b/runtime/src/loader_utils.rs index 7580ef873b75f6..6c5196300c15ee 100644 --- a/runtime/src/loader_utils.rs +++ b/runtime/src/loader_utils.rs @@ -1,13 +1,15 @@ -use serde::Serialize; -use solana_sdk::{ - bpf_loader_upgradeable::{self, UpgradeableLoaderState}, - client::Client, - instruction::{AccountMeta, Instruction}, - loader_instruction, - message::Message, - pubkey::Pubkey, - signature::{Keypair, Signer}, - system_instruction, +use { + serde::Serialize, + solana_sdk::{ + bpf_loader_upgradeable::{self, UpgradeableLoaderState}, + client::Client, + instruction::{AccountMeta, Instruction}, + loader_instruction, + message::Message, + pubkey::Pubkey, + signature::{Keypair, Signer}, + system_instruction, + }, }; pub fn load_program( diff --git a/runtime/src/message_processor.rs b/runtime/src/message_processor.rs index c483f5a68b5ab0..5d0a7e7211a72e 100644 --- a/runtime/src/message_processor.rs +++ b/runtime/src/message_processor.rs @@ -1,24 +1,26 @@ -use serde::{Deserialize, Serialize}; -use solana_measure::measure::Measure; -use solana_program_runtime::{ - instruction_recorder::InstructionRecorder, - invoke_context::{BuiltinProgram, Executors, InvokeContext}, - log_collector::LogCollector, - timings::ExecuteDetailsTimings, -}; -use solana_sdk::{ - account::{AccountSharedData, WritableAccount}, - compute_budget::ComputeBudget, - feature_set::{prevent_calling_precompiles_as_programs, FeatureSet}, - hash::Hash, - message::Message, - precompiles::is_precompile, - pubkey::Pubkey, - rent::Rent, - sysvar::instructions, - transaction::TransactionError, +use { + serde::{Deserialize, Serialize}, + solana_measure::measure::Measure, + solana_program_runtime::{ + instruction_recorder::InstructionRecorder, + invoke_context::{BuiltinProgram, Executors, InvokeContext}, + log_collector::LogCollector, + timings::ExecuteDetailsTimings, + }, + solana_sdk::{ + account::{AccountSharedData, WritableAccount}, + compute_budget::ComputeBudget, + feature_set::{prevent_calling_precompiles_as_programs, FeatureSet}, + hash::Hash, + message::Message, + precompiles::is_precompile, + pubkey::Pubkey, + rent::Rent, + sysvar::instructions, + transaction::TransactionError, + }, + std::{cell::RefCell, rc::Rc, sync::Arc}, }; -use std::{cell::RefCell, rc::Rc, sync::Arc}; #[derive(Debug, Default, Clone, Deserialize, Serialize)] pub struct MessageProcessor {} @@ -134,16 +136,18 @@ impl MessageProcessor { #[cfg(test)] mod tests { - use super::*; - use crate::rent_collector::RentCollector; - use solana_sdk::{ - account::ReadableAccount, - instruction::{AccountMeta, Instruction, InstructionError}, - keyed_account::keyed_account_at_index, - message::Message, - native_loader::{self, create_loadable_account_for_test}, - secp256k1_instruction::new_secp256k1_instruction, - secp256k1_program, + use { + super::*, + crate::rent_collector::RentCollector, + solana_sdk::{ + account::ReadableAccount, + instruction::{AccountMeta, Instruction, InstructionError}, + keyed_account::keyed_account_at_index, + message::Message, + native_loader::{self, create_loadable_account_for_test}, + secp256k1_instruction::new_secp256k1_instruction, + secp256k1_program, + }, }; #[derive(Debug, Serialize, Deserialize)] diff --git a/runtime/src/non_circulating_supply.rs b/runtime/src/non_circulating_supply.rs index 6d66a6b48c1cb3..d00a4974957cff 100644 --- a/runtime/src/non_circulating_supply.rs +++ b/runtime/src/non_circulating_supply.rs @@ -217,15 +217,16 @@ solana_sdk::pubkeys!( #[cfg(test)] mod tests { - use super::*; - use solana_sdk::{ - account::Account, - account::AccountSharedData, - epoch_schedule::EpochSchedule, - genesis_config::{ClusterType, GenesisConfig}, - stake::state::{Authorized, Lockup, Meta}, + use { + super::*, + solana_sdk::{ + account::{Account, AccountSharedData}, + epoch_schedule::EpochSchedule, + genesis_config::{ClusterType, GenesisConfig}, + stake::state::{Authorized, Lockup, Meta}, + }, + std::{collections::BTreeMap, sync::Arc}, }; - use std::{collections::BTreeMap, sync::Arc}; fn new_from_parent(parent: &Arc) -> Bank { Bank::new_from_parent(parent, &Pubkey::default(), parent.slot() + 1) diff --git a/runtime/src/nonce_keyed_account.rs b/runtime/src/nonce_keyed_account.rs index aad7b537c603da..e154d86fe231a9 100644 --- a/runtime/src/nonce_keyed_account.rs +++ b/runtime/src/nonce_keyed_account.rs @@ -1,16 +1,18 @@ -use solana_program_runtime::{ic_msg, invoke_context::InvokeContext}; -use solana_sdk::{ - account::{ReadableAccount, WritableAccount}, - account_utils::State as AccountUtilsState, - feature_set::{self, nonce_must_be_writable}, - instruction::{checked_add, InstructionError}, - keyed_account::KeyedAccount, - nonce::{self, state::Versions, State}, - pubkey::Pubkey, - system_instruction::{nonce_to_instruction_error, NonceError}, - sysvar::rent::Rent, +use { + solana_program_runtime::{ic_msg, invoke_context::InvokeContext}, + solana_sdk::{ + account::{ReadableAccount, WritableAccount}, + account_utils::State as AccountUtilsState, + feature_set::{self, nonce_must_be_writable}, + instruction::{checked_add, InstructionError}, + keyed_account::KeyedAccount, + nonce::{self, state::Versions, State}, + pubkey::Pubkey, + system_instruction::{nonce_to_instruction_error, NonceError}, + sysvar::rent::Rent, + }, + std::collections::HashSet, }; -use std::collections::HashSet; pub trait NonceKeyedAccount { fn advance_nonce_account( @@ -313,16 +315,18 @@ impl<'a> NonceKeyedAccount for KeyedAccount<'a> { #[cfg(test)] mod test { - use super::*; - use solana_program_runtime::invoke_context::InvokeContext; - use solana_sdk::{ - account::ReadableAccount, - account_utils::State as AccountUtilsState, - hash::{hash, Hash}, - keyed_account::KeyedAccount, - nonce::{self, State}, - nonce_account::{create_account, verify_nonce_account}, - system_instruction::SystemError, + use { + super::*, + solana_program_runtime::invoke_context::InvokeContext, + solana_sdk::{ + account::ReadableAccount, + account_utils::State as AccountUtilsState, + hash::{hash, Hash}, + keyed_account::KeyedAccount, + nonce::{self, State}, + nonce_account::{create_account, verify_nonce_account}, + system_instruction::SystemError, + }, }; fn with_test_keyed_account(lamports: u64, signer: bool, f: F) diff --git a/runtime/src/read_only_accounts_cache.rs b/runtime/src/read_only_accounts_cache.rs index a9ba34b348d7c2..d4c023541b89c8 100644 --- a/runtime/src/read_only_accounts_cache.rs +++ b/runtime/src/read_only_accounts_cache.rs @@ -1,20 +1,21 @@ //! ReadOnlyAccountsCache used to store accounts, such as executable accounts, //! which can be large, loaded many times, and rarely change. -use dashmap::{mapref::entry::Entry, DashMap}; //use mapref::entry::{Entry, OccupiedEntry, VacantEntry}; -use solana_sdk::{ - account::{AccountSharedData, ReadableAccount}, - clock::Slot, - pubkey::Pubkey, -}; -use std::thread::{sleep, Builder, JoinHandle}; -use std::time::Duration; -use std::{ - sync::{ - atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}, - Arc, RwLock, +use { + dashmap::{mapref::entry::Entry, DashMap}, + solana_sdk::{ + account::{AccountSharedData, ReadableAccount}, + clock::Slot, + pubkey::Pubkey, + }, + std::{ + sync::{ + atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}, + Arc, RwLock, + }, + thread::{sleep, Builder, JoinHandle}, + time::{Duration, Instant}, }, - time::Instant, }; type ReadOnlyCacheKey = (Pubkey, Slot); @@ -240,8 +241,10 @@ impl ReadOnlyAccountsCache { #[cfg(test)] pub mod tests { - use super::*; - use solana_sdk::account::{accounts_equal, Account, WritableAccount}; + use { + super::*, + solana_sdk::account::{accounts_equal, Account, WritableAccount}, + }; #[test] fn test_accountsdb_sizeof() { // size_of(arc(x)) does not return the size of x diff --git a/runtime/src/rent_collector.rs b/runtime/src/rent_collector.rs index 0c8706c734fec0..2e51302b5c0f7f 100644 --- a/runtime/src/rent_collector.rs +++ b/runtime/src/rent_collector.rs @@ -146,8 +146,7 @@ impl RentCollector { #[cfg(test)] mod tests { - use super::*; - use solana_sdk::account::Account; + use {super::*, solana_sdk::account::Account}; #[test] fn test_collect_from_account_created_and_existing() { diff --git a/runtime/src/secondary_index.rs b/runtime/src/secondary_index.rs index 6b0e045423ff13..dd499a11c06107 100644 --- a/runtime/src/secondary_index.rs +++ b/runtime/src/secondary_index.rs @@ -1,11 +1,13 @@ -use dashmap::{mapref::entry::Entry::Occupied, DashMap}; -use solana_sdk::{pubkey::Pubkey, timing::AtomicInterval}; -use std::{ - collections::HashSet, - fmt::Debug, - sync::{ - atomic::{AtomicU64, Ordering}, - RwLock, +use { + dashmap::{mapref::entry::Entry::Occupied, DashMap}, + solana_sdk::{pubkey::Pubkey, timing::AtomicInterval}, + std::{ + collections::HashSet, + fmt::Debug, + sync::{ + atomic::{AtomicU64, Ordering}, + RwLock, + }, }, }; diff --git a/runtime/src/serde_snapshot.rs b/runtime/src/serde_snapshot.rs index 6a17e5ed40c553..600d8b823a2d79 100644 --- a/runtime/src/serde_snapshot.rs +++ b/runtime/src/serde_snapshot.rs @@ -1,3 +1,5 @@ +#[cfg(RUSTC_WITH_SPECIALIZATION)] +use solana_frozen_abi::abi_example::IgnoreAsHelper; use { crate::{ accounts::Accounts, @@ -17,8 +19,7 @@ use { serde_snapshot::future::SerializableStorage, stakes::Stakes, }, - bincode, - bincode::{config::Options, Error}, + bincode::{self, config::Options, Error}, log::*, rayon::prelude::*, serde::{de::DeserializeOwned, Deserialize, Serialize}, @@ -46,23 +47,18 @@ use { }, }; -#[cfg(RUSTC_WITH_SPECIALIZATION)] -use solana_frozen_abi::abi_example::IgnoreAsHelper; - mod common; mod future; mod tests; mod utils; -use future::Context as TypeContextFuture; -#[allow(unused_imports)] -use utils::{serialize_iter_as_map, serialize_iter_as_seq, serialize_iter_as_tuple}; - // a number of test cases in accounts_db use this #[cfg(test)] pub(crate) use self::tests::reconstruct_accounts_db_via_serialization; - pub(crate) use crate::accounts_db::{SnapshotStorage, SnapshotStorages}; +use future::Context as TypeContextFuture; +#[allow(unused_imports)] +use utils::{serialize_iter_as_map, serialize_iter_as_seq, serialize_iter_as_tuple}; #[derive(Copy, Clone, Eq, PartialEq)] pub(crate) enum SerdeStyle { diff --git a/runtime/src/serde_snapshot/common.rs b/runtime/src/serde_snapshot/common.rs index 23cdf45eecf395..e8464ea3def84f 100644 --- a/runtime/src/serde_snapshot/common.rs +++ b/runtime/src/serde_snapshot/common.rs @@ -1,5 +1,4 @@ -use super::*; -use std::collections::HashSet; +use {super::*, std::collections::HashSet}; #[derive(Default, Clone, PartialEq, Debug, Deserialize, Serialize, AbiExample)] pub(crate) struct UnusedAccounts { diff --git a/runtime/src/serde_snapshot/future.rs b/runtime/src/serde_snapshot/future.rs index 770384d4b8fcd5..8fd4a9a455ff04 100644 --- a/runtime/src/serde_snapshot/future.rs +++ b/runtime/src/serde_snapshot/future.rs @@ -1,9 +1,11 @@ -use super::common::UnusedAccounts; #[cfg(all(test, RUSTC_WITH_SPECIALIZATION))] use solana_frozen_abi::abi_example::IgnoreAsHelper; -use {super::*, solana_measure::measure::Measure, std::cell::RefCell}; - -use crate::ancestors::AncestorsForSerialization; +use { + super::{common::UnusedAccounts, *}, + crate::ancestors::AncestorsForSerialization, + solana_measure::measure::Measure, + std::cell::RefCell, +}; type AccountsDbFields = super::AccountsDbFields; diff --git a/runtime/src/shared_buffer_reader.rs b/runtime/src/shared_buffer_reader.rs index 7c8925caae688f..c6251d202ed6fa 100644 --- a/runtime/src/shared_buffer_reader.rs +++ b/runtime/src/shared_buffer_reader.rs @@ -483,9 +483,11 @@ impl Read for SharedBufferReader { #[cfg(test)] pub mod tests { - use super::*; - use crossbeam_channel::{unbounded, Receiver}; - use rayon::prelude::*; + use { + super::*, + crossbeam_channel::{unbounded, Receiver}, + rayon::prelude::*, + }; type SimpleReaderReceiverType = Receiver<(Vec, Option)>; struct SimpleReader { diff --git a/runtime/src/snapshot_archive_info.rs b/runtime/src/snapshot_archive_info.rs index a89f6bc38b63c8..353370e42a674c 100644 --- a/runtime/src/snapshot_archive_info.rs +++ b/runtime/src/snapshot_archive_info.rs @@ -1,8 +1,10 @@ //! Information about snapshot archives -use crate::snapshot_utils::{self, ArchiveFormat, Result}; -use solana_sdk::{clock::Slot, hash::Hash}; -use std::{cmp::Ordering, path::PathBuf}; +use { + crate::snapshot_utils::{self, ArchiveFormat, Result}, + solana_sdk::{clock::Slot, hash::Hash}, + std::{cmp::Ordering, path::PathBuf}, +}; /// Trait to query the snapshot archive information pub trait SnapshotArchiveInfoGetter { diff --git a/runtime/src/snapshot_config.rs b/runtime/src/snapshot_config.rs index cca9f732fcd37f..4a6061d3fdb248 100644 --- a/runtime/src/snapshot_config.rs +++ b/runtime/src/snapshot_config.rs @@ -1,6 +1,8 @@ -use crate::snapshot_utils::{self, ArchiveFormat, SnapshotVersion}; -use solana_sdk::clock::Slot; -use std::path::PathBuf; +use { + crate::snapshot_utils::{self, ArchiveFormat, SnapshotVersion}, + solana_sdk::clock::Slot, + std::path::PathBuf, +}; /// Snapshot configuration and runtime information #[derive(Clone, Debug)] diff --git a/runtime/src/snapshot_package.rs b/runtime/src/snapshot_package.rs index 6933e08acf31aa..59ffdbb64ea5df 100644 --- a/runtime/src/snapshot_package.rs +++ b/runtime/src/snapshot_package.rs @@ -1,26 +1,25 @@ -use crate::{ - accounts_db::SnapshotStorages, - bank::{Bank, BankSlotDelta}, -}; -use crate::{ - snapshot_archive_info::{SnapshotArchiveInfo, SnapshotArchiveInfoGetter}, - snapshot_utils::{ - self, ArchiveFormat, BankSnapshotInfo, Result, SnapshotVersion, TMP_BANK_SNAPSHOT_PREFIX, +use { + crate::{ + accounts_db::SnapshotStorages, + bank::{Bank, BankSlotDelta}, + snapshot_archive_info::{SnapshotArchiveInfo, SnapshotArchiveInfoGetter}, + snapshot_utils::{ + self, ArchiveFormat, BankSnapshotInfo, Result, SnapshotVersion, + TMP_BANK_SNAPSHOT_PREFIX, + }, }, -}; -use log::*; -use solana_sdk::clock::Slot; -use solana_sdk::genesis_config::ClusterType; -use solana_sdk::hash::Hash; -use std::{ - fs, - path::{Path, PathBuf}, - sync::{ - mpsc::{Receiver, SendError, Sender}, - Arc, Mutex, + log::*, + solana_sdk::{clock::Slot, genesis_config::ClusterType, hash::Hash}, + std::{ + fs, + path::{Path, PathBuf}, + sync::{ + mpsc::{Receiver, SendError, Sender}, + Arc, Mutex, + }, }, + tempfile::TempDir, }; -use tempfile::TempDir; /// The sender side of the AccountsPackage channel, used by AccountsBackgroundService pub type AccountsPackageSender = Sender; diff --git a/runtime/src/snapshot_utils.rs b/runtime/src/snapshot_utils.rs index 3d68c3671bb681..d33ca432842f66 100644 --- a/runtime/src/snapshot_utils.rs +++ b/runtime/src/snapshot_utils.rs @@ -1852,17 +1852,19 @@ pub fn should_take_incremental_snapshot( #[cfg(test)] mod tests { - use super::*; - use crate::accounts_db::ACCOUNTS_DB_CONFIG_FOR_TESTING; - use assert_matches::assert_matches; - use bincode::{deserialize_from, serialize_into}; - use solana_sdk::{ - genesis_config::create_genesis_config, - signature::{Keypair, Signer}, - system_transaction, - transaction::SanitizedTransaction, + use { + super::*, + crate::accounts_db::ACCOUNTS_DB_CONFIG_FOR_TESTING, + assert_matches::assert_matches, + bincode::{deserialize_from, serialize_into}, + solana_sdk::{ + genesis_config::create_genesis_config, + signature::{Keypair, Signer}, + system_transaction, + transaction::SanitizedTransaction, + }, + std::mem::size_of, }; - use std::mem::size_of; #[test] fn test_serialize_snapshot_data_file_under_limit() { diff --git a/runtime/src/sorted_storages.rs b/runtime/src/sorted_storages.rs index 362742007b2eee..0afe664409ae24 100644 --- a/runtime/src/sorted_storages.rs +++ b/runtime/src/sorted_storages.rs @@ -1,8 +1,7 @@ -use crate::accounts_db::SnapshotStorage; -use log::*; -use solana_measure::measure::Measure; -use solana_sdk::clock::Slot; -use std::ops::Range; +use { + crate::accounts_db::SnapshotStorage, log::*, solana_measure::measure::Measure, + solana_sdk::clock::Slot, std::ops::Range, +}; pub struct SortedStorages<'a> { range: Range, diff --git a/runtime/src/stake_weighted_timestamp.rs b/runtime/src/stake_weighted_timestamp.rs index 65acc3b613ffc8..aa2a2c0869d302 100644 --- a/runtime/src/stake_weighted_timestamp.rs +++ b/runtime/src/stake_weighted_timestamp.rs @@ -99,8 +99,10 @@ where #[cfg(test)] pub mod tests { - use super::*; - use solana_sdk::{account::Account, native_token::sol_to_lamports}; + use { + super::*, + solana_sdk::{account::Account, native_token::sol_to_lamports}, + }; #[test] fn test_calculate_stake_weighted_timestamp_uses_median() { diff --git a/runtime/src/stakes.rs b/runtime/src/stakes.rs index b64a9aa0877f85..e1db78324fa052 100644 --- a/runtime/src/stakes.rs +++ b/runtime/src/stakes.rs @@ -294,11 +294,13 @@ impl Stakes { #[cfg(test)] pub mod tests { - use super::*; - use rayon::ThreadPoolBuilder; - use solana_sdk::{account::WritableAccount, pubkey::Pubkey, rent::Rent}; - use solana_stake_program::stake_state; - use solana_vote_program::vote_state::{self, VoteState, VoteStateVersions}; + use { + super::*, + rayon::ThreadPoolBuilder, + solana_sdk::{account::WritableAccount, pubkey::Pubkey, rent::Rent}, + solana_stake_program::stake_state, + solana_vote_program::vote_state::{self, VoteState, VoteStateVersions}, + }; // set up some dummies for a staked node (( vote ) ( stake )) pub fn create_staked_node_accounts( diff --git a/runtime/src/status_cache.rs b/runtime/src/status_cache.rs index d07ee5356e8765..34f335ad75054b 100644 --- a/runtime/src/status_cache.rs +++ b/runtime/src/status_cache.rs @@ -1,15 +1,16 @@ -use crate::ancestors::Ancestors; - -use log::*; -use rand::{thread_rng, Rng}; -use serde::Serialize; -use solana_sdk::{ - clock::{Slot, MAX_RECENT_BLOCKHASHES}, - hash::Hash, -}; -use std::{ - collections::{hash_map::Entry, HashMap, HashSet}, - sync::{Arc, Mutex}, +use { + crate::ancestors::Ancestors, + log::*, + rand::{thread_rng, Rng}, + serde::Serialize, + solana_sdk::{ + clock::{Slot, MAX_RECENT_BLOCKHASHES}, + hash::Hash, + }, + std::{ + collections::{hash_map::Entry, HashMap, HashSet}, + sync::{Arc, Mutex}, + }, }; pub const MAX_CACHE_ENTRIES: usize = MAX_RECENT_BLOCKHASHES; @@ -294,8 +295,10 @@ impl StatusCache { #[cfg(test)] mod tests { - use super::*; - use solana_sdk::{hash::hash, signature::Signature}; + use { + super::*, + solana_sdk::{hash::hash, signature::Signature}, + }; type BankStatusCache = StatusCache<()>; diff --git a/runtime/src/system_instruction_processor.rs b/runtime/src/system_instruction_processor.rs index ddb3670d227e23..5161af7842c180 100644 --- a/runtime/src/system_instruction_processor.rs +++ b/runtime/src/system_instruction_processor.rs @@ -1,20 +1,24 @@ -use crate::nonce_keyed_account::NonceKeyedAccount; -use log::*; -use solana_program_runtime::{ic_msg, invoke_context::InvokeContext}; -use solana_sdk::{ - account::{AccountSharedData, ReadableAccount, WritableAccount}, - account_utils::StateMut, - feature_set, - instruction::InstructionError, - keyed_account::{from_keyed_account, get_signers, keyed_account_at_index, KeyedAccount}, - nonce, - program_utils::limited_deserialize, - pubkey::Pubkey, - system_instruction::{NonceError, SystemError, SystemInstruction, MAX_PERMITTED_DATA_LENGTH}, - system_program, - sysvar::{self, rent::Rent}, +use { + crate::nonce_keyed_account::NonceKeyedAccount, + log::*, + solana_program_runtime::{ic_msg, invoke_context::InvokeContext}, + solana_sdk::{ + account::{AccountSharedData, ReadableAccount, WritableAccount}, + account_utils::StateMut, + feature_set, + instruction::InstructionError, + keyed_account::{from_keyed_account, get_signers, keyed_account_at_index, KeyedAccount}, + nonce, + program_utils::limited_deserialize, + pubkey::Pubkey, + system_instruction::{ + NonceError, SystemError, SystemInstruction, MAX_PERMITTED_DATA_LENGTH, + }, + system_program, + sysvar::{self, rent::Rent}, + }, + std::collections::HashSet, }; -use std::collections::HashSet; // represents an address that may or may not have been generated // from a seed @@ -484,10 +488,6 @@ pub fn get_system_account_kind(account: &AccountSharedData) -> Option for Address { fn from(address: Pubkey) -> Self { diff --git a/runtime/src/transaction_batch.rs b/runtime/src/transaction_batch.rs index 5c6ce630446218..16bc747d88bc3f 100644 --- a/runtime/src/transaction_batch.rs +++ b/runtime/src/transaction_batch.rs @@ -49,9 +49,11 @@ impl<'a, 'b> Drop for TransactionBatch<'a, 'b> { #[cfg(test)] mod tests { - use super::*; - use crate::genesis_utils::{create_genesis_config_with_leader, GenesisConfigInfo}; - use solana_sdk::{signature::Keypair, system_transaction}; + use { + super::*, + crate::genesis_utils::{create_genesis_config_with_leader, GenesisConfigInfo}, + solana_sdk::{signature::Keypair, system_transaction}, + }; #[test] fn test_transaction_batch() { diff --git a/runtime/src/vote_account.rs b/runtime/src/vote_account.rs index f3b3d59f214616..453e54258f8ca3 100644 --- a/runtime/src/vote_account.rs +++ b/runtime/src/vote_account.rs @@ -1,9 +1,13 @@ use { itertools::Itertools, - serde::de::{Deserialize, Deserializer}, - serde::ser::{Serialize, Serializer}, + serde::{ + de::{Deserialize, Deserializer}, + ser::{Serialize, Serializer}, + }, solana_sdk::{ - account::Account, account::AccountSharedData, instruction::InstructionError, pubkey::Pubkey, + account::{Account, AccountSharedData}, + instruction::InstructionError, + pubkey::Pubkey, }, solana_vote_program::vote_state::VoteState, std::{ @@ -325,12 +329,14 @@ impl<'de> Deserialize<'de> for VoteAccounts { #[cfg(test)] mod tests { - use super::*; - use bincode::Options; - use rand::Rng; - use solana_sdk::{pubkey::Pubkey, sysvar::clock::Clock}; - use solana_vote_program::vote_state::{VoteInit, VoteStateVersions}; - use std::iter::repeat_with; + use { + super::*, + bincode::Options, + rand::Rng, + solana_sdk::{pubkey::Pubkey, sysvar::clock::Clock}, + solana_vote_program::vote_state::{VoteInit, VoteStateVersions}, + std::iter::repeat_with, + }; fn new_rand_vote_account( rng: &mut R, diff --git a/runtime/src/vote_sender_types.rs b/runtime/src/vote_sender_types.rs index 6d81b1916c5b55..ef7f245cd58232 100644 --- a/runtime/src/vote_sender_types.rs +++ b/runtime/src/vote_sender_types.rs @@ -1,6 +1,8 @@ -use crossbeam_channel::{Receiver, Sender}; -use solana_sdk::{hash::Hash, pubkey::Pubkey}; -use solana_vote_program::vote_state::Vote; +use { + crossbeam_channel::{Receiver, Sender}, + solana_sdk::{hash::Hash, pubkey::Pubkey}, + solana_vote_program::vote_state::Vote, +}; pub type ReplayedVote = (Pubkey, Vote, Option); pub type ReplayVoteSender = Sender; diff --git a/runtime/src/waitable_condvar.rs b/runtime/src/waitable_condvar.rs index b83441c0c94630..92fc68c2f408e5 100644 --- a/runtime/src/waitable_condvar.rs +++ b/runtime/src/waitable_condvar.rs @@ -30,13 +30,15 @@ impl WaitableCondvar { #[cfg(test)] pub mod tests { - use super::*; - use std::{ - sync::{ - atomic::{AtomicBool, Ordering}, - Arc, + use { + super::*, + std::{ + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, + }, + thread::Builder, }, - thread::Builder, }; #[ignore] #[test] diff --git a/runtime/store-tool/src/main.rs b/runtime/store-tool/src/main.rs index 68ed04231485c8..7c6c162ce45647 100644 --- a/runtime/store-tool/src/main.rs +++ b/runtime/store-tool/src/main.rs @@ -1,6 +1,8 @@ -use clap::{crate_description, crate_name, value_t_or_exit, App, Arg}; -use log::*; -use solana_runtime::append_vec::AppendVec; +use { + clap::{crate_description, crate_name, value_t_or_exit, App, Arg}, + log::*, + solana_runtime::append_vec::AppendVec, +}; fn main() { solana_logger::setup_with_default("solana=info"); diff --git a/runtime/tests/accounts.rs b/runtime/tests/accounts.rs index 5a3c4a4cbf0fbf..a055d62da14da5 100644 --- a/runtime/tests/accounts.rs +++ b/runtime/tests/accounts.rs @@ -1,20 +1,26 @@ -use log::*; -use rand::{thread_rng, Rng}; -use rayon::prelude::*; -use solana_runtime::{ - accounts_db::{AccountsDb, LoadHint}, - ancestors::Ancestors, +use { + log::*, + rand::{thread_rng, Rng}, + rayon::prelude::*, + solana_runtime::{ + accounts_db::{AccountsDb, LoadHint}, + ancestors::Ancestors, + }, + solana_sdk::{ + account::{AccountSharedData, ReadableAccount, WritableAccount}, + clock::Slot, + genesis_config::ClusterType, + pubkey::Pubkey, + }, + std::{ + collections::HashSet, + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, + }, + time::Instant, + }, }; -use solana_sdk::genesis_config::ClusterType; -use solana_sdk::{ - account::{AccountSharedData, ReadableAccount, WritableAccount}, - clock::Slot, - pubkey::Pubkey, -}; -use std::collections::HashSet; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::Arc; -use std::time::Instant; #[test] fn test_shrink_and_clean() { diff --git a/runtime/tests/bank.rs b/runtime/tests/bank.rs index b5f09b49655b55..7ec79e9afbd730 100644 --- a/runtime/tests/bank.rs +++ b/runtime/tests/bank.rs @@ -1,6 +1,8 @@ -use solana_runtime::bank::Bank; -use solana_sdk::{genesis_config::create_genesis_config, hash::hash}; -use std::{sync::Arc, thread::Builder}; +use { + solana_runtime::bank::Bank, + solana_sdk::{genesis_config::create_genesis_config, hash::hash}, + std::{sync::Arc, thread::Builder}, +}; #[test] fn test_race_register_tick_freeze() { diff --git a/runtime/tests/stake.rs b/runtime/tests/stake.rs index 00cca185e0f42d..cc4054e696ac42 100644 --- a/runtime/tests/stake.rs +++ b/runtime/tests/stake.rs @@ -1,28 +1,30 @@ #![allow(clippy::integer_arithmetic)] -use solana_runtime::{ - bank::Bank, - bank_client::BankClient, - genesis_utils::{create_genesis_config_with_leader, GenesisConfigInfo}, -}; -use solana_sdk::{ - account::from_account, - account_utils::StateMut, - client::SyncClient, - message::Message, - pubkey::Pubkey, - signature::{Keypair, Signer}, - stake::{ - self, instruction as stake_instruction, - state::{Authorized, Lockup, StakeState}, +use { + solana_runtime::{ + bank::Bank, + bank_client::BankClient, + genesis_utils::{create_genesis_config_with_leader, GenesisConfigInfo}, }, - sysvar::{self, stake_history::StakeHistory}, -}; -use solana_stake_program::stake_state; -use solana_vote_program::{ - vote_instruction, - vote_state::{Vote, VoteInit, VoteState, VoteStateVersions}, + solana_sdk::{ + account::from_account, + account_utils::StateMut, + client::SyncClient, + message::Message, + pubkey::Pubkey, + signature::{Keypair, Signer}, + stake::{ + self, instruction as stake_instruction, + state::{Authorized, Lockup, StakeState}, + }, + sysvar::{self, stake_history::StakeHistory}, + }, + solana_stake_program::stake_state, + solana_vote_program::{ + vote_instruction, + vote_state::{Vote, VoteInit, VoteState, VoteStateVersions}, + }, + std::sync::Arc, }; -use std::sync::Arc; fn next_epoch(bank: &Arc) -> Arc { bank.squash(); diff --git a/sdk/benches/serialize_instructions.rs b/sdk/benches/serialize_instructions.rs index 7495a313c69588..0788bdc5ab0b2a 100644 --- a/sdk/benches/serialize_instructions.rs +++ b/sdk/benches/serialize_instructions.rs @@ -1,13 +1,17 @@ #![feature(test)] extern crate test; -use bincode::{deserialize, serialize}; -use solana_sdk::instruction::{AccountMeta, Instruction}; -use solana_sdk::message::{Message, SanitizedMessage}; -use solana_sdk::pubkey::{self, Pubkey}; -use solana_sdk::sysvar::instructions; -use std::convert::TryFrom; -use test::Bencher; +use { + bincode::{deserialize, serialize}, + solana_sdk::{ + instruction::{AccountMeta, Instruction}, + message::{Message, SanitizedMessage}, + pubkey::{self, Pubkey}, + sysvar::instructions, + }, + std::convert::TryFrom, + test::Bencher, +}; fn make_instructions() -> Vec { let meta = AccountMeta::new(pubkey::new_rand(), false); diff --git a/sdk/benches/short_vec.rs b/sdk/benches/short_vec.rs index c1e687edf38002..0a73a7e0eb5ddb 100644 --- a/sdk/benches/short_vec.rs +++ b/sdk/benches/short_vec.rs @@ -1,9 +1,7 @@ #![feature(test)] extern crate test; -use bincode::deserialize; -use solana_sdk::short_vec::ShortVec; -use test::Bencher; +use {bincode::deserialize, solana_sdk::short_vec::ShortVec, test::Bencher}; // Return a ShortVec with 127 bytes fn create_encoded_short_vec() -> Vec { diff --git a/sdk/benches/slot_hashes.rs b/sdk/benches/slot_hashes.rs index 0167d8d777ede6..3d13d2de8f9304 100644 --- a/sdk/benches/slot_hashes.rs +++ b/sdk/benches/slot_hashes.rs @@ -1,12 +1,14 @@ #![feature(test)] extern crate test; -use solana_sdk::{ - account::{create_account_for_test, from_account}, - hash::Hash, - slot_hashes::{Slot, SlotHashes, MAX_ENTRIES}, +use { + solana_sdk::{ + account::{create_account_for_test, from_account}, + hash::Hash, + slot_hashes::{Slot, SlotHashes, MAX_ENTRIES}, + }, + test::Bencher, }; -use test::Bencher; #[bench] fn bench_to_from_account(b: &mut Bencher) { diff --git a/sdk/benches/slot_history.rs b/sdk/benches/slot_history.rs index 9da3cf69d08620..9ae9329139faf6 100644 --- a/sdk/benches/slot_history.rs +++ b/sdk/benches/slot_history.rs @@ -1,11 +1,13 @@ #![feature(test)] extern crate test; -use solana_sdk::{ - account::{create_account_for_test, from_account}, - slot_history::SlotHistory, +use { + solana_sdk::{ + account::{create_account_for_test, from_account}, + slot_history::SlotHistory, + }, + test::Bencher, }; -use test::Bencher; #[bench] fn bench_to_from_account(b: &mut Bencher) { diff --git a/sdk/cargo-build-bpf/src/main.rs b/sdk/cargo-build-bpf/src/main.rs index d9491e6d4a2ce0..d18ffaff6fe574 100644 --- a/sdk/cargo-build-bpf/src/main.rs +++ b/sdk/cargo-build-bpf/src/main.rs @@ -13,8 +13,7 @@ use { fs::{self, File}, io::{prelude::*, BufReader, BufWriter}, path::{Path, PathBuf}, - process::exit, - process::{Command, Stdio}, + process::{exit, Command, Stdio}, str::FromStr, }, tar::Archive, diff --git a/sdk/cargo-test-bpf/src/main.rs b/sdk/cargo-test-bpf/src/main.rs index 8c348745078ce5..e43bfa39a00128 100644 --- a/sdk/cargo-test-bpf/src/main.rs +++ b/sdk/cargo-test-bpf/src/main.rs @@ -1,14 +1,15 @@ -use clap::{ - crate_description, crate_name, crate_version, value_t, values_t, App, AppSettings, Arg, -}; -use std::{ - env, - ffi::OsStr, - fs::File, - io::{prelude::*, BufWriter}, - path::{Path, PathBuf}, - process::exit, - process::Command, +use { + clap::{ + crate_description, crate_name, crate_version, value_t, values_t, App, AppSettings, Arg, + }, + std::{ + env, + ffi::OsStr, + fs::File, + io::{prelude::*, BufWriter}, + path::{Path, PathBuf}, + process::{exit, Command}, + }, }; struct Config { diff --git a/sdk/macro/src/lib.rs b/sdk/macro/src/lib.rs index 95a8f3891dee65..8ffb6f54673cb9 100644 --- a/sdk/macro/src/lib.rs +++ b/sdk/macro/src/lib.rs @@ -4,17 +4,19 @@ extern crate proc_macro; -use proc_macro::TokenStream; -use proc_macro2::{Delimiter, Span, TokenTree}; -use quote::{quote, ToTokens}; -use std::convert::TryFrom; -use syn::{ - bracketed, - parse::{Parse, ParseStream, Result}, - parse_macro_input, - punctuated::Punctuated, - token::Bracket, - Expr, Ident, LitByte, LitStr, Path, Token, +use { + proc_macro::TokenStream, + proc_macro2::{Delimiter, Span, TokenTree}, + quote::{quote, ToTokens}, + std::convert::TryFrom, + syn::{ + bracketed, + parse::{Parse, ParseStream, Result}, + parse_macro_input, + punctuated::Punctuated, + token::Bracket, + Expr, Ident, LitByte, LitStr, Path, Token, + }, }; fn parse_id( diff --git a/sdk/program/src/account_info.rs b/sdk/program/src/account_info.rs index bd38eb64276bab..27150a7d0fe8e3 100644 --- a/sdk/program/src/account_info.rs +++ b/sdk/program/src/account_info.rs @@ -1,10 +1,12 @@ -use crate::{ - clock::Epoch, program_error::ProgramError, program_memory::sol_memset, pubkey::Pubkey, -}; -use std::{ - cell::{Ref, RefCell, RefMut}, - cmp, fmt, - rc::Rc, +use { + crate::{ + clock::Epoch, program_error::ProgramError, program_memory::sol_memset, pubkey::Pubkey, + }, + std::{ + cell::{Ref, RefCell, RefMut}, + cmp, fmt, + rc::Rc, + }, }; /// Account information diff --git a/sdk/program/src/blake3.rs b/sdk/program/src/blake3.rs index de219953cb823f..388833c47ae218 100644 --- a/sdk/program/src/blake3.rs +++ b/sdk/program/src/blake3.rs @@ -1,8 +1,10 @@ //! The `blake3` module provides functions for creating hashes. -use crate::sanitize::Sanitize; -use borsh::{BorshDeserialize, BorshSchema, BorshSerialize}; -use std::{convert::TryFrom, fmt, mem, str::FromStr}; -use thiserror::Error; +use { + crate::sanitize::Sanitize, + borsh::{BorshDeserialize, BorshSchema, BorshSerialize}, + std::{convert::TryFrom, fmt, mem, str::FromStr}, + thiserror::Error, +}; /// Size of hash pub const HASH_BYTES: usize = 32; diff --git a/sdk/program/src/bpf_loader_upgradeable.rs b/sdk/program/src/bpf_loader_upgradeable.rs index f086b5828223e6..9d56a0dddf9b76 100644 --- a/sdk/program/src/bpf_loader_upgradeable.rs +++ b/sdk/program/src/bpf_loader_upgradeable.rs @@ -8,13 +8,15 @@ //! upgradeable programs which still have a functioning authority. For more //! information refer to `loader_upgradeable_instruction.rs` -use crate::{ - instruction::{AccountMeta, Instruction, InstructionError}, - loader_upgradeable_instruction::UpgradeableLoaderInstruction, - pubkey::Pubkey, - system_instruction, sysvar, +use { + crate::{ + instruction::{AccountMeta, Instruction, InstructionError}, + loader_upgradeable_instruction::UpgradeableLoaderInstruction, + pubkey::Pubkey, + system_instruction, sysvar, + }, + bincode::serialized_size, }; -use bincode::serialized_size; crate::declare_id!("BPFLoaderUpgradeab1e11111111111111111111111"); diff --git a/sdk/program/src/decode_error.rs b/sdk/program/src/decode_error.rs index 7ca44864d7c9a2..4d94e767047647 100644 --- a/sdk/program/src/decode_error.rs +++ b/sdk/program/src/decode_error.rs @@ -13,8 +13,7 @@ pub trait DecodeError { #[cfg(test)] mod tests { - use super::*; - use num_derive::FromPrimitive; + use {super::*, num_derive::FromPrimitive}; #[test] fn test_decode_custom_error_to_enum() { diff --git a/sdk/program/src/entrypoint.rs b/sdk/program/src/entrypoint.rs index 6442ac9246607f..c342a80c9dc695 100644 --- a/sdk/program/src/entrypoint.rs +++ b/sdk/program/src/entrypoint.rs @@ -2,17 +2,18 @@ //! BPFLoader. For more information see './bpf_loader.rs' extern crate alloc; -use crate::{account_info::AccountInfo, program_error::ProgramError, pubkey::Pubkey}; -use alloc::vec::Vec; -use std::{ - alloc::Layout, - cell::RefCell, - mem::size_of, - ptr::null_mut, - rc::Rc, - // Hide Result from bindgen gets confused about generics in non-generic type declarations - result::Result as ResultGeneric, - slice::{from_raw_parts, from_raw_parts_mut}, +use { + crate::{account_info::AccountInfo, program_error::ProgramError, pubkey::Pubkey}, + alloc::vec::Vec, + std::{ + alloc::Layout, + cell::RefCell, + mem::size_of, + ptr::null_mut, + rc::Rc, + result::Result as ResultGeneric, + slice::{from_raw_parts, from_raw_parts_mut}, + }, }; pub type ProgramResult = ResultGeneric<(), ProgramError>; @@ -354,8 +355,7 @@ pub unsafe fn deserialize<'a>(input: *mut u8) -> (&'a Pubkey, Vec; diff --git a/sdk/program/src/feature.rs b/sdk/program/src/feature.rs index e754b64b186387..c9a2af15838a71 100644 --- a/sdk/program/src/feature.rs +++ b/sdk/program/src/feature.rs @@ -62,8 +62,7 @@ pub fn activate_with_lamports( #[cfg(test)] mod test { - use super::*; - use solana_program::clock::Slot; + use {super::*, solana_program::clock::Slot}; #[test] fn feature_sizeof() { diff --git a/sdk/program/src/fee_calculator.rs b/sdk/program/src/fee_calculator.rs index 41ecffd78a5b1e..cd7f7a8ece2f55 100644 --- a/sdk/program/src/fee_calculator.rs +++ b/sdk/program/src/fee_calculator.rs @@ -1,9 +1,8 @@ #![allow(clippy::integer_arithmetic)] -use crate::clock::DEFAULT_MS_PER_SLOT; -use crate::ed25519_program; -use crate::message::Message; -use crate::secp256k1_program; -use log::*; +use { + crate::{clock::DEFAULT_MS_PER_SLOT, ed25519_program, message::Message, secp256k1_program}, + log::*, +}; #[derive(Serialize, Deserialize, Default, PartialEq, Eq, Clone, Debug, AbiExample)] #[serde(rename_all = "camelCase")] @@ -176,8 +175,10 @@ impl FeeRateGovernor { #[cfg(test)] mod tests { - use super::*; - use crate::{pubkey::Pubkey, system_instruction}; + use { + super::*, + crate::{pubkey::Pubkey, system_instruction}, + }; #[test] fn test_fee_rate_governor_burn() { diff --git a/sdk/program/src/hash.rs b/sdk/program/src/hash.rs index b4f707ef891bce..c150268cd36e78 100644 --- a/sdk/program/src/hash.rs +++ b/sdk/program/src/hash.rs @@ -1,10 +1,12 @@ //! The `hash` module provides functions for creating SHA-256 hashes. -use crate::sanitize::Sanitize; -use borsh::{BorshDeserialize, BorshSchema, BorshSerialize}; -use sha2::{Digest, Sha256}; -use std::{convert::TryFrom, fmt, mem, str::FromStr}; -use thiserror::Error; +use { + crate::sanitize::Sanitize, + borsh::{BorshDeserialize, BorshSchema, BorshSerialize}, + sha2::{Digest, Sha256}, + std::{convert::TryFrom, fmt, mem, str::FromStr}, + thiserror::Error, +}; pub const HASH_BYTES: usize = 32; /// Maximum string length of a base58 encoded hash diff --git a/sdk/program/src/instruction.rs b/sdk/program/src/instruction.rs index d9c1396b099163..51324ab60953b3 100644 --- a/sdk/program/src/instruction.rs +++ b/sdk/program/src/instruction.rs @@ -1,12 +1,13 @@ #![allow(clippy::integer_arithmetic)] //! Defines a composable Instruction type and a memory-efficient CompiledInstruction. -use crate::sanitize::Sanitize; -use crate::{pubkey::Pubkey, short_vec}; -use bincode::serialize; -use borsh::BorshSerialize; -use serde::Serialize; -use thiserror::Error; +use { + crate::{pubkey::Pubkey, sanitize::Sanitize, short_vec}, + bincode::serialize, + borsh::BorshSerialize, + serde::Serialize, + thiserror::Error, +}; /// Reasons the runtime might have rejected an instruction. /// diff --git a/sdk/program/src/keccak.rs b/sdk/program/src/keccak.rs index 99db669b43c10e..2cb3c5fbd5ba92 100644 --- a/sdk/program/src/keccak.rs +++ b/sdk/program/src/keccak.rs @@ -1,8 +1,10 @@ -use crate::sanitize::Sanitize; -use borsh::{BorshDeserialize, BorshSchema, BorshSerialize}; -use sha3::{Digest, Keccak256}; -use std::{convert::TryFrom, fmt, mem, str::FromStr}; -use thiserror::Error; +use { + crate::sanitize::Sanitize, + borsh::{BorshDeserialize, BorshSchema, BorshSerialize}, + sha3::{Digest, Keccak256}, + std::{convert::TryFrom, fmt, mem, str::FromStr}, + thiserror::Error, +}; pub const HASH_BYTES: usize = 32; /// Maximum string length of a base58 encoded hash diff --git a/sdk/program/src/lamports.rs b/sdk/program/src/lamports.rs index 36ecb0ae0d7434..c1f77118937dbb 100644 --- a/sdk/program/src/lamports.rs +++ b/sdk/program/src/lamports.rs @@ -1,5 +1,4 @@ -use crate::instruction::InstructionError; -use thiserror::Error; +use {crate::instruction::InstructionError, thiserror::Error}; #[derive(Debug, Error)] pub enum LamportsError { diff --git a/sdk/program/src/message/legacy.rs b/sdk/program/src/message/legacy.rs index de607daa8d8b19..1961018c59aaa0 100644 --- a/sdk/program/src/message/legacy.rs +++ b/sdk/program/src/message/legacy.rs @@ -1,21 +1,23 @@ #![allow(clippy::integer_arithmetic)] //! A library for generating a message from a sequence of instructions -use crate::sanitize::{Sanitize, SanitizeError}; -use crate::serialize_utils::{ - append_slice, append_u16, append_u8, read_pubkey, read_slice, read_u16, read_u8, +use { + crate::{ + bpf_loader, bpf_loader_deprecated, bpf_loader_upgradeable, + hash::Hash, + instruction::{AccountMeta, CompiledInstruction, Instruction}, + message::MessageHeader, + pubkey::Pubkey, + sanitize::{Sanitize, SanitizeError}, + serialize_utils::{ + append_slice, append_u16, append_u8, read_pubkey, read_slice, read_u16, read_u8, + }, + short_vec, system_instruction, system_program, sysvar, + }, + itertools::Itertools, + lazy_static::lazy_static, + std::{convert::TryFrom, str::FromStr}, }; -use crate::{ - bpf_loader, bpf_loader_deprecated, bpf_loader_upgradeable, - hash::Hash, - instruction::{AccountMeta, CompiledInstruction, Instruction}, - message::MessageHeader, - pubkey::Pubkey, - short_vec, system_instruction, system_program, sysvar, -}; -use itertools::Itertools; -use lazy_static::lazy_static; -use std::{convert::TryFrom, str::FromStr}; lazy_static! { // Copied keys over since direct references create cyclical dependency. @@ -526,9 +528,11 @@ impl Message { #[cfg(test)] mod tests { #![allow(deprecated)] - use super::*; - use crate::{hash, instruction::AccountMeta, message::MESSAGE_HEADER_LENGTH}; - use std::collections::HashSet; + use { + super::*, + crate::{hash, instruction::AccountMeta, message::MESSAGE_HEADER_LENGTH}, + std::collections::HashSet, + }; #[test] fn test_message_unique_program_ids() { diff --git a/sdk/program/src/message/mapped.rs b/sdk/program/src/message/mapped.rs index 7c599fb6d9d2bf..4c60e4fd5d3c6a 100644 --- a/sdk/program/src/message/mapped.rs +++ b/sdk/program/src/message/mapped.rs @@ -114,7 +114,8 @@ impl MappedMessage { /// Returns true if the account at the specified index is called as a program by an instruction pub fn is_key_called_as_program(&self, key_index: usize) -> bool { if let Ok(key_index) = u8::try_from(key_index) { - self.message.instructions + self.message + .instructions .iter() .any(|ix| ix.program_id_index == key_index) } else { @@ -131,9 +132,11 @@ impl MappedMessage { #[cfg(test)] mod tests { - use super::*; - use crate::{instruction::CompiledInstruction, message::MessageHeader, system_program, sysvar}; - use itertools::Itertools; + use { + super::*, + crate::{instruction::CompiledInstruction, message::MessageHeader, system_program, sysvar}, + itertools::Itertools, + }; fn create_test_mapped_message() -> (MappedMessage, [Pubkey; 6]) { let key0 = Pubkey::new_unique(); @@ -279,13 +282,11 @@ mod tests { num_readonly_unsigned_accounts: 0, }, account_keys: vec![key0], - instructions: vec![ - CompiledInstruction { - program_id_index: 2, - accounts: vec![1], - data: vec![], - } - ], + instructions: vec![CompiledInstruction { + program_id_index: 2, + accounts: vec![1], + data: vec![], + }], ..v0::Message::default() }, mapped_addresses: MappedAddresses { diff --git a/sdk/program/src/message/mod.rs b/sdk/program/src/message/mod.rs index 37eb187af146b6..8c5737d38378d9 100644 --- a/sdk/program/src/message/mod.rs +++ b/sdk/program/src/message/mod.rs @@ -10,13 +10,10 @@ mod non_bpf_modules { pub mod v0; mod versions; - pub use mapped::*; - pub use sanitized::*; - pub use versions::*; + pub use {mapped::*, sanitized::*, versions::*}; } pub use legacy::Message; - #[cfg(not(target_arch = "bpf"))] pub use non_bpf_modules::*; diff --git a/sdk/program/src/message/sanitized.rs b/sdk/program/src/message/sanitized.rs index ba70b618f1568b..7a600e002243ea 100644 --- a/sdk/program/src/message/sanitized.rs +++ b/sdk/program/src/message/sanitized.rs @@ -300,10 +300,12 @@ impl SanitizedMessage { #[cfg(test)] mod tests { - use super::*; - use crate::{ - instruction::{AccountMeta, Instruction}, - message::v0, + use { + super::*, + crate::{ + instruction::{AccountMeta, Instruction}, + message::v0, + }, }; #[test] diff --git a/sdk/program/src/message/v0.rs b/sdk/program/src/message/v0.rs index 6b8b73abfc3d6f..9319d32157181d 100644 --- a/sdk/program/src/message/v0.rs +++ b/sdk/program/src/message/v0.rs @@ -127,8 +127,7 @@ impl Message { #[cfg(test)] mod tests { - use super::*; - use crate::message::VersionedMessage; + use {super::*, crate::message::VersionedMessage}; fn simple_message() -> Message { Message { diff --git a/sdk/program/src/message/versions.rs b/sdk/program/src/message/versions.rs index d31b313e2e5e5b..1ec621d74c0d50 100644 --- a/sdk/program/src/message/versions.rs +++ b/sdk/program/src/message/versions.rs @@ -10,7 +10,7 @@ use { serde::{ de::{self, Deserializer, SeqAccess, Visitor}, ser::{SerializeTuple, Serializer}, - {Deserialize, Serialize}, + Deserialize, Serialize, }, std::fmt, }; @@ -243,10 +243,12 @@ impl<'de> Deserialize<'de> for VersionedMessage { #[cfg(test)] mod tests { - use super::*; - use crate::{ - instruction::{AccountMeta, Instruction}, - message::v0::AddressMapIndexes, + use { + super::*, + crate::{ + instruction::{AccountMeta, Instruction}, + message::v0::AddressMapIndexes, + }, }; #[test] diff --git a/sdk/program/src/nonce/state/current.rs b/sdk/program/src/nonce/state/current.rs index e57139d58b66fe..50d1942db3d90d 100644 --- a/sdk/program/src/nonce/state/current.rs +++ b/sdk/program/src/nonce/state/current.rs @@ -1,6 +1,8 @@ -use super::Versions; -use crate::{fee_calculator::FeeCalculator, hash::Hash, pubkey::Pubkey}; -use serde_derive::{Deserialize, Serialize}; +use { + super::Versions, + crate::{fee_calculator::FeeCalculator, hash::Hash, pubkey::Pubkey}, + serde_derive::{Deserialize, Serialize}, +}; #[derive(Debug, Default, Serialize, Deserialize, PartialEq, Clone)] pub struct Data { diff --git a/sdk/program/src/nonce/state/mod.rs b/sdk/program/src/nonce/state/mod.rs index 18b1ffcb94977f..910843d2fd00db 100644 --- a/sdk/program/src/nonce/state/mod.rs +++ b/sdk/program/src/nonce/state/mod.rs @@ -1,6 +1,5 @@ mod current; pub use current::{Data, State}; - use serde_derive::{Deserialize, Serialize}; #[derive(Debug, Serialize, Deserialize, PartialEq, Clone)] diff --git a/sdk/program/src/program_error.rs b/sdk/program/src/program_error.rs index bce1a6a50e0eac..cc0f18f18667ef 100644 --- a/sdk/program/src/program_error.rs +++ b/sdk/program/src/program_error.rs @@ -1,9 +1,11 @@ #![allow(clippy::integer_arithmetic)] -use crate::{decode_error::DecodeError, instruction::InstructionError, msg, pubkey::PubkeyError}; -use borsh::maybestd::io::Error as BorshIoError; -use num_traits::{FromPrimitive, ToPrimitive}; -use std::convert::TryFrom; -use thiserror::Error; +use { + crate::{decode_error::DecodeError, instruction::InstructionError, msg, pubkey::PubkeyError}, + borsh::maybestd::io::Error as BorshIoError, + num_traits::{FromPrimitive, ToPrimitive}, + std::convert::TryFrom, + thiserror::Error, +}; /// Reasons the program may fail #[derive(Clone, Debug, Deserialize, Eq, Error, PartialEq, Serialize)] diff --git a/sdk/program/src/program_stubs.rs b/sdk/program/src/program_stubs.rs index 901e1aa70d0f0f..b3542062ad4ebe 100644 --- a/sdk/program/src/program_stubs.rs +++ b/sdk/program/src/program_stubs.rs @@ -2,12 +2,14 @@ #![cfg(not(target_arch = "bpf"))] -use crate::{ - account_info::AccountInfo, entrypoint::ProgramResult, instruction::Instruction, - program_error::UNSUPPORTED_SYSVAR, pubkey::Pubkey, +use { + crate::{ + account_info::AccountInfo, entrypoint::ProgramResult, instruction::Instruction, + program_error::UNSUPPORTED_SYSVAR, pubkey::Pubkey, + }, + itertools::Itertools, + std::sync::{Arc, RwLock}, }; -use itertools::Itertools; -use std::sync::{Arc, RwLock}; lazy_static::lazy_static! { static ref SYSCALL_STUBS: Arc>> = Arc::new(RwLock::new(Box::new(DefaultSyscallStubs {}))); diff --git a/sdk/program/src/pubkey.rs b/sdk/program/src/pubkey.rs index 764a1aabbe486c..2222f8a6f25f7a 100644 --- a/sdk/program/src/pubkey.rs +++ b/sdk/program/src/pubkey.rs @@ -393,8 +393,7 @@ impl fmt::Display for Pubkey { #[cfg(test)] mod tests { - use super::*; - use std::str::from_utf8; + use {super::*, std::str::from_utf8}; #[test] fn test_new_unique() { diff --git a/sdk/program/src/secp256k1_recover.rs b/sdk/program/src/secp256k1_recover.rs index 6325a885bd7bb7..6820884bfd23b5 100644 --- a/sdk/program/src/secp256k1_recover.rs +++ b/sdk/program/src/secp256k1_recover.rs @@ -1,6 +1,8 @@ -use borsh::{BorshDeserialize, BorshSchema, BorshSerialize}; -use core::convert::TryFrom; -use thiserror::Error; +use { + borsh::{BorshDeserialize, BorshSchema, BorshSerialize}, + core::convert::TryFrom, + thiserror::Error, +}; #[derive(Debug, Clone, PartialEq, Eq, Error)] pub enum Secp256k1RecoverError { diff --git a/sdk/program/src/serialize_utils.rs b/sdk/program/src/serialize_utils.rs index e334e3f4774338..24e85f648fbf25 100644 --- a/sdk/program/src/serialize_utils.rs +++ b/sdk/program/src/serialize_utils.rs @@ -1,6 +1,5 @@ #![allow(clippy::integer_arithmetic)] -use crate::pubkey::Pubkey; -use crate::sanitize::SanitizeError; +use crate::{pubkey::Pubkey, sanitize::SanitizeError}; pub fn append_u16(buf: &mut Vec, data: u16) { let start = buf.len(); diff --git a/sdk/program/src/short_vec.rs b/sdk/program/src/short_vec.rs index 8eac7395957113..15221bd86d8b51 100644 --- a/sdk/program/src/short_vec.rs +++ b/sdk/program/src/short_vec.rs @@ -1,10 +1,12 @@ #![allow(clippy::integer_arithmetic)] -use serde::{ - de::{self, Deserializer, SeqAccess, Visitor}, - ser::{self, SerializeTuple, Serializer}, - {Deserialize, Serialize}, +use { + serde::{ + de::{self, Deserializer, SeqAccess, Visitor}, + ser::{self, SerializeTuple, Serializer}, + Deserialize, Serialize, + }, + std::{convert::TryFrom, fmt, marker::PhantomData}, }; -use std::{convert::TryFrom, fmt, marker::PhantomData}; /// Same as u16, but serialized with 1 to 3 bytes. If the value is above /// 0x7f, the top bit is set and the remaining value is stored in the next @@ -265,9 +267,11 @@ pub fn decode_shortu16_len(bytes: &[u8]) -> Result<(usize, usize), ()> { #[cfg(test)] mod tests { - use super::*; - use assert_matches::assert_matches; - use bincode::{deserialize, serialize}; + use { + super::*, + assert_matches::assert_matches, + bincode::{deserialize, serialize}, + }; /// Return the serialized length. fn encode_len(len: u16) -> Vec { diff --git a/sdk/program/src/slot_hashes.rs b/sdk/program/src/slot_hashes.rs index e87d6ed9007352..1b1e65d8ebefa9 100644 --- a/sdk/program/src/slot_hashes.rs +++ b/sdk/program/src/slot_hashes.rs @@ -2,8 +2,10 @@ //! //! this account carries the Bank's most recent bank hashes for some N parents //! -use crate::hash::Hash; -use std::{iter::FromIterator, ops::Deref}; +use { + crate::hash::Hash, + std::{iter::FromIterator, ops::Deref}, +}; pub const MAX_ENTRIES: usize = 512; // about 2.5 minutes to get your vote in @@ -54,8 +56,7 @@ impl Deref for SlotHashes { #[cfg(test)] mod tests { - use super::*; - use crate::hash::hash; + use {super::*, crate::hash::hash}; #[test] fn test() { diff --git a/sdk/program/src/slot_history.rs b/sdk/program/src/slot_history.rs index 930df19bd9595b..dc0d0240a54a34 100644 --- a/sdk/program/src/slot_history.rs +++ b/sdk/program/src/slot_history.rs @@ -3,8 +3,7 @@ //! slot history //! pub use crate::clock::Slot; -use bv::BitVec; -use bv::BitsMut; +use bv::{BitVec, BitsMut}; #[repr(C)] #[derive(Clone, Serialize, Deserialize, PartialEq)] @@ -86,8 +85,7 @@ impl SlotHistory { #[cfg(test)] mod tests { - use super::*; - use log::*; + use {super::*, log::*}; #[test] fn slot_history_test1() { diff --git a/sdk/program/src/stake/instruction.rs b/sdk/program/src/stake/instruction.rs index fc0dec91a783fe..5ddd92b9df9f1c 100644 --- a/sdk/program/src/stake/instruction.rs +++ b/sdk/program/src/stake/instruction.rs @@ -1,14 +1,14 @@ use { - crate::stake::{ - config, - program::id, - state::{Authorized, Lockup, StakeAuthorize, StakeState}, - }, crate::{ clock::{Epoch, UnixTimestamp}, decode_error::DecodeError, instruction::{AccountMeta, Instruction}, pubkey::Pubkey, + stake::{ + config, + program::id, + state::{Authorized, Lockup, StakeAuthorize, StakeState}, + }, system_instruction, sysvar, }, log::*, @@ -680,8 +680,7 @@ pub fn set_lockup_checked( #[cfg(test)] mod tests { - use super::*; - use crate::instruction::InstructionError; + use {super::*, crate::instruction::InstructionError}; #[test] fn test_custom_error_decode() { diff --git a/sdk/program/src/stake_history.rs b/sdk/program/src/stake_history.rs index 3b3014322a9156..9a2dd0b9e539d3 100644 --- a/sdk/program/src/stake_history.rs +++ b/sdk/program/src/stake_history.rs @@ -3,7 +3,6 @@ //! this account carries history about stake activations and de-activations //! pub use crate::clock::Epoch; - use std::ops::Deref; pub const MAX_ENTRIES: usize = 512; // it should never take as many as 512 epochs to warm up or cool down diff --git a/sdk/program/src/system_instruction.rs b/sdk/program/src/system_instruction.rs index 26590b22526c6f..59c6255146671c 100644 --- a/sdk/program/src/system_instruction.rs +++ b/sdk/program/src/system_instruction.rs @@ -1,15 +1,17 @@ #[allow(deprecated)] use crate::sysvar::recent_blockhashes; -use crate::{ - decode_error::DecodeError, - instruction::{AccountMeta, Instruction, InstructionError}, - nonce, - pubkey::Pubkey, - system_program, - sysvar::rent, +use { + crate::{ + decode_error::DecodeError, + instruction::{AccountMeta, Instruction, InstructionError}, + nonce, + pubkey::Pubkey, + system_program, + sysvar::rent, + }, + num_derive::{FromPrimitive, ToPrimitive}, + thiserror::Error, }; -use num_derive::{FromPrimitive, ToPrimitive}; -use thiserror::Error; #[derive(Error, Debug, Serialize, Clone, PartialEq, FromPrimitive, ToPrimitive)] pub enum SystemError { @@ -573,9 +575,11 @@ pub fn authorize_nonce_account( #[cfg(test)] mod tests { - use super::*; - use crate::instruction::{Instruction, InstructionError}; - use num_traits::ToPrimitive; + use { + super::*, + crate::instruction::{Instruction, InstructionError}, + num_traits::ToPrimitive, + }; fn get_keys(instruction: &Instruction) -> Vec { instruction.accounts.iter().map(|x| x.pubkey).collect() diff --git a/sdk/program/src/sysvar/clock.rs b/sdk/program/src/sysvar/clock.rs index 89566a05747f0d..d6a8c73d81f51b 100644 --- a/sdk/program/src/sysvar/clock.rs +++ b/sdk/program/src/sysvar/clock.rs @@ -1,7 +1,6 @@ //! This account contains the clock slot, epoch, and leader_schedule_epoch //! pub use crate::clock::Clock; - use crate::{impl_sysvar_get, program_error::ProgramError, sysvar::Sysvar}; crate::declare_sysvar_id!("SysvarC1ock11111111111111111111111111111111", Clock); diff --git a/sdk/program/src/sysvar/epoch_schedule.rs b/sdk/program/src/sysvar/epoch_schedule.rs index 502d477d9ec43f..d5b1a81a106f52 100644 --- a/sdk/program/src/sysvar/epoch_schedule.rs +++ b/sdk/program/src/sysvar/epoch_schedule.rs @@ -1,7 +1,6 @@ //! This account contains the current cluster rent //! pub use crate::epoch_schedule::EpochSchedule; - use crate::{impl_sysvar_get, program_error::ProgramError, sysvar::Sysvar}; crate::declare_sysvar_id!("SysvarEpochSchedu1e111111111111111111111111", EpochSchedule); diff --git a/sdk/program/src/sysvar/instructions.rs b/sdk/program/src/sysvar/instructions.rs index df43c0c8b0b0d3..bd50d87fb7af76 100644 --- a/sdk/program/src/sysvar/instructions.rs +++ b/sdk/program/src/sysvar/instructions.rs @@ -118,9 +118,11 @@ pub fn get_instruction_relative( #[cfg(test)] mod tests { - use super::*; - use crate::{instruction::AccountMeta, message::Message, pubkey::Pubkey}; - use std::convert::TryFrom; + use { + super::*, + crate::{instruction::AccountMeta, message::Message, pubkey::Pubkey}, + std::convert::TryFrom, + }; #[test] fn test_load_store_instruction() { diff --git a/sdk/program/src/sysvar/mod.rs b/sdk/program/src/sysvar/mod.rs index 597ec2891196ae..cabb9e785ea86a 100644 --- a/sdk/program/src/sysvar/mod.rs +++ b/sdk/program/src/sysvar/mod.rs @@ -1,7 +1,9 @@ //! named accounts for synthesized data accounts for bank state, etc. //! -use crate::{account_info::AccountInfo, program_error::ProgramError, pubkey::Pubkey}; -use lazy_static::lazy_static; +use { + crate::{account_info::AccountInfo, program_error::ProgramError, pubkey::Pubkey}, + lazy_static::lazy_static, +}; pub mod clock; pub mod epoch_schedule; @@ -140,9 +142,11 @@ macro_rules! impl_sysvar_get { #[cfg(test)] mod tests { - use super::*; - use crate::{clock::Epoch, program_error::ProgramError, pubkey::Pubkey}; - use std::{cell::RefCell, rc::Rc}; + use { + super::*, + crate::{clock::Epoch, program_error::ProgramError, pubkey::Pubkey}, + std::{cell::RefCell, rc::Rc}, + }; #[repr(C)] #[derive(Serialize, Deserialize, Debug, Default, PartialEq)] diff --git a/sdk/program/src/sysvar/recent_blockhashes.rs b/sdk/program/src/sysvar/recent_blockhashes.rs index e67213546cac9b..3647ebab267fe8 100644 --- a/sdk/program/src/sysvar/recent_blockhashes.rs +++ b/sdk/program/src/sysvar/recent_blockhashes.rs @@ -1,12 +1,14 @@ #![allow(deprecated)] #![allow(clippy::integer_arithmetic)] -use crate::{ - declare_deprecated_sysvar_id, - fee_calculator::FeeCalculator, - hash::{hash, Hash}, - sysvar::Sysvar, +use { + crate::{ + declare_deprecated_sysvar_id, + fee_calculator::FeeCalculator, + hash::{hash, Hash}, + sysvar::Sysvar, + }, + std::{cmp::Ordering, collections::BinaryHeap, iter::FromIterator, ops::Deref}, }; -use std::{cmp::Ordering, collections::BinaryHeap, iter::FromIterator, ops::Deref}; #[deprecated( since = "1.9.0", @@ -161,8 +163,7 @@ pub fn create_test_recent_blockhashes(start: usize) -> RecentBlockhashes { #[cfg(test)] mod tests { - use super::*; - use crate::clock::MAX_PROCESSING_AGE; + use {super::*, crate::clock::MAX_PROCESSING_AGE}; #[test] #[allow(clippy::assertions_on_constants)] diff --git a/sdk/program/src/sysvar/rent.rs b/sdk/program/src/sysvar/rent.rs index 13e7f323672fa6..83f2dfdecb0996 100644 --- a/sdk/program/src/sysvar/rent.rs +++ b/sdk/program/src/sysvar/rent.rs @@ -1,7 +1,6 @@ //! This account contains the current cluster rent //! pub use crate::rent::Rent; - use crate::{impl_sysvar_get, program_error::ProgramError, sysvar::Sysvar}; crate::declare_sysvar_id!("SysvarRent111111111111111111111111111111111", Rent); diff --git a/sdk/program/src/sysvar/slot_hashes.rs b/sdk/program/src/sysvar/slot_hashes.rs index d10cb57d8a9f98..e1f9d10a87c002 100644 --- a/sdk/program/src/sysvar/slot_hashes.rs +++ b/sdk/program/src/sysvar/slot_hashes.rs @@ -3,7 +3,6 @@ //! this account carries the Bank's most recent bank hashes for some N parents //! pub use crate::slot_hashes::SlotHashes; - use crate::{account_info::AccountInfo, program_error::ProgramError, sysvar::Sysvar}; crate::declare_sysvar_id!("SysvarS1otHashes111111111111111111111111111", SlotHashes); @@ -22,8 +21,10 @@ impl Sysvar for SlotHashes { #[cfg(test)] mod tests { - use super::*; - use crate::{clock::Slot, hash::Hash, slot_hashes::MAX_ENTRIES}; + use { + super::*, + crate::{clock::Slot, hash::Hash, slot_hashes::MAX_ENTRIES}, + }; #[test] fn test_size_of() { diff --git a/sdk/program/src/sysvar/slot_history.rs b/sdk/program/src/sysvar/slot_history.rs index fae51b2f26ede3..a180a2398ff389 100644 --- a/sdk/program/src/sysvar/slot_history.rs +++ b/sdk/program/src/sysvar/slot_history.rs @@ -3,12 +3,11 @@ //! this account carries a bitvector of slots present over the past //! epoch //! +use crate::sysvar::Sysvar; pub use crate::{ account_info::AccountInfo, program_error::ProgramError, slot_history::SlotHistory, }; -use crate::sysvar::Sysvar; - crate::declare_sysvar_id!("SysvarS1otHistory11111111111111111111111111", SlotHistory); impl Sysvar for SlotHistory { diff --git a/sdk/program/src/sysvar/stake_history.rs b/sdk/program/src/sysvar/stake_history.rs index 7b18ea73e627ae..ef527304894f0f 100644 --- a/sdk/program/src/sysvar/stake_history.rs +++ b/sdk/program/src/sysvar/stake_history.rs @@ -3,7 +3,6 @@ //! this account carries history about stake activations and de-activations //! pub use crate::stake_history::StakeHistory; - use crate::sysvar::Sysvar; crate::declare_sysvar_id!("SysvarStakeHistory1111111111111111111111111", StakeHistory); @@ -18,8 +17,7 @@ impl Sysvar for StakeHistory { #[cfg(test)] mod tests { - use super::*; - use crate::stake_history::*; + use {super::*, crate::stake_history::*}; #[test] fn test_size_of() { diff --git a/sdk/src/account.rs b/sdk/src/account.rs index 9d250162d5969b..0ec77fc6d0f84a 100644 --- a/sdk/src/account.rs +++ b/sdk/src/account.rs @@ -1,10 +1,17 @@ -use crate::{ - clock::{Epoch, INITIAL_RENT_EPOCH}, - lamports::LamportsError, - pubkey::Pubkey, +use { + crate::{ + clock::{Epoch, INITIAL_RENT_EPOCH}, + lamports::LamportsError, + pubkey::Pubkey, + }, + solana_program::{account_info::AccountInfo, sysvar::Sysvar}, + std::{ + cell::{Ref, RefCell}, + cmp, fmt, + rc::Rc, + sync::Arc, + }, }; -use solana_program::{account_info::AccountInfo, sysvar::Sysvar}; -use std::{cell::Ref, cell::RefCell, cmp, fmt, rc::Rc, sync::Arc}; /// An Account with data that is stored on chain #[repr(C)] diff --git a/sdk/src/account_utils.rs b/sdk/src/account_utils.rs index a7f5f30366344c..226fcb83233d9d 100644 --- a/sdk/src/account_utils.rs +++ b/sdk/src/account_utils.rs @@ -1,7 +1,12 @@ //! useful extras for Account state -use crate::{account::Account, account::AccountSharedData, instruction::InstructionError}; -use bincode::ErrorKind; -use std::cell::Ref; +use { + crate::{ + account::{Account, AccountSharedData}, + instruction::InstructionError, + }, + bincode::ErrorKind, + std::cell::Ref, +}; /// Convenience trait to covert bincode errors to instruction errors. pub trait StateMut { @@ -60,8 +65,10 @@ where #[cfg(test)] mod tests { - use super::*; - use crate::{account::AccountSharedData, pubkey::Pubkey}; + use { + super::*, + crate::{account::AccountSharedData, pubkey::Pubkey}, + }; #[test] fn test_account_state() { diff --git a/sdk/src/commitment_config.rs b/sdk/src/commitment_config.rs index 1e77c659685a6e..a3f7da1cb685bd 100644 --- a/sdk/src/commitment_config.rs +++ b/sdk/src/commitment_config.rs @@ -1,8 +1,7 @@ #![allow(deprecated)] #![cfg(feature = "full")] -use std::str::FromStr; -use thiserror::Error; +use {std::str::FromStr, thiserror::Error}; #[derive(Serialize, Deserialize, Default, Clone, Copy, Debug, PartialEq, Eq, Hash)] #[serde(rename_all = "camelCase")] diff --git a/sdk/src/compute_budget.rs b/sdk/src/compute_budget.rs index 3bdb7bb3994e75..9fdb2b9283149d 100644 --- a/sdk/src/compute_budget.rs +++ b/sdk/src/compute_budget.rs @@ -158,10 +158,12 @@ impl ComputeBudget { #[cfg(test)] mod tests { - use super::*; - use crate::{ - hash::Hash, message::Message, pubkey::Pubkey, signature::Keypair, signer::Signer, - transaction::Transaction, + use { + super::*, + crate::{ + hash::Hash, message::Message, pubkey::Pubkey, signature::Keypair, signer::Signer, + transaction::Transaction, + }, }; macro_rules! test { diff --git a/sdk/src/derivation_path.rs b/sdk/src/derivation_path.rs index 06feb0cfbd2e5b..a90b715e37353c 100644 --- a/sdk/src/derivation_path.rs +++ b/sdk/src/derivation_path.rs @@ -260,8 +260,7 @@ impl Bip44 for Solana { #[cfg(test)] mod tests { - use super::*; - use uriparse::URIReferenceBuilder; + use {super::*, uriparse::URIReferenceBuilder}; struct TestCoin; impl Bip44 for TestCoin { diff --git a/sdk/src/deserialize_utils.rs b/sdk/src/deserialize_utils.rs index e6293e293d6669..9eb37d2e056518 100644 --- a/sdk/src/deserialize_utils.rs +++ b/sdk/src/deserialize_utils.rs @@ -18,8 +18,7 @@ where #[cfg(test)] pub mod tests { - use super::*; - use bincode::deserialize; + use {super::*, bincode::deserialize}; #[test] fn test_default_on_eof() { diff --git a/sdk/src/ed25519_instruction.rs b/sdk/src/ed25519_instruction.rs index 6d52fbf369cd8c..801345f1f43200 100644 --- a/sdk/src/ed25519_instruction.rs +++ b/sdk/src/ed25519_instruction.rs @@ -1,9 +1,11 @@ #![cfg(feature = "full")] -use crate::{feature_set::FeatureSet, instruction::Instruction, precompiles::PrecompileError}; -use bytemuck::{bytes_of, Pod, Zeroable}; -use ed25519_dalek::{ed25519::signature::Signature, Signer, Verifier}; -use std::sync::Arc; +use { + crate::{feature_set::FeatureSet, instruction::Instruction, precompiles::PrecompileError}, + bytemuck::{bytes_of, Pod, Zeroable}, + ed25519_dalek::{ed25519::signature::Signature, Signer, Verifier}, + std::sync::Arc, +}; pub const PUBKEY_SERIALIZED_SIZE: usize = 32; pub const SIGNATURE_SERIALIZED_SIZE: usize = 64; @@ -173,16 +175,18 @@ fn get_data_slice<'a>( #[cfg(test)] pub mod test { - use super::*; - use crate::{ - ed25519_instruction::new_ed25519_instruction, - feature_set::FeatureSet, - hash::Hash, - signature::{Keypair, Signer}, - transaction::Transaction, + use { + super::*, + crate::{ + ed25519_instruction::new_ed25519_instruction, + feature_set::FeatureSet, + hash::Hash, + signature::{Keypair, Signer}, + transaction::Transaction, + }, + rand::{thread_rng, Rng}, + std::sync::Arc, }; - use rand::{thread_rng, Rng}; - use std::sync::Arc; fn test_case( num_signatures: u16, diff --git a/sdk/src/feature_set.rs b/sdk/src/feature_set.rs index 5d77e65823f07a..cef24b5b6faae5 100644 --- a/sdk/src/feature_set.rs +++ b/sdk/src/feature_set.rs @@ -18,13 +18,15 @@ //! //! For more information on how features are picked up, see comments for `Feature`. -use lazy_static::lazy_static; -use solana_sdk::{ - clock::Slot, - hash::{Hash, Hasher}, - pubkey::Pubkey, +use { + lazy_static::lazy_static, + solana_sdk::{ + clock::Slot, + hash::{Hash, Hasher}, + pubkey::Pubkey, + }, + std::collections::{HashMap, HashSet}, }; -use std::collections::{HashMap, HashSet}; pub mod deprecate_rewards_sysvar { solana_sdk::declare_id!("GaBtBJvmS4Arjj5W1NmFcyvPjsHN38UGYDq2MDwbs9Qu"); diff --git a/sdk/src/genesis_config.rs b/sdk/src/genesis_config.rs index 8b1831d536df5a..b038e6e07b18da 100644 --- a/sdk/src/genesis_config.rs +++ b/sdk/src/genesis_config.rs @@ -2,34 +2,35 @@ #![cfg(feature = "full")] -use crate::{ - account::Account, - account::AccountSharedData, - clock::{UnixTimestamp, DEFAULT_TICKS_PER_SLOT}, - epoch_schedule::EpochSchedule, - fee_calculator::FeeRateGovernor, - hash::{hash, Hash}, - inflation::Inflation, - native_token::lamports_to_sol, - poh_config::PohConfig, - pubkey::Pubkey, - rent::Rent, - shred_version::compute_shred_version, - signature::{Keypair, Signer}, - system_program, - timing::years_as_slots, -}; -use bincode::{deserialize, serialize}; -use chrono::{TimeZone, Utc}; -use memmap2::Mmap; -use std::{ - collections::BTreeMap, - fmt, - fs::{File, OpenOptions}, - io::Write, - path::{Path, PathBuf}, - str::FromStr, - time::{SystemTime, UNIX_EPOCH}, +use { + crate::{ + account::{Account, AccountSharedData}, + clock::{UnixTimestamp, DEFAULT_TICKS_PER_SLOT}, + epoch_schedule::EpochSchedule, + fee_calculator::FeeRateGovernor, + hash::{hash, Hash}, + inflation::Inflation, + native_token::lamports_to_sol, + poh_config::PohConfig, + pubkey::Pubkey, + rent::Rent, + shred_version::compute_shred_version, + signature::{Keypair, Signer}, + system_program, + timing::years_as_slots, + }, + bincode::{deserialize, serialize}, + chrono::{TimeZone, Utc}, + memmap2::Mmap, + std::{ + collections::BTreeMap, + fmt, + fs::{File, OpenOptions}, + io::Write, + path::{Path, PathBuf}, + str::FromStr, + time::{SystemTime, UNIX_EPOCH}, + }, }; pub const DEFAULT_GENESIS_FILE: &str = "genesis.bin"; @@ -291,9 +292,11 @@ impl fmt::Display for GenesisConfig { #[cfg(test)] mod tests { - use super::*; - use crate::signature::{Keypair, Signer}; - use std::path::PathBuf; + use { + super::*, + crate::signature::{Keypair, Signer}, + std::path::PathBuf, + }; fn make_tmp_path(name: &str) -> PathBuf { let out_dir = std::env::var("FARF_DIR").unwrap_or_else(|_| "farf".to_string()); diff --git a/sdk/src/hard_forks.rs b/sdk/src/hard_forks.rs index 1714fef45833ed..a83168ce372fe1 100644 --- a/sdk/src/hard_forks.rs +++ b/sdk/src/hard_forks.rs @@ -3,8 +3,10 @@ #![cfg(feature = "full")] -use byteorder::{ByteOrder, LittleEndian}; -use solana_sdk::clock::Slot; +use { + byteorder::{ByteOrder, LittleEndian}, + solana_sdk::clock::Slot, +}; #[derive(Default, Clone, Debug, Deserialize, Serialize, AbiExample, PartialEq, Eq)] pub struct HardForks { diff --git a/sdk/src/keyed_account.rs b/sdk/src/keyed_account.rs index d53a22711998f2..5c1ef91056f55b 100644 --- a/sdk/src/keyed_account.rs +++ b/sdk/src/keyed_account.rs @@ -1,12 +1,14 @@ -use crate::{ - account::{from_account, AccountSharedData, ReadableAccount}, - account_utils::{State, StateMut}, -}; -use solana_program::{clock::Epoch, instruction::InstructionError, pubkey::Pubkey, sysvar::Sysvar}; -use std::{ - cell::{Ref, RefCell, RefMut}, - iter::FromIterator, - rc::Rc, +use { + crate::{ + account::{from_account, AccountSharedData, ReadableAccount}, + account_utils::{State, StateMut}, + }, + solana_program::{clock::Epoch, instruction::InstructionError, pubkey::Pubkey, sysvar::Sysvar}, + std::{ + cell::{Ref, RefCell, RefMut}, + iter::FromIterator, + rc::Rc, + }, }; #[repr(C)] @@ -258,12 +260,14 @@ pub fn from_keyed_account( #[cfg(test)] mod tests { - use super::*; - use crate::{ - account::{create_account_for_test, to_account}, - pubkey::Pubkey, + use { + super::*, + crate::{ + account::{create_account_for_test, to_account}, + pubkey::Pubkey, + }, + std::cell::RefCell, }; - use std::cell::RefCell; #[repr(C)] #[derive(Serialize, Deserialize, Debug, Default, PartialEq)] diff --git a/sdk/src/native_loader.rs b/sdk/src/native_loader.rs index eaed82badedfb6..68b835e1bb7279 100644 --- a/sdk/src/native_loader.rs +++ b/sdk/src/native_loader.rs @@ -1,7 +1,9 @@ -use crate::account::{ - Account, AccountSharedData, InheritableAccountFields, DUMMY_INHERITABLE_ACCOUNT_FIELDS, +use crate::{ + account::{ + Account, AccountSharedData, InheritableAccountFields, DUMMY_INHERITABLE_ACCOUNT_FIELDS, + }, + clock::INITIAL_RENT_EPOCH, }; -use crate::clock::INITIAL_RENT_EPOCH; crate::declare_id!("NativeLoader1111111111111111111111111111111"); diff --git a/sdk/src/nonce_account.rs b/sdk/src/nonce_account.rs index bdca92ed181255..23e4a9285dec61 100644 --- a/sdk/src/nonce_account.rs +++ b/sdk/src/nonce_account.rs @@ -1,10 +1,12 @@ -use crate::{ - account::{AccountSharedData, ReadableAccount}, - account_utils::StateMut, - hash::Hash, - nonce::{state::Versions, State}, +use { + crate::{ + account::{AccountSharedData, ReadableAccount}, + account_utils::StateMut, + hash::Hash, + nonce::{state::Versions, State}, + }, + std::cell::RefCell, }; -use std::cell::RefCell; pub fn create_account(lamports: u64) -> RefCell { RefCell::new( @@ -40,8 +42,7 @@ pub fn lamports_per_signature_of(account: &AccountSharedData) -> Option { #[cfg(test)] mod tests { - use super::*; - use crate::pubkey::Pubkey; + use {super::*, crate::pubkey::Pubkey}; #[test] fn test_verify_bad_account_owner_fails() { diff --git a/sdk/src/packet.rs b/sdk/src/packet.rs index 62b9e0f960400a..27435b3ae677fb 100644 --- a/sdk/src/packet.rs +++ b/sdk/src/packet.rs @@ -1,9 +1,11 @@ -use crate::clock::Slot; -use bincode::Result; -use serde::Serialize; -use std::{ - net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}, - {fmt, io}, +use { + crate::clock::Slot, + bincode::Result, + serde::Serialize, + std::{ + fmt, io, + net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}, + }, }; /// Maximum over-the-wire size of a Transaction diff --git a/sdk/src/poh_config.rs b/sdk/src/poh_config.rs index a3933657502763..9639ed45309cf9 100644 --- a/sdk/src/poh_config.rs +++ b/sdk/src/poh_config.rs @@ -1,5 +1,7 @@ -use crate::{clock::DEFAULT_TICKS_PER_SECOND, unchecked_div_by_const}; -use std::time::Duration; +use { + crate::{clock::DEFAULT_TICKS_PER_SECOND, unchecked_div_by_const}, + std::time::Duration, +}; #[derive(Serialize, Deserialize, Clone, Debug, AbiExample)] pub struct PohConfig { diff --git a/sdk/src/program_utils.rs b/sdk/src/program_utils.rs index cfe8033479c8c4..590e81ae39007b 100644 --- a/sdk/src/program_utils.rs +++ b/sdk/src/program_utils.rs @@ -1,5 +1,4 @@ -use crate::instruction::InstructionError; -use bincode::config::Options; +use {crate::instruction::InstructionError, bincode::config::Options}; /// Deserialize with a limit based the maximum amount of data a program can expect to get. /// This function should be used in place of direct deserialization to help prevent OOM errors diff --git a/sdk/src/pubkey.rs b/sdk/src/pubkey.rs index a5fe36addefa3d..4b343ae629c023 100644 --- a/sdk/src/pubkey.rs +++ b/sdk/src/pubkey.rs @@ -33,8 +33,7 @@ pub fn read_pubkey_file(infile: &str) -> Result Result<(), Box> { diff --git a/sdk/src/recent_blockhashes_account.rs b/sdk/src/recent_blockhashes_account.rs index 1aac867a13d6e1..73cb1ecf72d433 100644 --- a/sdk/src/recent_blockhashes_account.rs +++ b/sdk/src/recent_blockhashes_account.rs @@ -1,13 +1,17 @@ -use crate::account::{ - create_account_shared_data_with_fields, to_account, AccountSharedData, - InheritableAccountFields, DUMMY_INHERITABLE_ACCOUNT_FIELDS, -}; -use crate::clock::INITIAL_RENT_EPOCH; #[allow(deprecated)] use solana_program::sysvar::recent_blockhashes::{ IntoIterSorted, IterItem, RecentBlockhashes, MAX_ENTRIES, }; -use std::{collections::BinaryHeap, iter::FromIterator}; +use { + crate::{ + account::{ + create_account_shared_data_with_fields, to_account, AccountSharedData, + InheritableAccountFields, DUMMY_INHERITABLE_ACCOUNT_FIELDS, + }, + clock::INITIAL_RENT_EPOCH, + }, + std::{collections::BinaryHeap, iter::FromIterator}, +}; #[deprecated( since = "1.9.0", @@ -79,12 +83,14 @@ where #[cfg(test)] mod tests { #![allow(deprecated)] - use super::*; - use crate::account::from_account; - use rand::{seq::SliceRandom, thread_rng}; - use solana_program::{ - hash::{Hash, HASH_BYTES}, - sysvar::recent_blockhashes::Entry, + use { + super::*, + crate::account::from_account, + rand::{seq::SliceRandom, thread_rng}, + solana_program::{ + hash::{Hash, HASH_BYTES}, + sysvar::recent_blockhashes::Entry, + }, }; #[test] diff --git a/sdk/src/secp256k1_instruction.rs b/sdk/src/secp256k1_instruction.rs index 1cf471db9b681a..f284e1f2dab5ab 100644 --- a/sdk/src/secp256k1_instruction.rs +++ b/sdk/src/secp256k1_instruction.rs @@ -1,13 +1,17 @@ #![cfg(feature = "full")] -use crate::{ - feature_set::{libsecp256k1_0_5_upgrade_enabled, libsecp256k1_fail_on_bad_count, FeatureSet}, - instruction::Instruction, - precompiles::PrecompileError, +use { + crate::{ + feature_set::{ + libsecp256k1_0_5_upgrade_enabled, libsecp256k1_fail_on_bad_count, FeatureSet, + }, + instruction::Instruction, + precompiles::PrecompileError, + }, + digest::Digest, + serde_derive::{Deserialize, Serialize}, + std::sync::Arc, }; -use digest::Digest; -use serde_derive::{Deserialize, Serialize}; -use std::sync::Arc; pub const HASHED_PUBKEY_SERIALIZED_SIZE: usize = 20; pub const SIGNATURE_SERIALIZED_SIZE: usize = 64; @@ -211,18 +215,20 @@ fn get_data_slice<'a>( #[cfg(test)] pub mod test { - use super::*; - use crate::{ - feature_set, - hash::Hash, - secp256k1_instruction::{ - new_secp256k1_instruction, SecpSignatureOffsets, SIGNATURE_OFFSETS_SERIALIZED_SIZE, + use { + super::*, + crate::{ + feature_set, + hash::Hash, + secp256k1_instruction::{ + new_secp256k1_instruction, SecpSignatureOffsets, SIGNATURE_OFFSETS_SERIALIZED_SIZE, + }, + signature::{Keypair, Signer}, + transaction::Transaction, }, - signature::{Keypair, Signer}, - transaction::Transaction, + rand::{thread_rng, Rng}, + std::sync::Arc, }; - use rand::{thread_rng, Rng}; - use std::sync::Arc; fn test_case( num_signatures: u8, diff --git a/sdk/src/signature.rs b/sdk/src/signature.rs index 7ac68e4fc36269..ace0bf0981e92d 100644 --- a/sdk/src/signature.rs +++ b/sdk/src/signature.rs @@ -1,18 +1,19 @@ //! The `signature` module provides functionality for public, and private keys. #![cfg(feature = "full")] -use crate::pubkey::Pubkey; -use generic_array::{typenum::U64, GenericArray}; -use std::{ - borrow::{Borrow, Cow}, - convert::TryInto, - fmt, mem, - str::FromStr, -}; -use thiserror::Error; - // legacy module paths pub use crate::signer::{keypair::*, null_signer::*, presigner::*, *}; +use { + crate::pubkey::Pubkey, + generic_array::{typenum::U64, GenericArray}, + std::{ + borrow::{Borrow, Cow}, + convert::TryInto, + fmt, mem, + str::FromStr, + }, + thiserror::Error, +}; /// Number of bytes in a signature pub const SIGNATURE_BYTES: usize = 64; diff --git a/sdk/src/signer/mod.rs b/sdk/src/signer/mod.rs index 27a4d0706659f4..3a4c4cd0225804 100644 --- a/sdk/src/signer/mod.rs +++ b/sdk/src/signer/mod.rs @@ -100,8 +100,7 @@ pub fn unique_signers(signers: Vec<&dyn Signer>) -> Vec<&dyn Signer> { #[cfg(test)] mod tests { - use super::*; - use crate::signer::keypair::Keypair; + use {super::*, crate::signer::keypair::Keypair}; fn pubkeys(signers: &[&dyn Signer]) -> Vec { signers.iter().map(|x| x.pubkey()).collect() diff --git a/sdk/src/signer/presigner.rs b/sdk/src/signer/presigner.rs index a5f16fb6e18f5c..47eb3119eff253 100644 --- a/sdk/src/signer/presigner.rs +++ b/sdk/src/signer/presigner.rs @@ -63,8 +63,7 @@ where #[cfg(test)] mod tests { - use super::*; - use crate::signer::keypair::keypair_from_seed; + use {super::*, crate::signer::keypair::keypair_from_seed}; #[test] fn test_presigner() { diff --git a/sdk/src/timing.rs b/sdk/src/timing.rs index c56fe59393f718..376db2023829ff 100644 --- a/sdk/src/timing.rs +++ b/sdk/src/timing.rs @@ -1,7 +1,11 @@ //! The `timing` module provides std::time utility functions. -use crate::unchecked_div_by_const; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::time::{Duration, SystemTime, UNIX_EPOCH}; +use { + crate::unchecked_div_by_const, + std::{ + sync::atomic::{AtomicU64, Ordering}, + time::{Duration, SystemTime, UNIX_EPOCH}, + }, +}; pub fn duration_as_ns(d: &Duration) -> u64 { d.as_secs() diff --git a/sdk/src/transaction/mod.rs b/sdk/src/transaction/mod.rs index 6799a1af732ce6..5ed77660eed76e 100644 --- a/sdk/src/transaction/mod.rs +++ b/sdk/src/transaction/mod.rs @@ -19,16 +19,14 @@ use { serde::Serialize, solana_program::{system_instruction::SystemInstruction, system_program}, solana_sdk::feature_set, - std::result, - std::sync::Arc, + std::{result, sync::Arc}, thiserror::Error, }; mod sanitized; mod versioned; -pub use sanitized::*; -pub use versioned::*; +pub use {sanitized::*, versioned::*}; /// Reasons a transaction might be rejected. #[derive( @@ -547,15 +545,17 @@ pub fn get_nonce_pubkey_from_instruction<'a>( mod tests { #![allow(deprecated)] - use super::*; - use crate::{ - hash::hash, - instruction::AccountMeta, - signature::{Keypair, Presigner, Signer}, - system_instruction, sysvar, + use { + super::*, + crate::{ + hash::hash, + instruction::AccountMeta, + signature::{Keypair, Presigner, Signer}, + system_instruction, sysvar, + }, + bincode::{deserialize, serialize, serialized_size}, + std::mem::size_of, }; - use bincode::{deserialize, serialize, serialized_size}; - use std::mem::size_of; fn get_program_id(tx: &Transaction, instruction_index: usize) -> &Pubkey { let message = tx.message(); diff --git a/sdk/src/transport.rs b/sdk/src/transport.rs index db4cef4bb0a33f..fe8b178fafac6a 100644 --- a/sdk/src/transport.rs +++ b/sdk/src/transport.rs @@ -1,8 +1,6 @@ #![cfg(feature = "full")] -use crate::transaction::TransactionError; -use std::io; -use thiserror::Error; +use {crate::transaction::TransactionError, std::io, thiserror::Error}; #[derive(Debug, Error)] pub enum TransportError { diff --git a/stake-accounts/src/arg_parser.rs b/stake-accounts/src/arg_parser.rs index fefd2ab113ee6f..a29b880cbe2d88 100644 --- a/stake-accounts/src/arg_parser.rs +++ b/stake-accounts/src/arg_parser.rs @@ -1,16 +1,17 @@ -use crate::args::{ - Args, AuthorizeArgs, Command, CountArgs, MoveArgs, NewArgs, QueryArgs, RebaseArgs, - SetLockupArgs, +use { + crate::args::{ + Args, AuthorizeArgs, Command, CountArgs, MoveArgs, NewArgs, QueryArgs, RebaseArgs, + SetLockupArgs, + }, + clap::{value_t, value_t_or_exit, App, Arg, ArgMatches, SubCommand}, + solana_clap_utils::{ + input_parsers::unix_timestamp_from_rfc3339_datetime, + input_validators::{is_amount, is_rfc3339_datetime, is_valid_pubkey, is_valid_signer}, + }, + solana_cli_config::CONFIG_FILE, + solana_sdk::native_token::sol_to_lamports, + std::{ffi::OsString, process::exit}, }; -use clap::{value_t, value_t_or_exit, App, Arg, ArgMatches, SubCommand}; -use solana_clap_utils::{ - input_parsers::unix_timestamp_from_rfc3339_datetime, - input_validators::{is_amount, is_rfc3339_datetime, is_valid_pubkey, is_valid_signer}, -}; -use solana_cli_config::CONFIG_FILE; -use solana_sdk::native_token::sol_to_lamports; -use std::ffi::OsString; -use std::process::exit; fn fee_payer_arg<'a, 'b>() -> Arg<'a, 'b> { solana_clap_utils::fee_payer::fee_payer_arg().required(true) diff --git a/stake-accounts/src/args.rs b/stake-accounts/src/args.rs index 56a0a3a6fe5bed..de25dca8709b3e 100644 --- a/stake-accounts/src/args.rs +++ b/stake-accounts/src/args.rs @@ -1,13 +1,14 @@ -use clap::ArgMatches; -use solana_clap_utils::keypair::{pubkey_from_path, signer_from_path}; -use solana_remote_wallet::remote_wallet::RemoteWalletManager; -use solana_sdk::{ - clock::{Epoch, UnixTimestamp}, - pubkey::Pubkey, - signature::Signer, +use { + clap::ArgMatches, + solana_clap_utils::keypair::{pubkey_from_path, signer_from_path}, + solana_remote_wallet::remote_wallet::RemoteWalletManager, + solana_sdk::{ + clock::{Epoch, UnixTimestamp}, + pubkey::Pubkey, + signature::Signer, + }, + std::{error::Error, sync::Arc}, }; -use std::error::Error; -use std::sync::Arc; pub(crate) struct NewArgs { pub fee_payer: K, diff --git a/stake-accounts/src/main.rs b/stake-accounts/src/main.rs index bbf68036542001..90421c2d1763e3 100644 --- a/stake-accounts/src/main.rs +++ b/stake-accounts/src/main.rs @@ -3,25 +3,27 @@ mod arg_parser; mod args; mod stake_accounts; -use crate::arg_parser::parse_args; -use crate::args::{ - resolve_command, AuthorizeArgs, Command, MoveArgs, NewArgs, RebaseArgs, SetLockupArgs, +use { + crate::{ + arg_parser::parse_args, + args::{ + resolve_command, AuthorizeArgs, Command, MoveArgs, NewArgs, RebaseArgs, SetLockupArgs, + }, + }, + solana_cli_config::Config, + solana_client::{client_error::ClientError, rpc_client::RpcClient}, + solana_sdk::{ + message::Message, + native_token::lamports_to_sol, + pubkey::Pubkey, + signature::{unique_signers, Signature, Signer}, + signers::Signers, + stake::{instruction::LockupArgs, state::Lockup}, + transaction::Transaction, + }, + solana_stake_program::stake_state, + std::{env, error::Error}, }; -use solana_cli_config::Config; -use solana_client::client_error::ClientError; -use solana_client::rpc_client::RpcClient; -use solana_sdk::{ - message::Message, - native_token::lamports_to_sol, - pubkey::Pubkey, - signature::{unique_signers, Signature, Signer}, - signers::Signers, - stake::{instruction::LockupArgs, state::Lockup}, - transaction::Transaction, -}; -use solana_stake_program::stake_state; -use std::env; -use std::error::Error; fn get_balance_at(client: &RpcClient, pubkey: &Pubkey, i: usize) -> Result { let address = stake_accounts::derive_stake_account_address(pubkey, i); diff --git a/stake-accounts/src/stake_accounts.rs b/stake-accounts/src/stake_accounts.rs index d2571943d7b278..e443ab37d7f151 100644 --- a/stake-accounts/src/stake_accounts.rs +++ b/stake-accounts/src/stake_accounts.rs @@ -281,16 +281,18 @@ pub(crate) fn move_stake_accounts( #[cfg(test)] mod tests { - use super::*; - use solana_runtime::{bank::Bank, bank_client::BankClient}; - use solana_sdk::{ - account::{AccountSharedData, ReadableAccount}, - client::SyncClient, - genesis_config::create_genesis_config, - signature::{Keypair, Signer}, - stake::state::StakeState, + use { + super::*, + solana_runtime::{bank::Bank, bank_client::BankClient}, + solana_sdk::{ + account::{AccountSharedData, ReadableAccount}, + client::SyncClient, + genesis_config::create_genesis_config, + signature::{Keypair, Signer}, + stake::state::StakeState, + }, + solana_stake_program::stake_state, }; - use solana_stake_program::stake_state; fn create_bank(lamports: u64) -> (Bank, Keypair, u64) { let (genesis_config, mint_keypair) = create_genesis_config(lamports); diff --git a/storage-bigtable/src/access_token.rs b/storage-bigtable/src/access_token.rs index e73962b2b28fbc..9b8cef01530a3e 100644 --- a/storage-bigtable/src/access_token.rs +++ b/storage-bigtable/src/access_token.rs @@ -1,3 +1,4 @@ +pub use goauth::scopes::Scope; /// A module for managing a Google API access token use { goauth::{ @@ -15,8 +16,6 @@ use { }, }; -pub use goauth::scopes::Scope; - fn load_credentials() -> Result { // Use standard GOOGLE_APPLICATION_CREDENTIALS environment variable let credentials_file = std::env::var("GOOGLE_APPLICATION_CREDENTIALS") diff --git a/storage-bigtable/src/bigtable.rs b/storage-bigtable/src/bigtable.rs index 640c9f97a94fac..7e6ac5a5a3b6f9 100644 --- a/storage-bigtable/src/bigtable.rs +++ b/storage-bigtable/src/bigtable.rs @@ -782,15 +782,17 @@ where #[cfg(test)] mod tests { - use super::*; - use crate::StoredConfirmedBlock; - use prost::Message; - use solana_sdk::{hash::Hash, signature::Keypair, system_transaction}; - use solana_storage_proto::convert::generated; - use solana_transaction_status::{ - ConfirmedBlock, TransactionStatusMeta, TransactionWithStatusMeta, + use { + super::*, + crate::StoredConfirmedBlock, + prost::Message, + solana_sdk::{hash::Hash, signature::Keypair, system_transaction}, + solana_storage_proto::convert::generated, + solana_transaction_status::{ + ConfirmedBlock, TransactionStatusMeta, TransactionWithStatusMeta, + }, + std::convert::TryInto, }; - use std::convert::TryInto; #[test] fn test_deserialize_protobuf_or_bincode_cell_data() { diff --git a/storage-proto/src/convert.rs b/storage-proto/src/convert.rs index f05ab2c19c81f7..e8511867c6b3a8 100644 --- a/storage-proto/src/convert.rs +++ b/storage-proto/src/convert.rs @@ -3,13 +3,11 @@ use { solana_account_decoder::parse_token::{real_number_string_trimmed, UiTokenAmount}, solana_sdk::{ hash::Hash, - instruction::CompiledInstruction, - instruction::InstructionError, + instruction::{CompiledInstruction, InstructionError}, message::{Message, MessageHeader}, pubkey::Pubkey, signature::Signature, - transaction::Transaction, - transaction::TransactionError, + transaction::{Transaction, TransactionError}, }, solana_transaction_status::{ ConfirmedBlock, InnerInstructions, Reward, RewardType, TransactionByAddrInfo, diff --git a/streamer/src/packet.rs b/streamer/src/packet.rs index 3e7f7342246748..58688ef80ec98a 100644 --- a/streamer/src/packet.rs +++ b/streamer/src/packet.rs @@ -1,17 +1,20 @@ //! The `packet` module defines data structures and methods to pull data from the network. -use crate::{ - recvmmsg::{recv_mmsg, NUM_RCVMMSGS}, - socket::SocketAddrSpace, +use { + crate::{ + recvmmsg::{recv_mmsg, NUM_RCVMMSGS}, + socket::SocketAddrSpace, + }, + solana_metrics::inc_new_counter_debug, + std::{io::Result, net::UdpSocket, time::Instant}, }; -pub use solana_perf::packet::{ - limited_deserialize, to_packets_chunked, Packets, PacketsRecycler, NUM_PACKETS, - PACKETS_PER_BATCH, +pub use { + solana_perf::packet::{ + limited_deserialize, to_packets_chunked, Packets, PacketsRecycler, NUM_PACKETS, + PACKETS_PER_BATCH, + }, + solana_sdk::packet::{Meta, Packet, PACKET_DATA_SIZE}, }; -use solana_metrics::inc_new_counter_debug; -pub use solana_sdk::packet::{Meta, Packet, PACKET_DATA_SIZE}; -use std::{io::Result, net::UdpSocket, time::Instant}; - pub fn recv_from(obj: &mut Packets, socket: &UdpSocket, max_wait_ms: u64) -> Result { let mut i = 0; //DOCUMENTED SIDE-EFFECT @@ -73,10 +76,14 @@ pub fn send_to( #[cfg(test)] mod tests { - use super::*; - use std::io; - use std::io::Write; - use std::net::{SocketAddr, UdpSocket}; + use { + super::*, + std::{ + io, + io::Write, + net::{SocketAddr, UdpSocket}, + }, + }; #[test] fn test_packets_set_addr() { diff --git a/streamer/src/recvmmsg.rs b/streamer/src/recvmmsg.rs index 0f9d8ee79ad9fc..897ba07990002f 100644 --- a/streamer/src/recvmmsg.rs +++ b/streamer/src/recvmmsg.rs @@ -119,10 +119,13 @@ pub fn recv_mmsg(sock: &UdpSocket, packets: &mut [Packet]) -> io::Result<(usize, #[cfg(test)] mod tests { - use crate::packet::PACKET_DATA_SIZE; - use crate::recvmmsg::*; - use std::net::{SocketAddr, UdpSocket}; - use std::time::{Duration, Instant}; + use { + crate::{packet::PACKET_DATA_SIZE, recvmmsg::*}, + std::{ + net::{SocketAddr, UdpSocket}, + time::{Duration, Instant}, + }, + }; type TestConfig = (UdpSocket, SocketAddr, UdpSocket, SocketAddr); diff --git a/streamer/src/sendmmsg.rs b/streamer/src/sendmmsg.rs index e3ce61713e6960..6e434f5ed5e27e 100644 --- a/streamer/src/sendmmsg.rs +++ b/streamer/src/sendmmsg.rs @@ -149,13 +149,17 @@ where #[cfg(test)] mod tests { - use crate::packet::Packet; - use crate::recvmmsg::recv_mmsg; - use crate::sendmmsg::{batch_send, multi_target_send, SendPktsError}; - use solana_sdk::packet::PACKET_DATA_SIZE; - use std::{ - io::ErrorKind, - net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, UdpSocket}, + use { + crate::{ + packet::Packet, + recvmmsg::recv_mmsg, + sendmmsg::{batch_send, multi_target_send, SendPktsError}, + }, + solana_sdk::packet::PACKET_DATA_SIZE, + std::{ + io::ErrorKind, + net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, UdpSocket}, + }, }; #[test] diff --git a/streamer/src/streamer.rs b/streamer/src/streamer.rs index e0169c3f2d9fac..d71a458c1cf7e8 100644 --- a/streamer/src/streamer.rs +++ b/streamer/src/streamer.rs @@ -1,19 +1,25 @@ //! The `streamer` module defines a set of services for efficiently pulling data from UDP sockets. //! -use crate::{ - packet::{self, send_to, Packets, PacketsRecycler, PACKETS_PER_BATCH}, - recvmmsg::NUM_RCVMMSGS, - socket::SocketAddrSpace, +use { + crate::{ + packet::{self, send_to, Packets, PacketsRecycler, PACKETS_PER_BATCH}, + recvmmsg::NUM_RCVMMSGS, + socket::SocketAddrSpace, + }, + solana_sdk::timing::timestamp, + std::{ + net::UdpSocket, + sync::{ + atomic::{AtomicBool, Ordering}, + mpsc::{Receiver, RecvTimeoutError, SendError, Sender}, + Arc, + }, + thread::{Builder, JoinHandle}, + time::{Duration, Instant}, + }, + thiserror::Error, }; -use solana_sdk::timing::timestamp; -use std::net::UdpSocket; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::mpsc::{Receiver, RecvTimeoutError, SendError, Sender}; -use std::sync::Arc; -use std::thread::{Builder, JoinHandle}; -use std::time::{Duration, Instant}; -use thiserror::Error; pub type PacketReceiver = Receiver; pub type PacketSender = Sender; @@ -178,17 +184,25 @@ pub fn responder( #[cfg(test)] mod test { - use super::*; - use crate::packet::{Packet, Packets, PACKET_DATA_SIZE}; - use crate::streamer::{receiver, responder}; - use solana_perf::recycler::Recycler; - use std::io; - use std::io::Write; - use std::net::UdpSocket; - use std::sync::atomic::{AtomicBool, Ordering}; - use std::sync::mpsc::channel; - use std::sync::Arc; - use std::time::Duration; + use { + super::*, + crate::{ + packet::{Packet, Packets, PACKET_DATA_SIZE}, + streamer::{receiver, responder}, + }, + solana_perf::recycler::Recycler, + std::{ + io, + io::Write, + net::UdpSocket, + sync::{ + atomic::{AtomicBool, Ordering}, + mpsc::channel, + Arc, + }, + time::Duration, + }, + }; fn get_msgs(r: PacketReceiver, num: &mut usize) { for _ in 0..10 { diff --git a/streamer/tests/recvmmsg.rs b/streamer/tests/recvmmsg.rs index e91a0dc6a21d8f..614dc16ee1b25c 100644 --- a/streamer/tests/recvmmsg.rs +++ b/streamer/tests/recvmmsg.rs @@ -1,10 +1,12 @@ #![cfg(target_os = "linux")] -use solana_streamer::packet::Packet; -use solana_streamer::packet::PACKET_DATA_SIZE; -use solana_streamer::recvmmsg::*; -use std::net::UdpSocket; -use std::time::Instant; +use { + solana_streamer::{ + packet::{Packet, PACKET_DATA_SIZE}, + recvmmsg::*, + }, + std::{net::UdpSocket, time::Instant}, +}; #[test] pub fn test_recv_mmsg_batch_size() { diff --git a/sys-tuner/src/main.rs b/sys-tuner/src/main.rs index 36b85539a395a8..2b8578b9713fd5 100644 --- a/sys-tuner/src/main.rs +++ b/sys-tuner/src/main.rs @@ -36,8 +36,7 @@ fn tune_poh_service_priority(uid: u32) { None } - use std::process::Command; - use std::str::from_utf8; + use std::{process::Command, str::from_utf8}; if let Some(pid) = find_pid("solana-validato", "/proc", uid, |dir| { let mut path = dir.path(); @@ -68,8 +67,7 @@ fn tune_poh_service_priority(uid: u32) { #[cfg(target_os = "linux")] fn tune_kernel_udp_buffers_and_vmmap() { - use sysctl::CtlValue::String; - use sysctl::Sysctl; + use sysctl::{CtlValue::String, Sysctl}; fn sysctl_write(name: &str, value: &str) { if let Ok(ctl) = sysctl::Ctl::new(name) { info!("Old {} value {:?}", name, ctl.value()); diff --git a/tokens/src/arg_parser.rs b/tokens/src/arg_parser.rs index 6b8bf2bcff3b0c..010acccf3b790d 100644 --- a/tokens/src/arg_parser.rs +++ b/tokens/src/arg_parser.rs @@ -1,19 +1,21 @@ -use crate::args::{ - Args, BalancesArgs, Command, DistributeTokensArgs, SenderStakeArgs, SplTokenArgs, StakeArgs, - TransactionLogArgs, +use { + crate::args::{ + Args, BalancesArgs, Command, DistributeTokensArgs, SenderStakeArgs, SplTokenArgs, + StakeArgs, TransactionLogArgs, + }, + clap::{ + crate_description, crate_name, value_t, value_t_or_exit, App, Arg, ArgMatches, SubCommand, + }, + solana_clap_utils::{ + input_parsers::{pubkey_of_signer, value_of}, + input_validators::{is_amount, is_valid_pubkey, is_valid_signer}, + keypair::{pubkey_from_path, signer_from_path}, + }, + solana_cli_config::CONFIG_FILE, + solana_remote_wallet::remote_wallet::maybe_wallet_manager, + solana_sdk::native_token::sol_to_lamports, + std::{error::Error, ffi::OsString, process::exit}, }; -use clap::{ - crate_description, crate_name, value_t, value_t_or_exit, App, Arg, ArgMatches, SubCommand, -}; -use solana_clap_utils::{ - input_parsers::{pubkey_of_signer, value_of}, - input_validators::{is_amount, is_valid_pubkey, is_valid_signer}, - keypair::{pubkey_from_path, signer_from_path}, -}; -use solana_cli_config::CONFIG_FILE; -use solana_remote_wallet::remote_wallet::maybe_wallet_manager; -use solana_sdk::native_token::sol_to_lamports; -use std::{error::Error, ffi::OsString, process::exit}; fn get_matches<'a, I, T>(args: I) -> ArgMatches<'a> where diff --git a/tokens/src/commands.rs b/tokens/src/commands.rs index fb137bebc12cbf..d282f6477652b8 100644 --- a/tokens/src/commands.rs +++ b/tokens/src/commands.rs @@ -1,51 +1,55 @@ -use crate::{ - args::{BalancesArgs, DistributeTokensArgs, SenderStakeArgs, StakeArgs, TransactionLogArgs}, - db::{self, TransactionInfo}, - spl_token::*, - token_display::Token, -}; -use chrono::prelude::*; -use console::style; -use csv::{ReaderBuilder, Trim}; -use indexmap::IndexMap; -use indicatif::{ProgressBar, ProgressStyle}; -use pickledb::PickleDb; -use serde::{Deserialize, Serialize}; -use solana_account_decoder::parse_token::{ - pubkey_from_spl_token, real_number_string, spl_token_pubkey, -}; -use solana_client::{ - client_error::{ClientError, Result as ClientResult}, - rpc_client::RpcClient, - rpc_config::RpcSendTransactionConfig, - rpc_request::MAX_GET_SIGNATURE_STATUSES_QUERY_ITEMS, -}; -use solana_sdk::{ - clock::Slot, - commitment_config::CommitmentConfig, - instruction::Instruction, - message::Message, - native_token::{lamports_to_sol, sol_to_lamports}, - signature::{unique_signers, Signature, Signer}, - stake::{ - instruction::{self as stake_instruction, LockupArgs}, - state::{Authorized, Lockup, StakeAuthorize}, +use { + crate::{ + args::{ + BalancesArgs, DistributeTokensArgs, SenderStakeArgs, StakeArgs, TransactionLogArgs, + }, + db::{self, TransactionInfo}, + spl_token::*, + token_display::Token, }, - system_instruction, - transaction::Transaction, -}; -use solana_transaction_status::TransactionStatus; -use spl_associated_token_account::get_associated_token_address; -use spl_token::solana_program::program_error::ProgramError; -use std::{ - cmp::{self}, - io, - sync::{ - atomic::{AtomicBool, Ordering}, - Arc, + chrono::prelude::*, + console::style, + csv::{ReaderBuilder, Trim}, + indexmap::IndexMap, + indicatif::{ProgressBar, ProgressStyle}, + pickledb::PickleDb, + serde::{Deserialize, Serialize}, + solana_account_decoder::parse_token::{ + pubkey_from_spl_token, real_number_string, spl_token_pubkey, + }, + solana_client::{ + client_error::{ClientError, Result as ClientResult}, + rpc_client::RpcClient, + rpc_config::RpcSendTransactionConfig, + rpc_request::MAX_GET_SIGNATURE_STATUSES_QUERY_ITEMS, + }, + solana_sdk::{ + clock::Slot, + commitment_config::CommitmentConfig, + instruction::Instruction, + message::Message, + native_token::{lamports_to_sol, sol_to_lamports}, + signature::{unique_signers, Signature, Signer}, + stake::{ + instruction::{self as stake_instruction, LockupArgs}, + state::{Authorized, Lockup, StakeAuthorize}, + }, + system_instruction, + transaction::Transaction, + }, + solana_transaction_status::TransactionStatus, + spl_associated_token_account::get_associated_token_address, + spl_token::solana_program::program_error::ProgramError, + std::{ + cmp::{self}, + io, + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, + }, + thread::sleep, + time::Duration, }, - thread::sleep, - time::Duration, }; #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] @@ -860,9 +864,11 @@ pub fn process_transaction_log(args: &TransactionLogArgs) -> Result<(), Error> { Ok(()) } -use crate::db::check_output_file; -use solana_sdk::{pubkey::Pubkey, signature::Keypair}; -use tempfile::{tempdir, NamedTempFile}; +use { + crate::db::check_output_file, + solana_sdk::{pubkey::Pubkey, signature::Keypair}, + tempfile::{tempdir, NamedTempFile}, +}; pub fn test_process_distribute_tokens_with_client( client: &RpcClient, sender_keypair: Keypair, @@ -1202,15 +1208,17 @@ pub fn test_process_distribute_stake_with_client(client: &RpcClient, sender_keyp #[cfg(test)] mod tests { - use super::*; - use solana_sdk::{ - instruction::AccountMeta, - signature::{read_keypair_file, write_keypair_file, Signer}, - stake::instruction::StakeInstruction, + use { + super::*, + solana_sdk::{ + instruction::AccountMeta, + signature::{read_keypair_file, write_keypair_file, Signer}, + stake::instruction::StakeInstruction, + }, + solana_streamer::socket::SocketAddrSpace, + solana_test_validator::TestValidator, + solana_transaction_status::TransactionConfirmationStatus, }; - use solana_streamer::socket::SocketAddrSpace; - use solana_test_validator::TestValidator; - use solana_transaction_status::TransactionConfirmationStatus; fn one_signer_message(client: &RpcClient) -> Message { Message::new_with_blockhash( diff --git a/tokens/src/db.rs b/tokens/src/db.rs index 9d3bb6ed8270ca..f4f0edddca99b5 100644 --- a/tokens/src/db.rs +++ b/tokens/src/db.rs @@ -1,9 +1,11 @@ -use chrono::prelude::*; -use pickledb::{error::Error, PickleDb, PickleDbDumpPolicy}; -use serde::{Deserialize, Serialize}; -use solana_sdk::{clock::Slot, pubkey::Pubkey, signature::Signature, transaction::Transaction}; -use solana_transaction_status::TransactionStatus; -use std::{cmp::Ordering, fs, io, path::Path}; +use { + chrono::prelude::*, + pickledb::{error::Error, PickleDb, PickleDbDumpPolicy}, + serde::{Deserialize, Serialize}, + solana_sdk::{clock::Slot, pubkey::Pubkey, signature::Signature, transaction::Transaction}, + solana_transaction_status::TransactionStatus, + std::{cmp::Ordering, fs, io, path::Path}, +}; #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct TransactionInfo { @@ -204,11 +206,13 @@ pub(crate) fn check_output_file(path: &str, db: &PickleDb) { #[cfg(test)] mod tests { - use super::*; - use csv::{ReaderBuilder, Trim}; - use solana_sdk::transaction::TransactionError; - use solana_transaction_status::TransactionConfirmationStatus; - use tempfile::NamedTempFile; + use { + super::*, + csv::{ReaderBuilder, Trim}, + solana_sdk::transaction::TransactionError, + solana_transaction_status::TransactionConfirmationStatus, + tempfile::NamedTempFile, + }; #[test] fn test_sort_transaction_infos_finalized_first() { diff --git a/tokens/src/main.rs b/tokens/src/main.rs index 447b7a66037bad..bbd8c0e435a8b6 100644 --- a/tokens/src/main.rs +++ b/tokens/src/main.rs @@ -1,14 +1,16 @@ -use solana_cli_config::{Config, CONFIG_FILE}; -use solana_client::rpc_client::RpcClient; -use solana_tokens::{arg_parser::parse_args, args::Command, commands, spl_token}; -use std::{ - env, - error::Error, - path::Path, - process, - sync::{ - atomic::{AtomicBool, Ordering}, - Arc, +use { + solana_cli_config::{Config, CONFIG_FILE}, + solana_client::rpc_client::RpcClient, + solana_tokens::{arg_parser::parse_args, args::Command, commands, spl_token}, + std::{ + env, + error::Error, + path::Path, + process, + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, + }, }, }; diff --git a/tokens/src/spl_token.rs b/tokens/src/spl_token.rs index bc28c2dac1764f..93bff668fe74c7 100644 --- a/tokens/src/spl_token.rs +++ b/tokens/src/spl_token.rs @@ -1,18 +1,20 @@ -use crate::{ - args::{DistributeTokensArgs, SplTokenArgs}, - commands::{Allocation, Error, FundingSource}, -}; -use console::style; -use solana_account_decoder::parse_token::{ - pubkey_from_spl_token, real_number_string, real_number_string_trimmed, spl_token_pubkey, -}; -use solana_client::rpc_client::RpcClient; -use solana_sdk::{instruction::Instruction, message::Message, native_token::lamports_to_sol}; -use solana_transaction_status::parse_token::spl_token_instruction; -use spl_associated_token_account::{create_associated_token_account, get_associated_token_address}; -use spl_token::{ - solana_program::program_pack::Pack, - state::{Account as SplTokenAccount, Mint}, +use { + crate::{ + args::{DistributeTokensArgs, SplTokenArgs}, + commands::{Allocation, Error, FundingSource}, + }, + console::style, + solana_account_decoder::parse_token::{ + pubkey_from_spl_token, real_number_string, real_number_string_trimmed, spl_token_pubkey, + }, + solana_client::rpc_client::RpcClient, + solana_sdk::{instruction::Instruction, message::Message, native_token::lamports_to_sol}, + solana_transaction_status::parse_token::spl_token_instruction, + spl_associated_token_account::{create_associated_token_account, get_associated_token_address}, + spl_token::{ + solana_program::program_pack::Pack, + state::{Account as SplTokenAccount, Mint}, + }, }; pub fn update_token_args(client: &RpcClient, args: &mut Option) -> Result<(), Error> { diff --git a/tokens/src/token_display.rs b/tokens/src/token_display.rs index 1a42787c11822d..fae099f5f35e91 100644 --- a/tokens/src/token_display.rs +++ b/tokens/src/token_display.rs @@ -1,8 +1,10 @@ -use solana_account_decoder::parse_token::real_number_string_trimmed; -use solana_sdk::native_token::lamports_to_sol; -use std::{ - fmt::{Debug, Display, Formatter, Result}, - ops::Add, +use { + solana_account_decoder::parse_token::real_number_string_trimmed, + solana_sdk::native_token::lamports_to_sol, + std::{ + fmt::{Debug, Display, Formatter, Result}, + ops::Add, + }, }; const SOL_SYMBOL: &str = "◎"; diff --git a/tokens/tests/commands.rs b/tokens/tests/commands.rs index 8026a0f5edc3c3..ea0288283e5844 100644 --- a/tokens/tests/commands.rs +++ b/tokens/tests/commands.rs @@ -1,8 +1,10 @@ -use solana_client::rpc_client::RpcClient; -use solana_sdk::signature::{Keypair, Signer}; -use solana_streamer::socket::SocketAddrSpace; -use solana_test_validator::TestValidator; -use solana_tokens::commands::test_process_distribute_tokens_with_client; +use { + solana_client::rpc_client::RpcClient, + solana_sdk::signature::{Keypair, Signer}, + solana_streamer::socket::SocketAddrSpace, + solana_test_validator::TestValidator, + solana_tokens::commands::test_process_distribute_tokens_with_client, +}; #[test] fn test_process_distribute_with_rpc_client() { diff --git a/transaction-dos/src/main.rs b/transaction-dos/src/main.rs index 4c4e6b859fc1de..78cb3c67116403 100644 --- a/transaction-dos/src/main.rs +++ b/transaction-dos/src/main.rs @@ -621,14 +621,16 @@ fn main() { #[cfg(test)] pub mod test { - use super::*; - use solana_core::validator::ValidatorConfig; - use solana_local_cluster::{ - local_cluster::{ClusterConfig, LocalCluster}, - validator_configs::make_identical_validator_configs, + use { + super::*, + solana_core::validator::ValidatorConfig, + solana_local_cluster::{ + local_cluster::{ClusterConfig, LocalCluster}, + validator_configs::make_identical_validator_configs, + }, + solana_measure::measure::Measure, + solana_sdk::poh_config::PohConfig, }; - use solana_measure::measure::Measure; - use solana_sdk::poh_config::PohConfig; #[test] fn test_tx_size() { diff --git a/upload-perf/src/upload-perf.rs b/upload-perf/src/upload-perf.rs index fd36f7a2fa7cd1..9d7a418d525f8f 100644 --- a/upload-perf/src/upload-perf.rs +++ b/upload-perf/src/upload-perf.rs @@ -1,9 +1,13 @@ -use serde_json::Value; -use std::collections::HashMap; -use std::env; -use std::fs::File; -use std::io::{BufRead, BufReader}; -use std::process::Command; +use { + serde_json::Value, + std::{ + collections::HashMap, + env, + fs::File, + io::{BufRead, BufReader}, + process::Command, + }, +}; fn get_last_metrics(metric: &str, db: &str, name: &str, branch: &str) -> Result { let query = format!( diff --git a/validator/src/lib.rs b/validator/src/lib.rs index 0958bcd60acc07..347437c2404b16 100644 --- a/validator/src/lib.rs +++ b/validator/src/lib.rs @@ -1,6 +1,4 @@ #![allow(clippy::integer_arithmetic)] -pub use solana_gossip::cluster_info::MINIMUM_VALIDATOR_PORT_RANGE_WIDTH; -pub use solana_test_validator; use { console::style, fd_lock::{RwLock, RwLockWriteGuard}, @@ -15,6 +13,7 @@ use { thread::JoinHandle, }, }; +pub use {solana_gossip::cluster_info::MINIMUM_VALIDATOR_PORT_RANGE_WIDTH, solana_test_validator}; pub mod admin_rpc_service; pub mod bootstrap; diff --git a/validator/src/main.rs b/validator/src/main.rs index 733bee6a0fd5c2..7d2a8a7ce142e3 100644 --- a/validator/src/main.rs +++ b/validator/src/main.rs @@ -1,4 +1,6 @@ #![allow(clippy::integer_arithmetic)] +#[cfg(not(target_env = "msvc"))] +use jemallocator::Jemalloc; use { clap::{ crate_description, crate_name, value_t, value_t_or_exit, values_t, values_t_or_exit, App, @@ -79,9 +81,6 @@ use { }, }; -#[cfg(not(target_env = "msvc"))] -use jemallocator::Jemalloc; - #[cfg(not(target_env = "msvc"))] #[global_allocator] static GLOBAL: Jemalloc = Jemalloc; @@ -423,9 +422,7 @@ fn platform_id() -> String { #[cfg(target_os = "linux")] fn check_os_network_limits() { - use solana_metrics::datapoint_warn; - use std::collections::HashMap; - use sysctl::Sysctl; + use {solana_metrics::datapoint_warn, std::collections::HashMap, sysctl::Sysctl}; fn sysctl_read(name: &str) -> Result { let ctl = sysctl::Ctl::new(name)?; diff --git a/version/src/lib.rs b/version/src/lib.rs index 85afcd95c47449..25d8fb256ebb47 100644 --- a/version/src/lib.rs +++ b/version/src/lib.rs @@ -1,9 +1,11 @@ #![cfg_attr(RUSTC_WITH_SPECIALIZATION, feature(min_specialization))] extern crate serde_derive; -use serde_derive::{Deserialize, Serialize}; -use solana_sdk::sanitize::Sanitize; -use std::{convert::TryInto, fmt}; +use { + serde_derive::{Deserialize, Serialize}, + solana_sdk::sanitize::Sanitize, + std::{convert::TryInto, fmt}, +}; #[macro_use] extern crate solana_frozen_abi_macro;