This commit is contained in:
Michael Vines 2021-04-18 10:27:36 -07:00
parent 3b79b21e9d
commit a911ae00ba
39 changed files with 113 additions and 144 deletions

View File

@ -104,11 +104,9 @@ impl DefaultSigner {
unique_signers.push(default_signer);
}
for signer in bulk_signers.into_iter() {
if let Some(signer) = signer {
if !unique_signers.iter().any(|s| s == &signer) {
unique_signers.push(signer);
}
for signer in bulk_signers.into_iter().flatten() {
if !unique_signers.iter().any(|s| s == &signer) {
unique_signers.push(signer);
}
}
Ok(CliSignerInfo {

View File

@ -1782,7 +1782,7 @@ fn read_and_verify_elf(program_location: &str) -> Result<Vec<u8>, Box<dyn std::e
.map_err(|err| format!("Unable to read program file: {}", err))?;
// Verify the program
Executable::<BpfError, ThisInstructionMeter>::from_elf(
<dyn Executable<BpfError, ThisInstructionMeter>>::from_elf(
&program_data,
Some(|x| bpf_verifier::check(x)),
Config::default(),

View File

@ -480,9 +480,9 @@ pub fn parse_stake_create_account(
staker,
withdrawer,
lockup: Lockup {
custodian,
epoch,
unix_timestamp,
epoch,
custodian,
},
amount,
sign_only,

View File

@ -169,8 +169,8 @@ impl ThinClient {
let rpc_clients: Vec<_> = rpc_addrs.into_iter().map(RpcClient::new_socket).collect();
let optimizer = ClientOptimizer::new(rpc_clients.len());
Self {
tpu_addrs,
transactions_socket,
tpu_addrs,
rpc_clients,
optimizer,
}

View File

@ -2633,7 +2633,7 @@ mod tests {
// should still be unprocessed
assert_eq!(
buffered_packets.len(),
packets_vec[interrupted_iteration + 1..].iter().count()
packets_vec[interrupted_iteration + 1..].len()
);
for ((remaining_unprocessed_packet, _, _forwarded), original_packet) in
buffered_packets

View File

@ -261,7 +261,6 @@ impl StandardBroadcastRun {
num_expected_batches,
slot_start_ts: self
.slot_broadcast_start
.clone()
.expect("Start timestamp must exist for a slot if we're broadcasting the slot"),
});
get_leader_schedule_time.stop();

View File

@ -1430,26 +1430,19 @@ mod tests {
let slot_vote_tracker = vote_tracker.get_slot_vote_tracker(vote_slot).unwrap();
let r_slot_vote_tracker = &slot_vote_tracker.read().unwrap();
assert_eq!(
r_slot_vote_tracker
.optimistic_votes_tracker(&vote_bank_hash)
.unwrap()
.stake(),
100
);
if events == vec![1] {
// Check `gossip_only_stake` is not incremented
assert_eq!(
r_slot_vote_tracker
.optimistic_votes_tracker(&vote_bank_hash)
.unwrap()
.stake(),
100
);
assert_eq!(r_slot_vote_tracker.gossip_only_stake, 0);
} else {
// Check that both the `gossip_only_stake` and `total_voted_stake` both
// increased
assert_eq!(
r_slot_vote_tracker
.optimistic_votes_tracker(&vote_bank_hash)
.unwrap()
.stake(),
100
);
assert_eq!(r_slot_vote_tracker.gossip_only_stake, 100);
}
}

View File

@ -315,15 +315,13 @@ mod tests {
);
for a in ancestors {
let mut expected = BlockCommitment::default();
if a <= root {
let mut expected = BlockCommitment::default();
expected.increase_rooted_stake(lamports);
assert_eq!(*commitment.get(&a).unwrap(), expected);
} else {
let mut expected = BlockCommitment::default();
expected.increase_confirmation_stake(1, lamports);
assert_eq!(*commitment.get(&a).unwrap(), expected);
}
assert_eq!(*commitment.get(&a).unwrap(), expected);
}
assert_eq!(rooted_stake[0], (root, lamports));
}

View File

@ -1210,7 +1210,7 @@ impl SavedTower {
pub fn new<T: Signer>(tower: &Tower, keypair: &Arc<T>) -> Result<Self> {
let data = bincode::serialize(tower)?;
let signature = keypair.sign_message(&data);
Ok(Self { data, signature })
Ok(Self { signature, data })
}
pub fn verify(&self, pubkey: &Pubkey) -> bool {

View File

@ -191,11 +191,11 @@ impl ForkProgress {
num_blocks_on_fork,
num_dropped_blocks_on_fork,
propagated_stats: PropagatedStats {
prev_leader_slot,
is_leader_slot,
propagated_validators_stake,
propagated_validators,
propagated_validators_stake,
is_propagated,
is_leader_slot,
prev_leader_slot,
total_epoch_stake,
..PropagatedStats::default()
},

View File

@ -175,7 +175,7 @@ fn update_retransmit_stats(
),
);
let mut packets_by_slot = stats.packets_by_slot.lock().unwrap();
let old_packets_by_slot = std::mem::replace(&mut *packets_by_slot, BTreeMap::new());
let old_packets_by_slot = std::mem::take(&mut *packets_by_slot);
drop(packets_by_slot);
for (slot, num_shreds) in old_packets_by_slot {

View File

@ -981,7 +981,7 @@ impl JsonRpcRequestProcessor {
return Ok(self
.runtime
.block_on(bigtable_ledger_storage.get_confirmed_blocks(start_slot, limit))
.unwrap_or_else(|_| vec![]));
.unwrap_or_default());
}
}
@ -1247,7 +1247,7 @@ impl JsonRpcRequestProcessor {
);
self.blockstore
.get_confirmed_signatures_for_address(pubkey, start_slot, end_slot)
.unwrap_or_else(|_| vec![])
.unwrap_or_default()
} else {
vec![]
}

View File

@ -482,8 +482,8 @@ impl RpcSubscriptions {
let exit_clone = exit.clone();
let subscriptions = Subscriptions {
account_subscriptions,
logs_subscriptions,
program_subscriptions,
logs_subscriptions,
signature_subscriptions,
gossip_account_subscriptions,
gossip_logs_subscriptions,

View File

@ -504,8 +504,8 @@ impl TestValidator {
preserve_ledger,
rpc_pubsub_url,
rpc_url,
gossip,
tpu,
gossip,
validator,
vote_account_address,
})

View File

@ -506,10 +506,10 @@ fn main() -> Result<(), Box<dyn error::Error>> {
let mut genesis_config = GenesisConfig {
native_instruction_processors,
ticks_per_slot,
epoch_schedule,
poh_config,
fee_rate_governor,
rent,
poh_config,
epoch_schedule,
cluster_type,
..GenesisConfig::default()
};

View File

@ -190,7 +190,7 @@ fn process_spy_results(
}
}
if let Some(node) = pubkey {
if validators.iter().find(|x| x.id == node).is_none() {
if !validators.iter().any(|x| x.id == node) {
eprintln!("Error: Could not find node {:?}", node);
exit(1);
}

View File

@ -1054,7 +1054,9 @@ pub fn init_or_update(config_file: &str, is_init: bool, check_only: bool) -> Res
print_update_manifest(&update_manifest);
if timestamp_secs()
< u64::from_str_radix(crate::build_env::BUILD_SECONDS_SINCE_UNIX_EPOCH, 10).unwrap()
< crate::build_env::BUILD_SECONDS_SINCE_UNIX_EPOCH
.parse::<u64>()
.unwrap()
{
return Err("Unable to update as system time seems unreliable".to_string());
}

View File

@ -1656,35 +1656,31 @@ fn main() {
let log_file = PathBuf::from(value_t_or_exit!(arg_matches, "log_path", String));
let f = BufReader::new(File::open(log_file).unwrap());
println!("Reading log file");
for line in f.lines() {
if let Ok(line) = line {
let parse_results = {
if let Some(slot_string) = frozen_regex.captures_iter(&line).next() {
Some((slot_string, &mut frozen))
} else {
full_regex
.captures_iter(&line)
.next()
.map(|slot_string| (slot_string, &mut full))
}
};
for line in f.lines().flatten() {
let parse_results = {
if let Some(slot_string) = frozen_regex.captures_iter(&line).next() {
Some((slot_string, &mut frozen))
} else {
full_regex
.captures_iter(&line)
.next()
.map(|slot_string| (slot_string, &mut full))
}
};
if let Some((slot_string, map)) = parse_results {
let slot = slot_string
.get(1)
.expect("Only one match group")
.as_str()
.parse::<u64>()
.unwrap();
if ancestors.contains(&slot) && !map.contains_key(&slot) {
map.insert(slot, line);
}
if slot == ending_slot
&& frozen.contains_key(&slot)
&& full.contains_key(&slot)
{
break;
}
if let Some((slot_string, map)) = parse_results {
let slot = slot_string
.get(1)
.expect("Only one match group")
.as_str()
.parse::<u64>()
.unwrap();
if ancestors.contains(&slot) && !map.contains_key(&slot) {
map.insert(slot, line);
}
if slot == ending_slot && frozen.contains_key(&slot) && full.contains_key(&slot)
{
break;
}
}
}

View File

@ -4708,14 +4708,10 @@ pub mod tests {
if slot % 3 == 0 {
let shred0 = shreds_for_slot.remove(0);
missing_shreds.push(shred0);
blockstore
.insert_shreds(shreds_for_slot, None, false)
.unwrap();
} else {
blockstore
.insert_shreds(shreds_for_slot, None, false)
.unwrap();
}
blockstore
.insert_shreds(shreds_for_slot, None, false)
.unwrap();
}
// Check metadata

View File

@ -449,6 +449,7 @@ impl<T: SlotColumn> Column for T {
index
}
#[allow(clippy::wrong_self_convention)]
fn as_index(slot: Slot) -> u64 {
slot
}
@ -480,6 +481,7 @@ impl Column for columns::TransactionStatus {
index.0
}
#[allow(clippy::wrong_self_convention)]
fn as_index(index: u64) -> Self::Index {
(index, Signature::default(), 0)
}
@ -516,6 +518,7 @@ impl Column for columns::AddressSignatures {
index.0
}
#[allow(clippy::wrong_self_convention)]
fn as_index(index: u64) -> Self::Index {
(index, Pubkey::default(), 0, Signature::default())
}
@ -542,6 +545,7 @@ impl Column for columns::TransactionStatusIndex {
index
}
#[allow(clippy::wrong_self_convention)]
fn as_index(slot: u64) -> u64 {
slot
}
@ -590,6 +594,7 @@ impl Column for columns::ShredCode {
index.0
}
#[allow(clippy::wrong_self_convention)]
fn as_index(slot: Slot) -> Self::Index {
(slot, 0)
}
@ -619,6 +624,7 @@ impl Column for columns::ShredData {
index.0
}
#[allow(clippy::wrong_self_convention)]
fn as_index(slot: Slot) -> Self::Index {
(slot, 0)
}
@ -697,6 +703,7 @@ impl Column for columns::ErasureMeta {
index.0
}
#[allow(clippy::wrong_self_convention)]
fn as_index(slot: Slot) -> Self::Index {
(slot, 0)
}

View File

@ -33,10 +33,8 @@ impl LeaderSchedule {
.map(|i| {
if i % repeat == 0 {
current_node = ids[weighted_index.sample(rng)];
current_node
} else {
current_node
}
current_node
})
.collect();
Self::new_from_schedule(slot_leaders)

View File

@ -117,25 +117,23 @@ fn find_cuda_home(perf_libs_path: &Path) -> Option<PathBuf> {
}
// Search /usr/local for a `cuda-` directory that matches a perf-libs subdirectory
for entry in fs::read_dir(&perf_libs_path).unwrap() {
if let Ok(entry) = entry {
let path = entry.path();
if !path.is_dir() {
continue;
}
let dir_name = path.file_name().unwrap().to_str().unwrap_or("");
if !dir_name.starts_with("cuda-") {
continue;
}
let cuda_home: PathBuf = ["/", "usr", "local", dir_name].iter().collect();
if !cuda_home.is_dir() {
continue;
}
info!("CUDA installation found at {:?}", cuda_home);
return Some(cuda_home);
for entry in fs::read_dir(&perf_libs_path).unwrap().flatten() {
let path = entry.path();
if !path.is_dir() {
continue;
}
let dir_name = path.file_name().unwrap().to_str().unwrap_or("");
if !dir_name.starts_with("cuda-") {
continue;
}
let cuda_home: PathBuf = ["/", "usr", "local", dir_name].iter().collect();
if !cuda_home.is_dir() {
continue;
}
info!("CUDA installation found at {:?}", cuda_home);
return Some(cuda_home);
}
None
}

View File

@ -737,9 +737,9 @@ impl ProgramTest {
block_commitment_cache,
last_blockhash,
GenesisConfigInfo {
genesis_config,
mint_keypair,
voting_keypair,
genesis_config,
},
)
}

View File

@ -76,7 +76,7 @@ pub fn create_and_cache_executor(
use_jit: bool,
) -> Result<Arc<BpfExecutor>, InstructionError> {
let bpf_compute_budget = invoke_context.get_bpf_compute_budget();
let mut program = Executable::<BpfError, ThisInstructionMeter>::from_elf(
let mut program = <dyn Executable<BpfError, ThisInstructionMeter>>::from_elf(
data,
None,
Config {
@ -923,7 +923,7 @@ mod tests {
];
let input = &mut [0x00];
let program = Executable::<BpfError, TestInstructionMeter>::from_text_bytes(
let program = <dyn Executable<BpfError, TestInstructionMeter>>::from_text_bytes(
program,
None,
Config::default(),

View File

@ -567,9 +567,9 @@ mod tests {
offset += size_of::<u64>();
accounts.push(AccountInfo {
key,
is_signer,
is_writable,
key,
lamports,
data,
owner,

View File

@ -86,10 +86,7 @@ pub fn process_instruction(
}
// If Config account is already initialized, update signatures must match Config data
if !current_data.keys.is_empty()
&& current_signer_keys
.iter()
.find(|&pubkey| pubkey == signer)
.is_none()
&& !current_signer_keys.iter().any(|pubkey| pubkey == signer)
{
ic_msg!(
invoke_context,

View File

@ -2536,13 +2536,12 @@ mod tests {
},
);
let effective_rate_limited = (effective as f64 * stake.warmup_cooldown_rate) as u64;
if epoch < stake.deactivation_epoch {
let increase = (effective as f64 * stake.warmup_cooldown_rate) as u64;
effective += increase.min(activating);
effective += effective_rate_limited.min(activating);
other_activations.push(0);
} else {
let decrease = (effective as f64 * stake.warmup_cooldown_rate) as u64;
effective -= decrease.min(deactivating);
effective -= effective_rate_limited.min(deactivating);
effective += other_activation;
other_activations.push(other_activation);
}

View File

@ -365,21 +365,15 @@ impl RemoteWallet for LedgerWallet {
) -> Result<RemoteWalletInfo, RemoteWalletError> {
let manufacturer = dev_info
.manufacturer_string()
.clone()
.unwrap_or("Unknown")
.to_lowercase()
.replace(" ", "-");
let model = dev_info
.product_string()
.clone()
.unwrap_or("Unknown")
.to_lowercase()
.replace(" ", "-");
let serial = dev_info
.serial_number()
.clone()
.unwrap_or("Unknown")
.to_string();
let serial = dev_info.serial_number().unwrap_or("Unknown").to_string();
let host_device_path = dev_info.path().to_string_lossy().to_string();
let version = self.get_firmware_version()?;
self.version = version;

View File

@ -216,7 +216,7 @@ impl AccountsCache {
// we return all slots <= `max_root`
std::mem::replace(&mut w_maybe_unflushed_roots, greater_than_max_root)
} else {
std::mem::replace(&mut *w_maybe_unflushed_roots, BTreeSet::new())
std::mem::take(&mut *w_maybe_unflushed_roots)
}
}

View File

@ -2109,10 +2109,7 @@ impl AccountsDb {
}
pub fn shrink_candidate_slots(&self) -> usize {
let shrink_slots = std::mem::replace(
&mut *self.shrink_candidate_slots.lock().unwrap(),
HashMap::new(),
);
let shrink_slots = std::mem::take(&mut *self.shrink_candidate_slots.lock().unwrap());
let num_candidates = shrink_slots.len();
for (slot, slot_shrink_candidates) in shrink_slots {
let mut measure = Measure::start("shrink_candidate_slots-ms");
@ -6681,7 +6678,7 @@ pub mod tests {
let mint_key = Pubkey::new_unique();
let mut account_data_with_mint =
vec![0; inline_spl_token_v2_0::state::Account::get_packed_len()];
account_data_with_mint[..PUBKEY_BYTES].clone_from_slice(&(mint_key.clone().to_bytes()));
account_data_with_mint[..PUBKEY_BYTES].clone_from_slice(&(mint_key.to_bytes()));
let mut normal_account = AccountSharedData::new(1, 0, &AccountSharedData::default().owner);
normal_account.owner = inline_spl_token_v2_0::id();

View File

@ -2358,7 +2358,7 @@ pub mod tests {
let account_key = Pubkey::new_unique();
let mut account_data = vec![0; inline_spl_token_v2_0::state::Account::get_packed_len()];
account_data[key_start..key_end].clone_from_slice(&(index_key.clone().to_bytes()));
account_data[key_start..key_end].clone_from_slice(&(index_key.to_bytes()));
// Insert slots into secondary index
for slot in &slots {
@ -2583,7 +2583,7 @@ pub mod tests {
let index_key = Pubkey::new_unique();
let slot = 1;
let mut account_data = vec![0; inline_spl_token_v2_0::state::Account::get_packed_len()];
account_data[key_start..key_end].clone_from_slice(&(index_key.clone().to_bytes()));
account_data[key_start..key_end].clone_from_slice(&(index_key.to_bytes()));
// Wrong program id
index.upsert(
@ -2675,10 +2675,10 @@ pub mod tests {
let slot = 1;
let mut account_data1 = vec![0; inline_spl_token_v2_0::state::Account::get_packed_len()];
account_data1[index_key_start..index_key_end]
.clone_from_slice(&(secondary_key1.clone().to_bytes()));
.clone_from_slice(&(secondary_key1.to_bytes()));
let mut account_data2 = vec![0; inline_spl_token_v2_0::state::Account::get_packed_len()];
account_data2[index_key_start..index_key_end]
.clone_from_slice(&(secondary_key2.clone().to_bytes()));
.clone_from_slice(&(secondary_key2.to_bytes()));
// First write one mint index
index.upsert(

View File

@ -70,8 +70,8 @@ impl BlockCommitmentCache {
) -> Self {
Self {
block_commitment,
total_stake,
commitment_slots,
total_stake,
}
}

View File

@ -99,8 +99,8 @@ pub fn create_genesis_config_with_vote_accounts_and_cluster_type(
let mut genesis_config_info = GenesisConfigInfo {
genesis_config,
voting_keypair,
mint_keypair,
voting_keypair,
};
for (validator_voting_keypairs, stake) in voting_keypairs[1..].iter().zip(&stakes[1..]) {
@ -156,8 +156,8 @@ pub fn create_genesis_config_with_leader(
GenesisConfigInfo {
genesis_config,
voting_keypair,
mint_keypair,
voting_keypair,
}
}

View File

@ -198,9 +198,9 @@ pub unsafe fn deserialize<'a>(input: *mut u8) -> (&'a Pubkey, Vec<AccountInfo<'a
offset += size_of::<u64>();
accounts.push(AccountInfo {
key,
is_signer,
is_writable,
key,
lamports,
data,
owner,

View File

@ -106,9 +106,9 @@ pub unsafe fn deserialize<'a>(input: *mut u8) -> (&'a Pubkey, Vec<AccountInfo<'a
offset += size_of::<u64>();
accounts.push(AccountInfo {
key,
is_signer,
is_writable,
key,
lamports,
data,
owner,

View File

@ -244,8 +244,8 @@ impl Instruction {
let data = serialize(data).unwrap();
Self {
program_id,
data,
accounts,
data,
}
}
@ -257,16 +257,16 @@ impl Instruction {
let data = data.try_to_vec().unwrap();
Self {
program_id,
data,
accounts,
data,
}
}
pub fn new_with_bytes(program_id: Pubkey, data: &[u8], accounts: Vec<AccountMeta>) -> Self {
Self {
program_id,
data: data.to_vec(),
accounts,
data: data.to_vec(),
}
}
}

View File

@ -487,8 +487,8 @@ impl Message {
let data = read_slice(&mut current, &data, data_len as usize)?;
Ok(Instruction {
program_id,
data,
accounts,
data,
})
}

View File

@ -189,9 +189,9 @@ fn apply_lockup_changes(lockup: &LockupArgs, existing_lockup: &Lockup) -> Lockup
x => x,
};
LockupArgs {
custodian,
epoch,
unix_timestamp,
epoch,
custodian,
}
}

View File

@ -715,6 +715,7 @@ fn check_payer_balances(
(args.sender_keypair.pubkey(), None)
};
let fee_payer_balance = client.get_balance(&args.fee_payer.pubkey())?;
if let Some((unlocked_sol_source, total_unlocked_sol)) = unlocked_sol_source {
let staker_balance = client.get_balance(&distribution_source)?;
if staker_balance < undistributed_tokens {
@ -724,15 +725,13 @@ fn check_payer_balances(
));
}
if args.fee_payer.pubkey() == unlocked_sol_source {
let balance = client.get_balance(&args.fee_payer.pubkey())?;
if balance < fees + total_unlocked_sol {
if fee_payer_balance < fees + total_unlocked_sol {
return Err(Error::InsufficientFunds(
vec![FundingSource::SystemAccount, FundingSource::FeePayer].into(),
lamports_to_sol(fees + total_unlocked_sol).to_string(),
));
}
} else {
let fee_payer_balance = client.get_balance(&args.fee_payer.pubkey())?;
if fee_payer_balance < fees {
return Err(Error::InsufficientFunds(
vec![FundingSource::FeePayer].into(),
@ -748,15 +747,13 @@ fn check_payer_balances(
}
}
} else if args.fee_payer.pubkey() == distribution_source {
let balance = client.get_balance(&args.fee_payer.pubkey())?;
if balance < fees + undistributed_tokens {
if fee_payer_balance < fees + undistributed_tokens {
return Err(Error::InsufficientFunds(
vec![FundingSource::SystemAccount, FundingSource::FeePayer].into(),
lamports_to_sol(fees + undistributed_tokens).to_string(),
));
}
} else {
let fee_payer_balance = client.get_balance(&args.fee_payer.pubkey())?;
if fee_payer_balance < fees {
return Err(Error::InsufficientFunds(
vec![FundingSource::FeePayer].into(),