patches errors from clippy::uninlined_format_args

https://rust-lang.github.io/rust-clippy/master/index.html#uninlined_format_args
This commit is contained in:
behzad nouri 2022-12-06 09:30:06 -05:00
parent 9433c06745
commit 9524c9dbff
214 changed files with 1306 additions and 1862 deletions

View File

@ -119,7 +119,7 @@ pub fn parse_account_data(
ParsableAccount::Vote => serde_json::to_value(parse_vote(data)?)?,
};
Ok(ParsedAccount {
program: format!("{:?}", program_name).to_kebab_case(),
program: format!("{program_name:?}").to_kebab_case(),
parsed: parsed_json,
space: data.len() as u64,
})

View File

@ -60,13 +60,13 @@ fn main() {
let num_accounts = value_t!(matches, "num_accounts", usize).unwrap_or(10_000);
let iterations = value_t!(matches, "iterations", usize).unwrap_or(20);
let clean = matches.is_present("clean");
println!("clean: {:?}", clean);
println!("clean: {clean:?}");
let path = PathBuf::from(env::var("FARF_DIR").unwrap_or_else(|_| "farf".to_owned()))
.join("accounts-bench");
println!("cleaning file system: {:?}", path);
println!("cleaning file system: {path:?}");
if fs::remove_dir_all(path.clone()).is_err() {
println!("Warning: Couldn't remove {:?}", path);
println!("Warning: Couldn't remove {path:?}");
}
let accounts = Accounts::new_with_config_for_benches(
vec![path],
@ -75,7 +75,7 @@ fn main() {
false,
AccountShrinkThreshold::default(),
);
println!("Creating {} accounts", num_accounts);
println!("Creating {num_accounts} accounts");
let mut create_time = Measure::start("create accounts");
let pubkeys: Vec<_> = (0..num_slots)
.into_par_iter()
@ -112,7 +112,7 @@ fn main() {
let mut time = Measure::start("clean");
accounts.accounts_db.clean_accounts_for_tests();
time.stop();
println!("{}", time);
println!("{time}");
for slot in 0..num_slots {
update_accounts_bench(&accounts, &pubkeys, ((x + 1) * num_slots + slot) as u64);
accounts.add_root((x * num_slots + slot) as u64);

View File

@ -67,22 +67,20 @@ pub fn airdrop_lamports(
}
if tries >= 5 {
panic!(
"Error requesting airdrop: to addr: {:?} amount: {} {:?}",
faucet_addr, airdrop_amount, result
"Error requesting airdrop: to addr: {faucet_addr:?} amount: {airdrop_amount} {result:?}"
)
}
}
}
Err(err) => {
panic!(
"Error requesting airdrop: {:?} to addr: {:?} amount: {}",
err, faucet_addr, airdrop_amount
"Error requesting airdrop: {err:?} to addr: {faucet_addr:?} amount: {airdrop_amount}"
);
}
};
let current_balance = client.get_balance(&id.pubkey()).unwrap_or_else(|e| {
panic!("airdrop error {}", e);
panic!("airdrop error {e}");
});
info!("current balance {}...", current_balance);
@ -575,14 +573,14 @@ fn main() {
let mut entrypoint_addr = SocketAddr::from(([127, 0, 0, 1], port));
if let Some(addr) = matches.value_of("entrypoint") {
entrypoint_addr = solana_net_utils::parse_host_port(addr).unwrap_or_else(|e| {
eprintln!("failed to parse entrypoint address: {}", e);
eprintln!("failed to parse entrypoint address: {e}");
exit(1)
});
}
let mut faucet_addr = SocketAddr::from(([127, 0, 0, 1], FAUCET_PORT));
if let Some(addr) = matches.value_of("faucet_addr") {
faucet_addr = solana_net_utils::parse_host_port(addr).unwrap_or_else(|e| {
eprintln!("failed to parse entrypoint address: {}", e);
eprintln!("failed to parse entrypoint address: {e}");
exit(1)
});
}
@ -594,7 +592,7 @@ fn main() {
let iterations = value_t!(matches, "iterations", usize).unwrap_or(10);
let num_instructions = value_t!(matches, "num_instructions", usize).unwrap_or(1);
if num_instructions == 0 || num_instructions > 500 {
eprintln!("bad num_instructions: {}", num_instructions);
eprintln!("bad num_instructions: {num_instructions}");
exit(1);
}
@ -604,7 +602,7 @@ fn main() {
.iter()
.map(|keypair_string| {
read_keypair_file(keypair_string)
.unwrap_or_else(|_| panic!("bad keypair {:?}", keypair_string))
.unwrap_or_else(|_| panic!("bad keypair {keypair_string:?}"))
})
.collect();
let mut payer_keypair_refs: Vec<&Keypair> = vec![];
@ -626,7 +624,7 @@ fn main() {
SocketAddrSpace::Unspecified,
)
.unwrap_or_else(|err| {
eprintln!("Failed to discover {} node: {:?}", entrypoint_addr, err);
eprintln!("Failed to discover {entrypoint_addr} node: {err:?}");
exit(1);
});

View File

@ -384,7 +384,7 @@ fn main() {
.iter()
.for_each(|tx| {
let res = bank.process_transaction(tx);
assert!(res.is_ok(), "sanity test transactions error: {:?}", res);
assert!(res.is_ok(), "sanity test transactions error: {res:?}");
});
});
bank.clear_signatures();
@ -395,7 +395,7 @@ fn main() {
let res =
bank.process_transactions(packets_for_single_iteration.transactions.iter());
for r in res {
assert!(r.is_ok(), "sanity parallel execution error: {:?}", r);
assert!(r.is_ok(), "sanity parallel execution error: {r:?}");
}
bank.clear_signatures();
});

View File

@ -89,7 +89,7 @@ impl BenchTpsClient for BankClient {
.map_err(|err| err.into())
.and_then(|account| {
account.ok_or_else(|| {
BenchTpsError::Custom(format!("AccountNotFound: pubkey={}", pubkey))
BenchTpsError::Custom(format!("AccountNotFound: pubkey={pubkey}"))
})
})
}
@ -103,7 +103,7 @@ impl BenchTpsClient for BankClient {
.map_err(|err| err.into())
.and_then(|account| {
account.ok_or_else(|| {
BenchTpsError::Custom(format!("AccountNotFound: pubkey={}", pubkey))
BenchTpsError::Custom(format!("AccountNotFound: pubkey={pubkey}"))
})
})
}

View File

@ -95,7 +95,7 @@ impl BenchTpsClient for RpcClient {
.map_err(|err| err.into())
.and_then(|account| {
account.ok_or_else(|| {
BenchTpsError::Custom(format!("AccountNotFound: pubkey={}", pubkey))
BenchTpsError::Custom(format!("AccountNotFound: pubkey={pubkey}"))
})
})
}

View File

@ -100,7 +100,7 @@ impl BenchTpsClient for ThinClient {
.map_err(|err| err.into())
.and_then(|account| {
account.ok_or_else(|| {
BenchTpsError::Custom(format!("AccountNotFound: pubkey={}", pubkey))
BenchTpsError::Custom(format!("AccountNotFound: pubkey={pubkey}"))
})
})
}

View File

@ -112,7 +112,7 @@ impl BenchTpsClient for TpuClient {
.map_err(|err| err.into())
.and_then(|account| {
account.ok_or_else(|| {
BenchTpsError::Custom(format!("AccountNotFound: pubkey={}", pubkey))
BenchTpsError::Custom(format!("AccountNotFound: pubkey={pubkey}"))
})
})
}

View File

@ -400,7 +400,7 @@ pub fn extract_args(matches: &ArgMatches) -> Config {
if let Some(addr) = matches.value_of("entrypoint") {
args.entrypoint_addr = solana_net_utils::parse_host_port(addr).unwrap_or_else(|e| {
eprintln!("failed to parse entrypoint address: {}", e);
eprintln!("failed to parse entrypoint address: {e}");
exit(1)
});
}

View File

@ -58,14 +58,14 @@ where
last_balance,
)
.unwrap_or_else(|e| {
eprintln!("Error could not fund keys: {:?}", e);
eprintln!("Error could not fund keys: {e:?}");
exit(1);
});
keypairs
} else {
generate_and_fund_keypairs(client, id, keypair_count, num_lamports_per_account)
.unwrap_or_else(|e| {
eprintln!("Error could not fund keys: {:?}", e);
eprintln!("Error could not fund keys: {e:?}");
exit(1);
})
}

View File

@ -62,7 +62,7 @@ fn create_client(
let nodes =
discover_cluster(entrypoint_addr, num_nodes, SocketAddrSpace::Unspecified)
.unwrap_or_else(|err| {
eprintln!("Failed to discover {} nodes: {:?}", num_nodes, err);
eprintln!("Failed to discover {num_nodes} nodes: {err:?}");
exit(1);
});
if multi_client {
@ -70,8 +70,7 @@ fn create_client(
get_multi_client(&nodes, &SocketAddrSpace::Unspecified, connection_cache);
if nodes.len() < num_clients {
eprintln!(
"Error: Insufficient nodes discovered. Expecting {} or more",
num_nodes
"Error: Insufficient nodes discovered. Expecting {num_nodes} or more"
);
exit(1);
}
@ -90,7 +89,7 @@ fn create_client(
}
}
Arc::new(target_client.unwrap_or_else(|| {
eprintln!("Target node {} not found", target_node);
eprintln!("Target node {target_node} not found");
exit(1);
}))
} else {
@ -120,7 +119,7 @@ fn create_client(
Arc::new(connection_cache),
)
.unwrap_or_else(|err| {
eprintln!("Could not create TpuClient {:?}", err);
eprintln!("Could not create TpuClient {err:?}");
exit(1);
}),
)
@ -198,14 +197,14 @@ fn main() {
let rpc_tpu_sockets: Option<(SocketAddr, SocketAddr)> =
if let Ok(rpc_addr) = value_t!(matches, "rpc_addr", String) {
let rpc = rpc_addr.parse().unwrap_or_else(|e| {
eprintln!("RPC address should parse as socketaddr {:?}", e);
eprintln!("RPC address should parse as socketaddr {e:?}");
exit(1);
});
let tpu = value_t!(matches, "tpu_addr", String)
.unwrap()
.parse()
.unwrap_or_else(|e| {
eprintln!("TPU address should parse to a socket: {:?}", e);
eprintln!("TPU address should parse to a socket: {e:?}");
exit(1);
});
Some((rpc, tpu))

View File

@ -308,7 +308,7 @@ mod test {
let mut b: Bloom<Hash> = Bloom::new(3, vec![100]);
b.add(&Hash::default());
assert_eq!(
format!("{:?}", b),
format!("{b:?}"),
"Bloom { keys.len: 1 bits.len: 3 num_set: 1 bits: 001 }"
);
@ -316,7 +316,7 @@ mod test {
b.add(&Hash::default());
b.add(&hash(&[1, 2]));
assert_eq!(
format!("{:?}", b),
format!("{b:?}"),
"Bloom { keys.len: 1 bits.len: 1000 num_set: 2 bits: 0000000000.. }"
);
}
@ -345,7 +345,7 @@ mod test {
.take(10_000)
.filter(|hash_value| bloom.contains(hash_value))
.count();
assert!(false_positive < 2_000, "false_positive: {}", false_positive);
assert!(false_positive < 2_000, "false_positive: {false_positive}");
}
#[test]
@ -360,7 +360,7 @@ mod test {
bloom.add(hash_value);
}
let num_bits_set = bloom.num_bits_set;
assert!(num_bits_set > 2000, "# bits set: {}", num_bits_set);
assert!(num_bits_set > 2000, "# bits set: {num_bits_set}");
// Round-trip with no inserts.
let bloom: AtomicBloom<_> = bloom.into();
assert_eq!(bloom.num_bits, 9731);
@ -408,7 +408,7 @@ mod test {
.take(10_000)
.filter(|hash_value| bloom.contains(hash_value))
.count();
assert!(false_positive < 2000, "false_positive: {}", false_positive);
assert!(false_positive < 2000, "false_positive: {false_positive}");
let bloom: Bloom<_> = bloom.into();
assert_eq!(bloom.bits.len(), 9731);
assert!(bloom.num_bits_set > num_bits_set);
@ -427,7 +427,7 @@ mod test {
.take(10_000)
.filter(|hash_value| bloom.contains(hash_value))
.count();
assert!(false_positive < 2000, "false_positive: {}", false_positive);
assert!(false_positive < 2000, "false_positive: {false_positive}");
// Assert that the bits vector precisely match if no atomic ops were
// used.
let bits = bloom.bits;

View File

@ -559,7 +559,7 @@ mod tests {
map.insert(&k, (&v, rc))
} else {
map.update(&k, |current| {
assert_eq!(current, v_old.map(|(v, rc)| (&v[..], *rc)), "{}", k);
assert_eq!(current, v_old.map(|(v, rc)| (&v[..], *rc)), "{k}");
Some((v.clone(), rc))
})
}

View File

@ -219,7 +219,7 @@ mod tests {
use std::env;
let out_dir = env::var("FARF_DIR").unwrap_or_else(|_| "farf".to_string());
format!("{}/tmp/{}-{}", out_dir, name, pubkey)
format!("{out_dir}/tmp/{name}-{pubkey}")
}
#[test]
@ -338,8 +338,8 @@ mod tests {
let key2 = solana_sdk::pubkey::new_rand();
let sig1 = Keypair::new().sign_message(&[0u8]);
let sig2 = Keypair::new().sign_message(&[1u8]);
let signer1 = format!("{}={}", key1, sig1);
let signer2 = format!("{}={}", key2, sig2);
let signer1 = format!("{key1}={sig1}");
let signer2 = format!("{key2}={sig2}");
let matches = app().clone().get_matches_from(vec![
"test",
"--multiple",

View File

@ -20,7 +20,7 @@ where
.as_ref()
.parse::<U>()
.map(|_| ())
.map_err(|err| format!("error parsing '{}': {}", string, err))
.map_err(|err| format!("error parsing '{string}': {err}"))
}
// Return an error if string cannot be parsed as type T.
@ -45,14 +45,13 @@ where
let range = range_min..range_max + 1.into();
if !range.contains(&input) {
Err(format!(
"input '{:?}' out of range ({:?}..{:?}]",
input, range_min, range_max
"input '{input:?}' out of range ({range_min:?}..{range_max:?}]"
))
} else {
Ok(())
}
}
Err(err) => Err(format!("error parsing '{}': {}", string, err)),
Err(err) => Err(format!("error parsing '{string}': {err}")),
}
}
@ -79,7 +78,7 @@ where
{
read_keypair_file(string.as_ref())
.map(|_| ())
.map_err(|err| format!("{}", err))
.map_err(|err| format!("{err}"))
}
// Return an error if a keypair file cannot be parsed
@ -92,7 +91,7 @@ where
}
read_keypair_file(string.as_ref())
.map(|_| ())
.map_err(|err| format!("{}", err))
.map_err(|err| format!("{err}"))
}
// Return an error if a `SignerSourceKind::Prompt` cannot be parsed
@ -104,13 +103,12 @@ where
return Ok(());
}
match parse_signer_source(string.as_ref())
.map_err(|err| format!("{}", err))?
.map_err(|err| format!("{err}"))?
.kind
{
SignerSourceKind::Prompt => Ok(()),
_ => Err(format!(
"Unable to parse input as `prompt:` URI scheme or `ASK` keyword: {}",
string
"Unable to parse input as `prompt:` URI scheme or `ASK` keyword: {string}"
)),
}
}
@ -130,7 +128,7 @@ where
T: AsRef<str> + Display,
{
match parse_signer_source(string.as_ref())
.map_err(|err| format!("{}", err))?
.map_err(|err| format!("{err}"))?
.kind
{
SignerSourceKind::Filepath(path) => is_keypair(path),
@ -171,10 +169,10 @@ where
.ok_or_else(|| "Malformed signer string".to_string())?,
) {
Ok(_) => Ok(()),
Err(err) => Err(format!("{}", err)),
Err(err) => Err(format!("{err}")),
}
}
Err(err) => Err(format!("{}", err)),
Err(err) => Err(format!("{err}")),
}
}
@ -191,7 +189,7 @@ where
Err("no host provided".to_string())
}
}
Err(err) => Err(format!("{}", err)),
Err(err) => Err(format!("{err}")),
}
}
@ -207,7 +205,7 @@ where
Err("no host provided".to_string())
}
}
Err(err) => Err(format!("{}", err)),
Err(err) => Err(format!("{err}")),
}
}
@ -242,10 +240,10 @@ where
{
bins.as_ref()
.parse::<usize>()
.map_err(|e| format!("Unable to parse, provided: {}, err: {}", bins, e))
.map_err(|e| format!("Unable to parse, provided: {bins}, err: {e}"))
.and_then(|v| {
if !v.is_power_of_two() {
Err(format!("Must be a power of 2: {}", v))
Err(format!("Must be a power of 2: {v}"))
} else {
Ok(())
}
@ -266,17 +264,11 @@ where
percentage
.as_ref()
.parse::<u8>()
.map_err(|e| {
format!(
"Unable to parse input percentage, provided: {}, err: {}",
percentage, e
)
})
.map_err(|e| format!("Unable to parse input percentage, provided: {percentage}, err: {e}"))
.and_then(|v| {
if v > 100 {
Err(format!(
"Percentage must be in range of 0 to 100, provided: {}",
v
"Percentage must be in range of 0 to 100, provided: {v}"
))
} else {
Ok(())
@ -292,8 +284,7 @@ where
Ok(())
} else {
Err(format!(
"Unable to parse input amount as integer or float, provided: {}",
amount
"Unable to parse input amount as integer or float, provided: {amount}"
))
}
}
@ -309,8 +300,7 @@ where
Ok(())
} else {
Err(format!(
"Unable to parse input amount as integer or float, provided: {}",
amount
"Unable to parse input amount as integer or float, provided: {amount}"
))
}
}
@ -321,7 +311,7 @@ where
{
DateTime::parse_from_rfc3339(value.as_ref())
.map(|_| ())
.map_err(|e| format!("{}", e))
.map_err(|e| format!("{e}"))
}
pub fn is_derivation<T>(value: T) -> Result<(), String>
@ -333,19 +323,11 @@ where
let account = parts.next().unwrap();
account
.parse::<u32>()
.map_err(|e| {
format!(
"Unable to parse derivation, provided: {}, err: {}",
account, e
)
})
.map_err(|e| format!("Unable to parse derivation, provided: {account}, err: {e}"))
.and_then(|_| {
if let Some(change) = parts.next() {
change.parse::<u32>().map_err(|e| {
format!(
"Unable to parse derivation, provided: {}, err: {}",
change, e
)
format!("Unable to parse derivation, provided: {change}, err: {e}")
})
} else {
Ok(0)
@ -361,8 +343,7 @@ where
let value = value.as_ref();
if value.len() > MAX_SEED_LEN {
Err(format!(
"Address seed must not be longer than {} bytes",
MAX_SEED_LEN
"Address seed must not be longer than {MAX_SEED_LEN} bytes"
))
} else {
Ok(())
@ -373,12 +354,10 @@ pub fn is_niceness_adjustment_valid<T>(value: T) -> Result<(), String>
where
T: AsRef<str> + Display,
{
let adjustment = value.as_ref().parse::<i8>().map_err(|err| {
format!(
"error parsing niceness adjustment value '{}': {}",
value, err
)
})?;
let adjustment = value
.as_ref()
.parse::<i8>()
.map_err(|err| format!("error parsing niceness adjustment value '{value}': {err}"))?;
if solana_perf::thread::is_renice_allowed(adjustment) {
Ok(())
} else {

View File

@ -423,7 +423,7 @@ impl AsRef<str> for SignerSourceKind {
impl std::fmt::Debug for SignerSourceKind {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let s: &str = self.as_ref();
write!(f, "{}", s)
write!(f, "{s}")
}
}
@ -775,7 +775,7 @@ pub fn signer_from_path_with_config(
SignerSourceKind::Filepath(path) => match read_keypair_file(&path) {
Err(e) => Err(std::io::Error::new(
std::io::ErrorKind::Other,
format!("could not read keypair file \"{}\". Run \"solana-keygen new\" to create a keypair file: {}", path, e),
format!("could not read keypair file \"{path}\". Run \"solana-keygen new\" to create a keypair file: {e}"),
)
.into()),
Ok(file) => Ok(Box::new(file)),
@ -811,7 +811,7 @@ pub fn signer_from_path_with_config(
} else {
Err(std::io::Error::new(
std::io::ErrorKind::Other,
format!("missing signature for supplied pubkey: {}", pubkey),
format!("missing signature for supplied pubkey: {pubkey}"),
)
.into())
}
@ -898,9 +898,8 @@ pub fn resolve_signer_from_path(
Err(e) => Err(std::io::Error::new(
std::io::ErrorKind::Other,
format!(
"could not read keypair file \"{}\". \
Run \"solana-keygen new\" to create a keypair file: {}",
path, e
"could not read keypair file \"{path}\". \
Run \"solana-keygen new\" to create a keypair file: {e}"
),
)
.into()),
@ -1021,9 +1020,8 @@ pub fn keypair_from_path(
Err(e) => Err(std::io::Error::new(
std::io::ErrorKind::Other,
format!(
"could not read keypair file \"{}\". \
Run \"solana-keygen new\" to create a keypair file: {}",
path, e
"could not read keypair file \"{path}\". \
Run \"solana-keygen new\" to create a keypair file: {e}"
),
)
.into()),
@ -1035,10 +1033,7 @@ pub fn keypair_from_path(
}
_ => Err(std::io::Error::new(
std::io::ErrorKind::Other,
format!(
"signer of type `{:?}` does not support Keypair output",
kind
),
format!("signer of type `{kind:?}` does not support Keypair output"),
)
.into()),
}
@ -1055,11 +1050,10 @@ pub fn keypair_from_seed_phrase(
derivation_path: Option<DerivationPath>,
legacy: bool,
) -> Result<Keypair, Box<dyn error::Error>> {
let seed_phrase = prompt_password(format!("[{}] seed phrase: ", keypair_name))?;
let seed_phrase = prompt_password(format!("[{keypair_name}] seed phrase: "))?;
let seed_phrase = seed_phrase.trim();
let passphrase_prompt = format!(
"[{}] If this seed phrase has an associated passphrase, enter it now. Otherwise, press ENTER to continue: ",
keypair_name,
"[{keypair_name}] If this seed phrase has an associated passphrase, enter it now. Otherwise, press ENTER to continue: ",
);
let keypair = if skip_validation {
@ -1101,7 +1095,7 @@ pub fn keypair_from_seed_phrase(
if confirm_pubkey {
let pubkey = keypair.pubkey();
print!("Recovered pubkey `{:?}`. Continue? (y/n): ", pubkey);
print!("Recovered pubkey `{pubkey:?}`. Continue? (y/n): ");
let _ignored = stdout().flush();
let mut input = String::new();
stdin().read_line(&mut input).expect("Unexpected input");
@ -1275,14 +1269,14 @@ mod tests {
}
));
assert!(
matches!(parse_signer_source(format!("file:{}", absolute_path_str)).unwrap(), SignerSource {
matches!(parse_signer_source(format!("file:{absolute_path_str}")).unwrap(), SignerSource {
kind: SignerSourceKind::Filepath(p),
derivation_path: None,
legacy: false,
} if p == absolute_path_str)
);
assert!(
matches!(parse_signer_source(format!("file:{}", relative_path_str)).unwrap(), SignerSource {
matches!(parse_signer_source(format!("file:{relative_path_str}")).unwrap(), SignerSource {
kind: SignerSourceKind::Filepath(p),
derivation_path: None,
legacy: false,

View File

@ -220,7 +220,7 @@ mod tests {
use std::env;
let out_dir = env::var("FARF_DIR").unwrap_or_else(|_| "farf".to_string());
format!("{}/tmp/{}-{}", out_dir, name, pubkey)
format!("{out_dir}/tmp/{name}-{pubkey}")
}
#[test]
@ -339,8 +339,8 @@ mod tests {
let key2 = solana_sdk::pubkey::new_rand();
let sig1 = Keypair::new().sign_message(&[0u8]);
let sig2 = Keypair::new().sign_message(&[1u8]);
let signer1 = format!("{}={}", key1, sig1);
let signer2 = format!("{}={}", key2, sig2);
let signer1 = format!("{key1}={sig1}");
let signer2 = format!("{key2}={sig2}");
let matches = app().clone().get_matches_from(vec![
"test",
"--multiple",

View File

@ -20,7 +20,7 @@ where
.as_ref()
.parse::<U>()
.map(|_| ())
.map_err(|err| format!("error parsing '{}': {}", string, err))
.map_err(|err| format!("error parsing '{string}': {err}"))
}
// Return an error if string cannot be parsed as type T.
@ -45,14 +45,13 @@ where
let range = range_min..range_max + 1.into();
if !range.contains(&input) {
Err(format!(
"input '{:?}' out of range ({:?}..{:?}]",
input, range_min, range_max
"input '{input:?}' out of range ({range_min:?}..{range_max:?}]"
))
} else {
Ok(())
}
}
Err(err) => Err(format!("error parsing '{}': {}", string, err)),
Err(err) => Err(format!("error parsing '{string}': {err}")),
}
}
@ -76,7 +75,7 @@ where
{
read_keypair_file(string.as_ref())
.map(|_| ())
.map_err(|err| format!("{}", err))
.map_err(|err| format!("{err}"))
}
// Return an error if a keypair file cannot be parsed
@ -89,7 +88,7 @@ where
}
read_keypair_file(string.as_ref())
.map(|_| ())
.map_err(|err| format!("{}", err))
.map_err(|err| format!("{err}"))
}
// Return an error if a `SignerSourceKind::Prompt` cannot be parsed
@ -98,13 +97,12 @@ pub fn is_prompt_signer_source(string: &str) -> Result<(), String> {
return Ok(());
}
match parse_signer_source(string)
.map_err(|err| format!("{}", err))?
.map_err(|err| format!("{err}"))?
.kind
{
SignerSourceKind::Prompt => Ok(()),
_ => Err(format!(
"Unable to parse input as `prompt:` URI scheme or `ASK` keyword: {}",
string
"Unable to parse input as `prompt:` URI scheme or `ASK` keyword: {string}"
)),
}
}
@ -124,7 +122,7 @@ where
T: AsRef<str> + Display,
{
match parse_signer_source(string.as_ref())
.map_err(|err| format!("{}", err))?
.map_err(|err| format!("{err}"))?
.kind
{
SignerSourceKind::Filepath(path) => is_keypair(path),
@ -165,10 +163,10 @@ where
.ok_or_else(|| "Malformed signer string".to_string())?,
) {
Ok(_) => Ok(()),
Err(err) => Err(format!("{}", err)),
Err(err) => Err(format!("{err}")),
}
}
Err(err) => Err(format!("{}", err)),
Err(err) => Err(format!("{err}")),
}
}
@ -185,7 +183,7 @@ where
Err("no host provided".to_string())
}
}
Err(err) => Err(format!("{}", err)),
Err(err) => Err(format!("{err}")),
}
}
@ -201,7 +199,7 @@ where
Err("no host provided".to_string())
}
}
Err(err) => Err(format!("{}", err)),
Err(err) => Err(format!("{err}")),
}
}
@ -236,10 +234,10 @@ where
{
bins.as_ref()
.parse::<usize>()
.map_err(|e| format!("Unable to parse, provided: {}, err: {}", bins, e))
.map_err(|e| format!("Unable to parse, provided: {bins}, err: {e}"))
.and_then(|v| {
if !v.is_power_of_two() {
Err(format!("Must be a power of 2: {}", v))
Err(format!("Must be a power of 2: {v}"))
} else {
Ok(())
}
@ -260,17 +258,11 @@ where
percentage
.as_ref()
.parse::<u8>()
.map_err(|e| {
format!(
"Unable to parse input percentage, provided: {}, err: {}",
percentage, e
)
})
.map_err(|e| format!("Unable to parse input percentage, provided: {percentage}, err: {e}"))
.and_then(|v| {
if v > 100 {
Err(format!(
"Percentage must be in range of 0 to 100, provided: {}",
v
"Percentage must be in range of 0 to 100, provided: {v}"
))
} else {
Ok(())
@ -286,8 +278,7 @@ where
Ok(())
} else {
Err(format!(
"Unable to parse input amount as integer or float, provided: {}",
amount
"Unable to parse input amount as integer or float, provided: {amount}"
))
}
}
@ -303,8 +294,7 @@ where
Ok(())
} else {
Err(format!(
"Unable to parse input amount as integer or float, provided: {}",
amount
"Unable to parse input amount as integer or float, provided: {amount}"
))
}
}
@ -315,7 +305,7 @@ where
{
DateTime::parse_from_rfc3339(value.as_ref())
.map(|_| ())
.map_err(|e| format!("{}", e))
.map_err(|e| format!("{e}"))
}
pub fn is_derivation<T>(value: T) -> Result<(), String>
@ -327,19 +317,11 @@ where
let account = parts.next().unwrap();
account
.parse::<u32>()
.map_err(|e| {
format!(
"Unable to parse derivation, provided: {}, err: {}",
account, e
)
})
.map_err(|e| format!("Unable to parse derivation, provided: {account}, err: {e}"))
.and_then(|_| {
if let Some(change) = parts.next() {
change.parse::<u32>().map_err(|e| {
format!(
"Unable to parse derivation, provided: {}, err: {}",
change, e
)
format!("Unable to parse derivation, provided: {change}, err: {e}")
})
} else {
Ok(0)
@ -355,8 +337,7 @@ where
let value = value.as_ref();
if value.len() > MAX_SEED_LEN {
Err(format!(
"Address seed must not be longer than {} bytes",
MAX_SEED_LEN
"Address seed must not be longer than {MAX_SEED_LEN} bytes"
))
} else {
Ok(())
@ -367,12 +348,10 @@ pub fn is_niceness_adjustment_valid<T>(value: T) -> Result<(), String>
where
T: AsRef<str> + Display,
{
let adjustment = value.as_ref().parse::<i8>().map_err(|err| {
format!(
"error parsing niceness adjustment value '{}': {}",
value, err
)
})?;
let adjustment = value
.as_ref()
.parse::<i8>()
.map_err(|err| format!("error parsing niceness adjustment value '{value}': {err}"))?;
if solana_perf::thread::is_renice_allowed(adjustment) {
Ok(())
} else {

View File

@ -423,7 +423,7 @@ impl AsRef<str> for SignerSourceKind {
impl std::fmt::Debug for SignerSourceKind {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let s: &str = self.as_ref();
write!(f, "{}", s)
write!(f, "{s}")
}
}
@ -775,7 +775,7 @@ pub fn signer_from_path_with_config(
SignerSourceKind::Filepath(path) => match read_keypair_file(&path) {
Err(e) => Err(std::io::Error::new(
std::io::ErrorKind::Other,
format!("could not read keypair file \"{}\". Run \"solana-keygen new\" to create a keypair file: {}", path, e),
format!("could not read keypair file \"{path}\". Run \"solana-keygen new\" to create a keypair file: {e}"),
)
.into()),
Ok(file) => Ok(Box::new(file)),
@ -811,7 +811,7 @@ pub fn signer_from_path_with_config(
} else {
Err(std::io::Error::new(
std::io::ErrorKind::Other,
format!("missing signature for supplied pubkey: {}", pubkey),
format!("missing signature for supplied pubkey: {pubkey}"),
)
.into())
}
@ -898,9 +898,8 @@ pub fn resolve_signer_from_path(
Err(e) => Err(std::io::Error::new(
std::io::ErrorKind::Other,
format!(
"could not read keypair file \"{}\". \
Run \"solana-keygen new\" to create a keypair file: {}",
path, e
"could not read keypair file \"{path}\". \
Run \"solana-keygen new\" to create a keypair file: {e}"
),
)
.into()),
@ -1021,9 +1020,8 @@ pub fn keypair_from_path(
Err(e) => Err(std::io::Error::new(
std::io::ErrorKind::Other,
format!(
"could not read keypair file \"{}\". \
Run \"solana-keygen new\" to create a keypair file: {}",
path, e
"could not read keypair file \"{path}\". \
Run \"solana-keygen new\" to create a keypair file: {e}"
),
)
.into()),
@ -1035,10 +1033,7 @@ pub fn keypair_from_path(
}
_ => Err(std::io::Error::new(
std::io::ErrorKind::Other,
format!(
"signer of type `{:?}` does not support Keypair output",
kind
),
format!("signer of type `{kind:?}` does not support Keypair output"),
)
.into()),
}
@ -1055,11 +1050,10 @@ pub fn keypair_from_seed_phrase(
derivation_path: Option<DerivationPath>,
legacy: bool,
) -> Result<Keypair, Box<dyn error::Error>> {
let seed_phrase = prompt_password(format!("[{}] seed phrase: ", keypair_name))?;
let seed_phrase = prompt_password(format!("[{keypair_name}] seed phrase: "))?;
let seed_phrase = seed_phrase.trim();
let passphrase_prompt = format!(
"[{}] If this seed phrase has an associated passphrase, enter it now. Otherwise, press ENTER to continue: ",
keypair_name,
"[{keypair_name}] If this seed phrase has an associated passphrase, enter it now. Otherwise, press ENTER to continue: ",
);
let keypair = if skip_validation {
@ -1101,7 +1095,7 @@ pub fn keypair_from_seed_phrase(
if confirm_pubkey {
let pubkey = keypair.pubkey();
print!("Recovered pubkey `{:?}`. Continue? (y/n): ", pubkey);
print!("Recovered pubkey `{pubkey:?}`. Continue? (y/n): ");
let _ignored = stdout().flush();
let mut input = String::new();
stdin().read_line(&mut input).expect("Unexpected input");
@ -1275,14 +1269,14 @@ mod tests {
}
));
assert!(
matches!(parse_signer_source(format!("file:{}", absolute_path_str)).unwrap(), SignerSource {
matches!(parse_signer_source(format!("file:{absolute_path_str}")).unwrap(), SignerSource {
kind: SignerSourceKind::Filepath(p),
derivation_path: None,
legacy: false,
} if p == absolute_path_str)
);
assert!(
matches!(parse_signer_source(format!("file:{}", relative_path_str)).unwrap(), SignerSource {
matches!(parse_signer_source(format!("file:{relative_path_str}")).unwrap(), SignerSource {
kind: SignerSourceKind::Filepath(p),
derivation_path: None,
legacy: false,

View File

@ -83,7 +83,7 @@ where
{
let file = File::open(config_file)?;
let config = serde_yaml::from_reader(file)
.map_err(|err| io::Error::new(io::ErrorKind::Other, format!("{:?}", err)))?;
.map_err(|err| io::Error::new(io::ErrorKind::Other, format!("{err:?}")))?;
Ok(config)
}
@ -106,7 +106,7 @@ where
P: AsRef<Path>,
{
let serialized = serde_yaml::to_string(config)
.map_err(|err| io::Error::new(io::ErrorKind::Other, format!("{:?}", err)))?;
.map_err(|err| io::Error::new(io::ErrorKind::Other, format!("{err:?}")))?;
if let Some(outdir) = config_file.as_ref().parent() {
create_dir_all(outdir)?;

View File

@ -71,7 +71,7 @@ impl OutputFormat {
T: Serialize + fmt::Display + QuietDisplay + VerboseDisplay,
{
match self {
OutputFormat::Display => format!("{}", item),
OutputFormat::Display => format!("{item}"),
OutputFormat::DisplayQuiet => {
let mut s = String::new();
QuietDisplay::write_str(item, &mut s).unwrap();
@ -342,7 +342,7 @@ impl fmt::Display for CliEpochInfo {
writeln_name_value(
f,
"Epoch Slot Range:",
&format!("[{}..{})", start_slot, end_slot),
&format!("[{start_slot}..{end_slot})"),
)?;
writeln_name_value(
f,
@ -387,7 +387,7 @@ impl fmt::Display for CliEpochInfo {
)?;
if let Some(annotation) = annotation {
writeln!(f)?;
writeln!(f, "{}", annotation)?;
writeln!(f, "{annotation}")?;
}
Ok(())
}
@ -457,11 +457,11 @@ impl fmt::Display for CliValidators {
if v == 0 {
" - ".into()
} else if v == max_v {
format!("{:>9} ( 0)", v)
format!("{v:>9} ( 0)")
} else if v > max_v.saturating_sub(100) {
format!("{:>9} ({:>3})", v, -(max_v.saturating_sub(v) as isize))
} else {
format!("{:>9} ", v)
format!("{v:>9} ")
}
}
@ -479,7 +479,7 @@ impl fmt::Display for CliValidators {
non_zero_or_dash(validator.last_vote, highest_last_vote),
non_zero_or_dash(validator.root_slot, highest_root),
if let Some(skip_rate) = validator.skip_rate {
format!("{:.2}%", skip_rate)
format!("{skip_rate:.2}%")
} else {
"- ".to_string()
},
@ -518,7 +518,7 @@ impl fmt::Display for CliValidators {
padding = padding + 2
))
.bold();
writeln!(f, "{}", header)?;
writeln!(f, "{header}")?;
let mut sorted_validators = self.validators.clone();
match self.validators_sort_order {
@ -590,7 +590,7 @@ impl fmt::Display for CliValidators {
} else {
sorted_validators.len() - i
};
write!(f, "{:padding$} ", num, padding = padding)?;
write!(f, "{num:padding$} ")?;
}
write_vote_account(
f,
@ -604,7 +604,7 @@ impl fmt::Display for CliValidators {
// The actual header has long scrolled away. Print the header once more as a footer
if self.validators.len() > 100 {
writeln!(f, "{}", header)?;
writeln!(f, "{header}")?;
}
writeln!(f)?;
@ -794,14 +794,14 @@ impl fmt::Display for CliNonceAccount {
)
)?;
let nonce = self.nonce.as_deref().unwrap_or("uninitialized");
writeln!(f, "Nonce blockhash: {}", nonce)?;
writeln!(f, "Nonce blockhash: {nonce}")?;
if let Some(fees) = self.lamports_per_signature {
writeln!(f, "Fee: {} lamports per signature", fees)?;
writeln!(f, "Fee: {fees} lamports per signature")?;
} else {
writeln!(f, "Fees: uninitialized")?;
}
let authority = self.authority.as_deref().unwrap_or("uninitialized");
writeln!(f, "Authority: {}", authority)
writeln!(f, "Authority: {authority}")
}
}
@ -829,7 +829,7 @@ impl fmt::Display for CliStakeVec {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for state in &self.0 {
writeln!(f)?;
write!(f, "{}", state)?;
write!(f, "{state}")?;
}
Ok(())
}
@ -927,11 +927,11 @@ impl fmt::Display for CliKeyedEpochRewards {
reward.percent_change,
reward
.apr
.map(|apr| format!("{:.2}%", apr))
.map(|apr| format!("{apr:.2}%"))
.unwrap_or_default(),
reward
.commission
.map(|commission| format!("{}%", commission))
.map(|commission| format!("{commission}%"))
.unwrap_or_else(|| "-".to_string())
)?;
}
@ -1028,8 +1028,7 @@ fn show_votes_and_credits(
writeln!(
f,
"- ... (omitting {} past rooted votes, which have already been credited)",
count
"- ... (omitting {count} past rooted votes, which have already been credited)"
)?;
}
}
@ -1063,11 +1062,11 @@ fn show_epoch_rewards(
reward.percent_change,
reward
.apr
.map(|apr| format!("{:.2}%", apr))
.map(|apr| format!("{apr:.2}%"))
.unwrap_or_default(),
reward
.commission
.map(|commission| format!("{}%", commission))
.map(|commission| format!("{commission}%"))
.unwrap_or_else(|| "-".to_string())
)?;
}
@ -1113,9 +1112,9 @@ pub struct CliStakeState {
impl QuietDisplay for CliStakeState {}
impl VerboseDisplay for CliStakeState {
fn write_str(&self, w: &mut dyn std::fmt::Write) -> std::fmt::Result {
write!(w, "{}", self)?;
write!(w, "{self}")?;
if let Some(credits) = self.credits_observed {
writeln!(w, "Credits Observed: {}", credits)?;
writeln!(w, "Credits Observed: {credits}")?;
}
Ok(())
}
@ -1246,8 +1245,7 @@ impl fmt::Display for CliStakeState {
}
writeln!(
f,
"Stake deactivates starting from epoch: {}",
deactivation_epoch
"Stake deactivates starting from epoch: {deactivation_epoch}"
)?;
}
if let Some(delegated_vote_account_address) =
@ -1255,8 +1253,7 @@ impl fmt::Display for CliStakeState {
{
writeln!(
f,
"Delegated Vote Account Address: {}",
delegated_vote_account_address
"Delegated Vote Account Address: {delegated_vote_account_address}"
)?;
}
} else {
@ -1405,7 +1402,7 @@ impl fmt::Display for CliValidatorInfoVec {
}
for validator_info in &self.0 {
writeln!(f)?;
write!(f, "{}", validator_info)?;
write!(f, "{validator_info}")?;
}
Ok(())
}
@ -1695,19 +1692,19 @@ impl fmt::Display for CliSignOnlyData {
if !self.signers.is_empty() {
writeln!(f, "{}", style("Signers (Pubkey=Signature):").bold())?;
for signer in self.signers.iter() {
writeln!(f, " {}", signer)?;
writeln!(f, " {signer}")?;
}
}
if !self.absent.is_empty() {
writeln!(f, "{}", style("Absent Signers (Pubkey):").bold())?;
for pubkey in self.absent.iter() {
writeln!(f, " {}", pubkey)?;
writeln!(f, " {pubkey}")?;
}
}
if !self.bad_sig.is_empty() {
writeln!(f, "{}", style("Bad Signatures (Pubkey):").bold())?;
for pubkey in self.bad_sig.iter() {
writeln!(f, " {}", pubkey)?;
writeln!(f, " {pubkey}")?;
}
}
Ok(())
@ -1802,7 +1799,7 @@ impl fmt::Display for CliSupply {
writeln!(f)?;
writeln_name_value(f, "Non-Circulating Accounts:", " ")?;
for account in &self.non_circulating_accounts {
writeln!(f, " {}", account)?;
writeln!(f, " {account}")?;
}
}
Ok(())
@ -1851,7 +1848,7 @@ impl VerboseDisplay for CliFees {}
impl fmt::Display for CliFees {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.inner.as_ref() {
Some(inner) => write!(f, "{}", inner),
Some(inner) => write!(f, "{inner}"),
None => write!(f, "Fees unavailable"),
}
}
@ -2217,7 +2214,7 @@ impl fmt::Display for CliAddressLookupTable {
style(format!(" {:<5} {}", "Index", "Address")).bold()
)?;
for (index, address) in self.addresses.iter().enumerate() {
writeln!(f, " {:<5} {}", index, address)?;
writeln!(f, " {index:<5} {address}")?;
}
}
Ok(())
@ -2273,7 +2270,7 @@ pub fn return_signers_data(tx: &Transaction, config: &ReturnSignersConfig) -> Cl
.zip(verify_results.into_iter())
.for_each(|((sig, key), res)| {
if res {
signers.push(format!("{}={}", key, sig))
signers.push(format!("{key}={sig}"))
} else if *sig == Signature::default() {
absent.push(key.to_string());
} else {
@ -2418,7 +2415,7 @@ impl fmt::Display for CliBlock {
writeln!(f, "Block Time: {:?}", Local.timestamp(block_time, 0))?;
}
if let Some(block_height) = self.encoded_confirmed_block.block_height {
writeln!(f, "Block Height: {:?}", block_height)?;
writeln!(f, "Block Height: {block_height:?}")?;
}
if !self.encoded_confirmed_block.rewards.is_empty() {
let mut rewards = self.encoded_confirmed_block.rewards.clone();
@ -2440,7 +2437,7 @@ impl fmt::Display for CliBlock {
" {:<44} {:^15} {:>15} {} {}",
reward.pubkey,
if let Some(reward_type) = reward.reward_type {
format!("{}", reward_type)
format!("{reward_type}")
} else {
"-".to_string()
},
@ -2462,7 +2459,7 @@ impl fmt::Display for CliBlock {
},
reward
.commission
.map(|commission| format!("{:>9}%", commission))
.map(|commission| format!("{commission:>9}%"))
.unwrap_or_else(|| " -".to_string())
)?;
}
@ -2478,7 +2475,7 @@ impl fmt::Display for CliBlock {
for (index, transaction_with_meta) in
self.encoded_confirmed_block.transactions.iter().enumerate()
{
writeln!(f, "Transaction {}:", index)?;
writeln!(f, "Transaction {index}:")?;
writeln_transaction(
f,
&transaction_with_meta.transaction.decode().unwrap(),
@ -2549,7 +2546,7 @@ impl VerboseDisplay for CliTransactionConfirmation {
"\nTransaction executed in slot {}:",
transaction.slot.expect("slot should exist")
)?;
write!(w, "{}", transaction)?;
write!(w, "{transaction}")?;
} else if let Some(confirmation_status) = &self.confirmation_status {
if confirmation_status != &TransactionConfirmationStatus::Finalized {
writeln!(w)?;
@ -2559,11 +2556,11 @@ impl VerboseDisplay for CliTransactionConfirmation {
)?;
} else if let Some(err) = &self.get_transaction_error {
writeln!(w)?;
writeln!(w, "Unable to get finalized transaction details: {}", err)?;
writeln!(w, "Unable to get finalized transaction details: {err}")?;
}
}
writeln!(w)?;
write!(w, "{}", self)
write!(w, "{self}")
}
}
@ -2573,9 +2570,9 @@ impl fmt::Display for CliTransactionConfirmation {
None => write!(f, "Not found"),
Some(confirmation_status) => {
if let Some(err) = &self.err {
write!(f, "Transaction failed: {}", err)
write!(f, "Transaction failed: {err}")
} else {
write!(f, "{:?}", confirmation_status)
write!(f, "{confirmation_status:?}")
}
}
}
@ -2668,7 +2665,7 @@ impl fmt::Display for CliGossipNodes {
--------+-------+-----------------------+---------+----------------",
)?;
for node in self.0.iter() {
writeln!(f, "{}", node)?;
writeln!(f, "{node}")?;
}
writeln!(f, "Nodes: {}", self.0.len())
}
@ -2703,19 +2700,18 @@ impl fmt::Display for CliPing {
};
writeln!(
f,
"Fixed blockhash is used: {} ({})",
fixed_blockhash, blockhash_origin
"Fixed blockhash is used: {fixed_blockhash} ({blockhash_origin})"
)?;
}
writeln!(f)?;
for ping in &self.pings {
write!(f, "{}", ping)?;
write!(f, "{ping}")?;
}
writeln!(f)?;
writeln!(f, "--- transaction statistics ---")?;
write!(f, "{}", self.transaction_stats)?;
if let Some(confirmation_stats) = &self.confirmation_stats {
write!(f, "{}", confirmation_stats)?;
write!(f, "{confirmation_stats}")?;
}
Ok(())
}
@ -2859,7 +2855,7 @@ impl QuietDisplay for CliBalance {
..self.config
};
let balance_message = build_balance_message_with_config(self.lamports, &config);
write!(w, "{}", balance_message)
write!(w, "{balance_message}")
}
}
@ -2871,14 +2867,14 @@ impl VerboseDisplay for CliBalance {
..self.config
};
let balance_message = build_balance_message_with_config(self.lamports, &config);
write!(w, "{}", balance_message)
write!(w, "{balance_message}")
}
}
impl fmt::Display for CliBalance {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let balance_message = build_balance_message_with_config(self.lamports, &self.config);
write!(f, "{}", balance_message)
write!(f, "{balance_message}")
}
}

View File

@ -18,7 +18,7 @@ impl fmt::Display for CliVersion {
None => "unknown".to_string(),
Some(version) => version.to_string(),
};
write!(f, "{}", s)
write!(f, "{s}")
}
}

View File

@ -53,7 +53,7 @@ pub fn build_balance_message_with_config(
lamports.to_string()
} else {
let sol = lamports_to_sol(lamports);
let sol_str = format!("{:.9}", sol);
let sol_str = format!("{sol:.9}");
if config.trim_trailing_zeros {
sol_str
.trim_end_matches('0')
@ -66,14 +66,14 @@ pub fn build_balance_message_with_config(
let unit = if config.show_unit {
if config.use_lamports_unit {
let ess = if lamports == 1 { "" } else { "s" };
format!(" lamport{}", ess)
format!(" lamport{ess}")
} else {
" SOL".to_string()
}
} else {
"".to_string()
};
format!("{}{}", value, unit)
format!("{value}{unit}")
}
pub fn build_balance_message(lamports: u64, use_lamports_unit: bool, show_unit: bool) -> String {
@ -141,18 +141,18 @@ pub fn println_signers(
bad_sig: &[String],
) {
println!();
println!("Blockhash: {}", blockhash);
println!("Blockhash: {blockhash}");
if !signers.is_empty() {
println!("Signers (Pubkey=Signature):");
signers.iter().for_each(|signer| println!(" {}", signer))
signers.iter().for_each(|signer| println!(" {signer}"))
}
if !absent.is_empty() {
println!("Absent Signers (Pubkey):");
absent.iter().for_each(|pubkey| println!(" {}", pubkey))
absent.iter().for_each(|pubkey| println!(" {pubkey}"))
}
if !bad_sig.is_empty() {
println!("Bad Signatures (Pubkey):");
bad_sig.iter().for_each(|pubkey| println!(" {}", pubkey))
bad_sig.iter().for_each(|pubkey| println!(" {pubkey}"))
}
println!();
}
@ -272,7 +272,7 @@ fn write_transaction<W: io::Write>(
write_return_data(w, transaction_status.return_data.as_ref().into(), prefix)?;
write_rewards(w, transaction_status.rewards.as_ref().into(), prefix)?;
} else {
writeln!(w, "{}Status: Unavailable", prefix)?;
writeln!(w, "{prefix}Status: Unavailable")?;
}
Ok(())
@ -325,7 +325,7 @@ fn write_block_time<W: io::Write>(
CliTimezone::Local => format!("{:?}", Local.timestamp(block_time, 0)),
CliTimezone::Utc => format!("{:?}", Utc.timestamp(block_time, 0)),
};
writeln!(w, "{}Block Time: {}", prefix, block_time_output,)?;
writeln!(w, "{prefix}Block Time: {block_time_output}",)?;
}
Ok(())
}
@ -339,7 +339,7 @@ fn write_version<W: io::Write>(
TransactionVersion::Legacy(_) => "legacy".to_string(),
TransactionVersion::Number(number) => number.to_string(),
};
writeln!(w, "{}Version: {}", prefix, version)
writeln!(w, "{prefix}Version: {version}")
}
fn write_recent_blockhash<W: io::Write>(
@ -347,7 +347,7 @@ fn write_recent_blockhash<W: io::Write>(
recent_blockhash: &Hash,
prefix: &str,
) -> io::Result<()> {
writeln!(w, "{}Recent Blockhash: {:?}", prefix, recent_blockhash)
writeln!(w, "{prefix}Recent Blockhash: {recent_blockhash:?}")
}
fn write_signatures<W: io::Write>(
@ -357,10 +357,7 @@ fn write_signatures<W: io::Write>(
prefix: &str,
) -> io::Result<()> {
let sigverify_statuses = if let Some(sigverify_status) = sigverify_status {
sigverify_status
.iter()
.map(|s| format!(" ({})", s))
.collect()
sigverify_status.iter().map(|s| format!(" ({s})")).collect()
} else {
vec!["".to_string(); signatures.len()]
};
@ -369,8 +366,7 @@ fn write_signatures<W: io::Write>(
{
writeln!(
w,
"{}Signature {}: {:?}{}",
prefix, signature_index, signature, sigverify_status,
"{prefix}Signature {signature_index}: {signature:?}{sigverify_status}",
)?;
}
Ok(())
@ -388,15 +384,14 @@ enum AccountKeyType<'a> {
impl fmt::Display for AccountKeyType<'_> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::Known(address) => write!(f, "{}", address),
Self::Known(address) => write!(f, "{address}"),
Self::Unknown {
lookup_index,
table_index,
} => {
write!(
f,
"Unknown Address (uses lookup {} and index {})",
lookup_index, table_index
"Unknown Address (uses lookup {lookup_index} and index {table_index})"
)
}
}
@ -430,7 +425,7 @@ fn write_instruction<'a, W: io::Write>(
instruction_accounts: impl Iterator<Item = (AccountKeyType<'a>, u8)>,
prefix: &str,
) -> io::Result<()> {
writeln!(w, "{}Instruction {}", prefix, instruction_index)?;
writeln!(w, "{prefix}Instruction {instruction_index}")?;
writeln!(
w,
"{} Program: {} ({})",
@ -439,8 +434,7 @@ fn write_instruction<'a, W: io::Write>(
for (index, (account_address, account_index)) in instruction_accounts.enumerate() {
writeln!(
w,
"{} Account {}: {} ({})",
prefix, index, account_address, account_index
"{prefix} Account {index}: {account_address} ({account_index})"
)?;
}
@ -451,14 +445,14 @@ fn write_instruction<'a, W: io::Write>(
solana_vote_program::vote_instruction::VoteInstruction,
>(&instruction.data)
{
writeln!(w, "{} {:?}", prefix, vote_instruction)?;
writeln!(w, "{prefix} {vote_instruction:?}")?;
raw = false;
}
} else if program_pubkey == &stake::program::id() {
if let Ok(stake_instruction) =
limited_deserialize::<stake::instruction::StakeInstruction>(&instruction.data)
{
writeln!(w, "{} {:?}", prefix, stake_instruction)?;
writeln!(w, "{prefix} {stake_instruction:?}")?;
raw = false;
}
} else if program_pubkey == &solana_sdk::system_program::id() {
@ -466,12 +460,12 @@ fn write_instruction<'a, W: io::Write>(
solana_sdk::system_instruction::SystemInstruction,
>(&instruction.data)
{
writeln!(w, "{} {:?}", prefix, system_instruction)?;
writeln!(w, "{prefix} {system_instruction:?}")?;
raw = false;
}
} else if is_memo_program(program_pubkey) {
if let Ok(s) = std::str::from_utf8(&instruction.data) {
writeln!(w, "{} Data: \"{}\"", prefix, s)?;
writeln!(w, "{prefix} Data: \"{s}\"")?;
raw = false;
}
}
@ -490,7 +484,7 @@ fn write_address_table_lookups<W: io::Write>(
prefix: &str,
) -> io::Result<()> {
for (lookup_index, lookup) in address_table_lookups.iter().enumerate() {
writeln!(w, "{}Address Table Lookup {}", prefix, lookup_index,)?;
writeln!(w, "{prefix}Address Table Lookup {lookup_index}",)?;
writeln!(w, "{} Table Account: {}", prefix, lookup.account_key,)?;
writeln!(
w,
@ -515,7 +509,7 @@ fn write_rewards<W: io::Write>(
) -> io::Result<()> {
if let Some(rewards) = rewards {
if !rewards.is_empty() {
writeln!(w, "{}Rewards:", prefix,)?;
writeln!(w, "{prefix}Rewards:",)?;
writeln!(
w,
"{} {:<44} {:^15} {:<16} {:<20}",
@ -529,7 +523,7 @@ fn write_rewards<W: io::Write>(
prefix,
reward.pubkey,
if let Some(reward_type) = reward.reward_type {
format!("{}", reward_type)
format!("{reward_type}")
} else {
"-".to_string()
},
@ -611,7 +605,7 @@ fn write_return_data<W: io::Write>(
UiReturnDataEncoding::Base64 => base64::decode(data).map_err(|err| {
io::Error::new(
io::ErrorKind::Other,
format!("could not parse data as {:?}: {:?}", encoding, err),
format!("could not parse data as {encoding:?}: {err:?}"),
)
})?,
};
@ -634,7 +628,7 @@ fn write_compute_units_consumed<W: io::Write>(
prefix: &str,
) -> io::Result<()> {
if let Some(cus) = compute_units_consumed {
writeln!(w, "{}Compute Units Consumed: {}", prefix, cus)?;
writeln!(w, "{prefix}Compute Units Consumed: {cus}")?;
}
Ok(())
}
@ -646,9 +640,9 @@ fn write_log_messages<W: io::Write>(
) -> io::Result<()> {
if let Some(log_messages) = log_messages {
if !log_messages.is_empty() {
writeln!(w, "{}Log Messages:", prefix,)?;
writeln!(w, "{prefix}Log Messages:",)?;
for log_message in log_messages {
writeln!(w, "{} {}", prefix, log_message)?;
writeln!(w, "{prefix} {log_message}")?;
}
}
}
@ -675,7 +669,7 @@ pub fn println_transaction(
.is_ok()
{
if let Ok(s) = String::from_utf8(w) {
print!("{}", s);
print!("{s}");
}
}
}
@ -701,7 +695,7 @@ pub fn writeln_transaction(
if write_result.is_ok() {
if let Ok(s) = String::from_utf8(w) {
write!(f, "{}", s)?;
write!(f, "{s}")?;
}
}
Ok(())
@ -722,7 +716,7 @@ pub fn new_spinner_progress_bar() -> ProgressBar {
pub fn unix_timestamp_to_string(unix_timestamp: UnixTimestamp) -> String {
match NaiveDateTime::from_timestamp_opt(unix_timestamp, 0) {
Some(ndt) => DateTime::<Utc>::from_utc(ndt, Utc).to_rfc3339_opts(SecondsFormat::Secs, true),
None => format!("UnixTimestamp {}", unix_timestamp),
None => format!("UnixTimestamp {unix_timestamp}"),
}
}

View File

@ -6,12 +6,12 @@ pub use cli_output::*;
pub trait QuietDisplay: std::fmt::Display {
fn write_str(&self, w: &mut dyn std::fmt::Write) -> std::fmt::Result {
write!(w, "{}", self)
write!(w, "{self}")
}
}
pub trait VerboseDisplay: std::fmt::Display {
fn write_str(&self, w: &mut dyn std::fmt::Write) -> std::fmt::Result {
write!(w, "{}", self)
write!(w, "{self}")
}
}

View File

@ -576,7 +576,7 @@ fn process_create_lookup_table(
},
);
match result {
Err(err) => Err(format!("Create failed: {}", err).into()),
Err(err) => Err(format!("Create failed: {err}").into()),
Ok(signature) => Ok(config
.output_format
.formatted_string(&CliAddressLookupTableCreated {
@ -635,7 +635,7 @@ fn process_freeze_lookup_table(
},
);
match result {
Err(err) => Err(format!("Freeze failed: {}", err).into()),
Err(err) => Err(format!("Freeze failed: {err}").into()),
Ok(signature) => Ok(config.output_format.formatted_string(&CliSignature {
signature: signature.to_string(),
})),
@ -695,7 +695,7 @@ fn process_extend_lookup_table(
},
);
match result {
Err(err) => Err(format!("Extend failed: {}", err).into()),
Err(err) => Err(format!("Extend failed: {err}").into()),
Ok(signature) => Ok(config.output_format.formatted_string(&CliSignature {
signature: signature.to_string(),
})),
@ -753,7 +753,7 @@ fn process_deactivate_lookup_table(
},
);
match result {
Err(err) => Err(format!("Deactivate failed: {}", err).into()),
Err(err) => Err(format!("Deactivate failed: {err}").into()),
Ok(signature) => Ok(config.output_format.formatted_string(&CliSignature {
signature: signature.to_string(),
})),
@ -810,7 +810,7 @@ fn process_close_lookup_table(
},
);
match result {
Err(err) => Err(format!("Close failed: {}", err).into()),
Err(err) => Err(format!("Close failed: {err}").into()),
Ok(signature) => Ok(config.output_format.formatted_string(&CliSignature {
signature: signature.to_string(),
})),

View File

@ -838,7 +838,7 @@ pub fn process_command(config: &CliConfig) -> ProcessResult {
if config.keypair_path.starts_with("usb://") {
let pubkey = config
.pubkey()
.map(|pubkey| format!("{:?}", pubkey))
.map(|pubkey| format!("{pubkey:?}"))
.unwrap_or_else(|_| "Unavailable".to_string());
println_name_value("Pubkey:", &pubkey);
}
@ -1817,7 +1817,7 @@ mod tests {
let test_commands = get_clap_app("test", "desc", "version");
let pubkey = solana_sdk::pubkey::new_rand();
let pubkey_string = format!("{}", pubkey);
let pubkey_string = format!("{pubkey}");
let default_keypair = Keypair::new();
let keypair_file = make_tmp_path("keypair_file");
@ -1889,7 +1889,7 @@ mod tests {
// Test Confirm Subcommand
let signature = Signature::new(&[1; 64]);
let signature_string = format!("{:?}", signature);
let signature_string = format!("{signature:?}");
let test_confirm =
test_commands
.clone()
@ -2520,7 +2520,7 @@ mod tests {
//Test Transfer Subcommand, submit offline `from`
let from_sig = from_keypair.sign_message(&[0u8]);
let from_signer = format!("{}={}", from_pubkey, from_sig);
let from_signer = format!("{from_pubkey}={from_sig}");
let test_transfer = test_commands.clone().get_matches_from(vec![
"test",
"transfer",

View File

@ -680,7 +680,7 @@ pub fn parse_transaction_history(
Some(signature) => Some(
signature
.parse()
.map_err(|err| CliError::BadParameter(format!("Invalid signature: {}", err)))?,
.map_err(|err| CliError::BadParameter(format!("Invalid signature: {err}")))?,
),
None => None,
};
@ -688,7 +688,7 @@ pub fn parse_transaction_history(
Some(signature) => Some(
signature
.parse()
.map_err(|err| CliError::BadParameter(format!("Invalid signature: {}", err)))?,
.map_err(|err| CliError::BadParameter(format!("Invalid signature: {err}")))?,
),
None => None,
};
@ -722,7 +722,7 @@ pub fn process_catchup(
progress_bar.set_message("Connecting...");
if let Some(our_localhost_port) = our_localhost_port {
let gussed_default = Some(format!("http://localhost:{}", our_localhost_port));
let gussed_default = Some(format!("http://localhost:{our_localhost_port}"));
if node_json_rpc_url.is_some() && node_json_rpc_url != gussed_default {
// go to new line to leave this message on console
println!(
@ -766,10 +766,10 @@ pub fn process_catchup(
if let Some(rpc_addr) = contact_info.rpc {
break rpc_addr;
}
progress_bar.set_message(format!("RPC service not found for {}", node_pubkey));
progress_bar.set_message(format!("RPC service not found for {node_pubkey}"));
} else {
progress_bar
.set_message(format!("Contact information not found for {}", node_pubkey));
.set_message(format!("Contact information not found for {node_pubkey}"));
}
sleep(Duration::from_secs(sleep_interval as u64));
};
@ -785,7 +785,7 @@ pub fn process_catchup(
Ok(reported_node_pubkey) => break reported_node_pubkey,
Err(err) => {
if let ClientErrorKind::Reqwest(err) = err.kind() {
progress_bar.set_message(format!("Connection failed: {}", err));
progress_bar.set_message(format!("Connection failed: {err}"));
sleep(Duration::from_secs(sleep_interval as u64));
continue;
}
@ -796,8 +796,7 @@ pub fn process_catchup(
if reported_node_pubkey != node_pubkey {
return Err(format!(
"The identity reported by node RPC URL does not match. Expected: {:?}. Reported: {:?}",
node_pubkey, reported_node_pubkey
"The identity reported by node RPC URL does not match. Expected: {node_pubkey:?}. Reported: {reported_node_pubkey:?}"
)
.into());
}
@ -824,7 +823,7 @@ pub fn process_catchup(
retry_count += 1;
if log {
// go to new line to leave this message on console
println!("Retrying({}/{}): {}\n", retry_count, max_retry_count, e);
println!("Retrying({retry_count}/{max_retry_count}): {e}\n");
}
sleep(Duration::from_secs(1));
}
@ -844,8 +843,7 @@ pub fn process_catchup(
if !follow && node_slot > std::cmp::min(previous_rpc_slot, rpc_slot) {
progress_bar.finish_and_clear();
return Ok(format!(
"{} has caught up (us:{} them:{})",
node_pubkey, node_slot, rpc_slot,
"{node_pubkey} has caught up (us:{node_slot} them:{rpc_slot})",
));
}
@ -864,10 +862,7 @@ pub fn process_catchup(
if !average_time_remaining.is_normal() {
"".to_string()
} else if average_time_remaining < 0.0 {
format!(
" (AVG: {:.1} slots/second (falling))",
average_catchup_slots_per_second
)
format!(" (AVG: {average_catchup_slots_per_second:.1} slots/second (falling))")
} else {
// important not to miss next scheduled lead slots
let total_node_slot_delta = node_slot as i64 - start_node_slot as i64;
@ -942,7 +937,7 @@ pub fn process_cluster_version(rpc_client: &RpcClient, config: &CliConfig) -> Pr
let remote_version = rpc_client.get_version()?;
if config.verbose {
Ok(format!("{:?}", remote_version))
Ok(format!("{remote_version:?}"))
} else {
Ok(remote_version.to_string())
}
@ -986,7 +981,7 @@ pub fn process_fees(
pub fn process_first_available_block(rpc_client: &RpcClient) -> ProcessResult {
let first_available_block = rpc_client.get_first_available_block()?;
Ok(format!("{}", first_available_block))
Ok(format!("{first_available_block}"))
}
pub fn parse_leader_schedule(matches: &ArgMatches<'_>) -> Result<CliCommandInfo, CliError> {
@ -1005,7 +1000,7 @@ pub fn process_leader_schedule(
let epoch_info = rpc_client.get_epoch_info()?;
let epoch = epoch.unwrap_or(epoch_info.epoch);
if epoch > epoch_info.epoch {
return Err(format!("Epoch {} is in the future", epoch).into());
return Err(format!("Epoch {epoch} is in the future").into());
}
let epoch_schedule = rpc_client.get_epoch_schedule()?;
@ -1013,11 +1008,9 @@ pub fn process_leader_schedule(
let leader_schedule = rpc_client.get_leader_schedule(Some(first_slot_in_epoch))?;
if leader_schedule.is_none() {
return Err(format!(
"Unable to fetch leader schedule for slot {}",
first_slot_in_epoch
)
.into());
return Err(
format!("Unable to fetch leader schedule for slot {first_slot_in_epoch}").into(),
);
}
let leader_schedule = leader_schedule.unwrap();
@ -1180,7 +1173,7 @@ pub fn process_show_block_production(
let epoch = epoch.unwrap_or(epoch_info.epoch);
if epoch > epoch_info.epoch {
return Err(format!("Epoch {} is in the future", epoch).into());
return Err(format!("Epoch {epoch} is in the future").into());
}
let first_slot_in_epoch = epoch_schedule.get_first_slot_in_epoch(epoch);
@ -1197,8 +1190,7 @@ pub fn process_show_block_production(
let progress_bar = new_spinner_progress_bar();
progress_bar.set_message(format!(
"Fetching confirmed blocks between slots {} and {}...",
start_slot, end_slot
"Fetching confirmed blocks between slots {start_slot} and {end_slot}..."
));
let slot_history_account = rpc_client
@ -1210,45 +1202,44 @@ pub fn process_show_block_production(
CliError::RpcRequestError("Failed to deserialize slot history".to_string())
})?;
let (confirmed_blocks, start_slot) =
if start_slot >= slot_history.oldest() && end_slot <= slot_history.newest() {
// Fast, more reliable path using the SlotHistory sysvar
let (confirmed_blocks, start_slot) = if start_slot >= slot_history.oldest()
&& end_slot <= slot_history.newest()
{
// Fast, more reliable path using the SlotHistory sysvar
let confirmed_blocks: Vec<_> = (start_slot..=end_slot)
.filter(|slot| slot_history.check(*slot) == slot_history::Check::Found)
.collect();
(confirmed_blocks, start_slot)
} else {
// Slow, less reliable path using `getBlocks`.
//
// "less reliable" because if the RPC node has holds in its ledger then the block production data will be
// incorrect. This condition currently can't be detected over RPC
//
let confirmed_blocks: Vec<_> = (start_slot..=end_slot)
.filter(|slot| slot_history.check(*slot) == slot_history::Check::Found)
.collect();
(confirmed_blocks, start_slot)
} else {
// Slow, less reliable path using `getBlocks`.
//
// "less reliable" because if the RPC node has holds in its ledger then the block production data will be
// incorrect. This condition currently can't be detected over RPC
//
let minimum_ledger_slot = rpc_client.minimum_ledger_slot()?;
if minimum_ledger_slot > end_slot {
return Err(format!(
"Ledger data not available for slots {} to {} (minimum ledger slot is {})",
start_slot, end_slot, minimum_ledger_slot
let minimum_ledger_slot = rpc_client.minimum_ledger_slot()?;
if minimum_ledger_slot > end_slot {
return Err(format!(
"Ledger data not available for slots {start_slot} to {end_slot} (minimum ledger slot is {minimum_ledger_slot})"
)
.into());
}
}
if minimum_ledger_slot > start_slot {
progress_bar.println(format!(
if minimum_ledger_slot > start_slot {
progress_bar.println(format!(
"{}",
style(format!(
"Note: Requested start slot was {} but minimum ledger slot is {}",
start_slot, minimum_ledger_slot
"Note: Requested start slot was {start_slot} but minimum ledger slot is {minimum_ledger_slot}"
))
.italic(),
));
start_slot = minimum_ledger_slot;
}
start_slot = minimum_ledger_slot;
}
let confirmed_blocks = rpc_client.get_blocks(start_slot, Some(end_slot))?;
(confirmed_blocks, start_slot)
};
let confirmed_blocks = rpc_client.get_blocks(start_slot, Some(end_slot))?;
(confirmed_blocks, start_slot)
};
let start_slot_index = (start_slot - first_slot_in_epoch) as usize;
let end_slot_index = (end_slot - first_slot_in_epoch) as usize;
@ -1259,11 +1250,11 @@ pub fn process_show_block_production(
let mut leader_slot_count = HashMap::new();
let mut leader_skipped_slots = HashMap::new();
progress_bar.set_message(format!("Fetching leader schedule for epoch {}...", epoch));
progress_bar.set_message(format!("Fetching leader schedule for epoch {epoch}..."));
let leader_schedule = rpc_client
.get_leader_schedule_with_commitment(Some(start_slot), CommitmentConfig::finalized())?;
if leader_schedule.is_none() {
return Err(format!("Unable to fetch leader schedule for slot {}", start_slot).into());
return Err(format!("Unable to fetch leader schedule for slot {start_slot}").into());
}
let leader_schedule = leader_schedule.unwrap();
@ -1279,8 +1270,7 @@ pub fn process_show_block_production(
}
progress_bar.set_message(format!(
"Processing {} slots containing {} blocks and {} empty slots...",
total_slots, total_blocks_produced, total_slots_skipped
"Processing {total_slots} slots containing {total_blocks_produced} blocks and {total_slots_skipped} empty slots..."
));
let mut confirmed_blocks_index = 0;
@ -1480,7 +1470,7 @@ pub fn process_ping(
sequence: seq,
lamports: Some(lamports),
};
eprint!("{}", cli_ping_data);
eprint!("{cli_ping_data}");
cli_pings.push(cli_ping_data);
confirmed_count += 1;
}
@ -1495,7 +1485,7 @@ pub fn process_ping(
sequence: seq,
lamports: None,
};
eprint!("{}", cli_ping_data);
eprint!("{cli_ping_data}");
cli_pings.push(cli_ping_data);
}
}
@ -1513,7 +1503,7 @@ pub fn process_ping(
sequence: seq,
lamports: None,
};
eprint!("{}", cli_ping_data);
eprint!("{cli_ping_data}");
cli_pings.push(cli_ping_data);
break;
}
@ -1538,7 +1528,7 @@ pub fn process_ping(
sequence: seq,
lamports: None,
};
eprint!("{}", cli_ping_data);
eprint!("{cli_ping_data}");
cli_pings.push(cli_ping_data);
}
}
@ -1637,11 +1627,11 @@ pub fn process_logs(config: &CliConfig, filter: &RpcTransactionLogsFilter) -> Pr
);
println!(" Log Messages:");
for log in logs.value.logs {
println!(" {}", log);
println!(" {log}");
}
}
Err(err) => {
return Ok(format!("Disconnected: {}", err));
return Ok(format!("Disconnected: {err}"));
}
}
}
@ -1666,7 +1656,7 @@ pub fn process_live_slots(config: &CliConfig) -> ProcessResult {
let mut slots_per_second = std::f64::NAN;
loop {
if exit.load(Ordering::Relaxed) {
eprintln!("{}", message);
eprintln!("{message}");
client.shutdown().unwrap();
break;
}
@ -1686,11 +1676,10 @@ pub fn process_live_slots(config: &CliConfig) -> ProcessResult {
}
message = if slots_per_second.is_nan() {
format!("{:?}", new_info)
format!("{new_info:?}")
} else {
format!(
"{:?} | root slot advancing at {:.2} slots/second",
new_info, slots_per_second
"{new_info:?} | root slot advancing at {slots_per_second:.2} slots/second"
)
};
slot_progress.set_message(message.clone());
@ -1723,7 +1712,7 @@ pub fn process_live_slots(config: &CliConfig) -> ProcessResult {
current = Some(new_info);
}
Err(err) => {
eprintln!("disconnected: {}", err);
eprintln!("disconnected: {err}");
break;
}
}
@ -2051,11 +2040,11 @@ pub fn process_transaction_history(
format!("timestamp={} ", unix_timestamp_to_string(block_time)),
},
if let Some(err) = result.err {
format!("Failed: {:?}", err)
format!("Failed: {err:?}")
} else {
match result.confirmation_status {
None => "Finalized".to_string(),
Some(status) => format!("{:?}", status),
Some(status) => format!("{status:?}"),
}
},
result.memo.unwrap_or_default(),
@ -2087,7 +2076,7 @@ pub fn process_transaction_history(
None,
);
}
Err(err) => println!(" Unable to get confirmed transaction details: {}", err),
Err(err) => println!(" Unable to get confirmed transaction details: {err}"),
}
}
println!();

View File

@ -142,7 +142,7 @@ impl fmt::Display for CliFeatures {
}
CliFeatureStatus::Active(activation_slot) => {
let activation_epoch = self.epoch_schedule.get_epoch(activation_slot);
style(format!("active since epoch {}", activation_epoch)).green()
style(format!("active since epoch {activation_epoch}")).green()
}
},
match feature.status {
@ -154,11 +154,11 @@ impl fmt::Display for CliFeatures {
}
if let Some(software_versions) = &self.cluster_software_versions {
write!(f, "{}", software_versions)?;
write!(f, "{software_versions}")?;
}
if let Some(feature_sets) = &self.cluster_feature_sets {
write!(f, "{}", feature_sets)?;
write!(f, "{feature_sets}")?;
}
if self.inactive && !self.feature_activation_allowed {
@ -233,13 +233,7 @@ impl fmt::Display for CliClusterSoftwareVersions {
f,
"{}",
style(format!(
"{1:<0$} {3:>2$} {5:>4$}",
max_software_version_len,
software_version_title,
max_stake_percent_len,
stake_percent_title,
max_rpc_percent_len,
rpc_percent_title,
"{software_version_title:<max_software_version_len$} {stake_percent_title:>max_stake_percent_len$} {rpc_percent_title:>max_rpc_percent_len$}",
))
.bold(),
)?;
@ -348,15 +342,7 @@ impl fmt::Display for CliClusterFeatureSets {
f,
"{}",
style(format!(
"{1:<0$} {3:<2$} {5:>4$} {7:>6$}",
max_software_versions_len,
software_versions_title,
max_feature_set_len,
feature_set_title,
max_stake_percent_len,
stake_percent_title,
max_rpc_percent_len,
rpc_percent_title,
"{software_versions_title:<max_software_versions_len$} {feature_set_title:<max_feature_set_len$} {stake_percent_title:>max_stake_percent_len$} {rpc_percent_title:>max_rpc_percent_len$}",
))
.bold(),
)?;
@ -454,8 +440,7 @@ fn known_feature(feature: &Pubkey) -> Result<(), CliError> {
Ok(())
} else {
Err(CliError::BadParameter(format!(
"Unknown feature: {}",
feature
"Unknown feature: {feature}"
)))
}
}
@ -867,7 +852,7 @@ fn process_activate(
if let Some(account) = account {
if feature::from_account(&account).is_some() {
return Err(format!("{} has already been activated", feature_id).into());
return Err(format!("{feature_id} has already been activated").into());
}
}

View File

@ -107,9 +107,9 @@ fn process_rewards(
.get_inflation_reward(addresses, rewards_epoch)
.map_err(|err| {
if let Some(epoch) = rewards_epoch {
format!("Rewards not available for epoch {}", epoch)
format!("Rewards not available for epoch {epoch}")
} else {
format!("Rewards not available {}", err)
format!("Rewards not available {err}")
}
})?;
let epoch_schedule = rpc_client.get_epoch_schedule()?;

View File

@ -63,7 +63,7 @@ fn parse_settings(matches: &ArgMatches<'_>) -> Result<bool, Box<dyn error::Error
),
_ => unreachable!(),
};
println_name_value_or(&format!("{}:", field_name), &value, setting_type);
println_name_value_or(&format!("{field_name}:"), &value, setting_type);
} else {
println_name_value("Config File:", config_file);
println_name_value_or("RPC URL:", &json_rpc_url, url_setting_type);
@ -123,12 +123,12 @@ fn parse_settings(matches: &ArgMatches<'_>) -> Result<bool, Box<dyn error::Error
let filename = value_t_or_exit!(subcommand_matches, "filename", PathBuf);
config.import_address_labels(&filename)?;
config.save(config_file)?;
println!("Address labels imported from {:?}", filename);
println!("Address labels imported from {filename:?}");
}
("export-address-labels", Some(subcommand_matches)) => {
let filename = value_t_or_exit!(subcommand_matches, "filename", PathBuf);
config.export_address_labels(&filename)?;
println!("Address labels exported to {:?}", filename);
println!("Address labels exported to {filename:?}");
}
_ => unreachable!(),
}
@ -247,7 +247,7 @@ fn do_main(matches: &ArgMatches<'_>) -> Result<(), Box<dyn error::Error>> {
let (mut config, signers) = parse_args(matches, &mut wallet_manager)?;
config.signers = signers.iter().map(|s| s.as_ref()).collect();
let result = process_command(&config)?;
println!("{}", result);
println!("{result}");
};
Ok(())
}

View File

@ -507,12 +507,9 @@ pub fn process_create_nonce_account(
if let Ok(nonce_account) = get_account(rpc_client, &nonce_account_address) {
let err_msg = if state_from_account(&nonce_account).is_ok() {
format!("Nonce account {} already exists", nonce_account_address)
format!("Nonce account {nonce_account_address} already exists")
} else {
format!(
"Account {} already exists and is not a nonce account",
nonce_account_address
)
format!("Account {nonce_account_address} already exists and is not a nonce account")
};
return Err(CliError::BadParameter(err_msg).into());
}
@ -520,8 +517,7 @@ pub fn process_create_nonce_account(
let minimum_balance = rpc_client.get_minimum_balance_for_rent_exemption(State::size())?;
if lamports < minimum_balance {
return Err(CliError::BadParameter(format!(
"need at least {} lamports for nonce account to be rent exempt, provided lamports: {}",
minimum_balance, lamports
"need at least {minimum_balance} lamports for nonce account to be rent exempt, provided lamports: {lamports}"
))
.into());
}
@ -593,8 +589,7 @@ pub fn process_new_nonce(
if let Err(err) = rpc_client.get_account(nonce_account) {
return Err(CliError::BadParameter(format!(
"Unable to advance nonce account {}. error: {}",
nonce_account, err
"Unable to advance nonce account {nonce_account}. error: {err}"
))
.into());
}

View File

@ -843,8 +843,7 @@ fn process_program_deploy(
{
if account.owner != bpf_loader_upgradeable::id() {
return Err(format!(
"Account {} is not an upgradeable program or already in use",
program_pubkey
"Account {program_pubkey} is not an upgradeable program or already in use"
)
.into());
}
@ -867,7 +866,7 @@ fn process_program_deploy(
{
if program_authority_pubkey.is_none() {
return Err(
format!("Program {} is no longer upgradeable", program_pubkey).into(),
format!("Program {program_pubkey} is no longer upgradeable").into()
);
}
if program_authority_pubkey != Some(upgrade_authority_signer.pubkey()) {
@ -882,20 +881,18 @@ fn process_program_deploy(
false
} else {
return Err(format!(
"Program {} has been closed, use a new Program Id",
program_pubkey
"Program {program_pubkey} has been closed, use a new Program Id"
)
.into());
}
} else {
return Err(format!(
"Program {} has been closed, use a new Program Id",
program_pubkey
"Program {program_pubkey} has been closed, use a new Program Id"
)
.into());
}
} else {
return Err(format!("{} is not an upgradeable program", program_pubkey).into());
return Err(format!("{program_pubkey} is not an upgradeable program").into());
}
} else {
// do new deploy
@ -1056,7 +1053,7 @@ fn process_write_buffer(
{
if let Ok(UpgradeableLoaderState::Buffer { authority_address }) = account.state() {
if authority_address.is_none() {
return Err(format!("Buffer {} is immutable", buffer_pubkey).into());
return Err(format!("Buffer {buffer_pubkey} is immutable").into());
}
if authority_address != Some(buffer_authority.pubkey()) {
return Err(format!(
@ -1067,11 +1064,9 @@ fn process_write_buffer(
.into());
}
} else {
return Err(format!(
"{} is not an upgradeable loader buffer account",
buffer_pubkey
)
.into());
return Err(
format!("{buffer_pubkey} is not an upgradeable loader buffer account").into(),
);
}
}
@ -1161,7 +1156,7 @@ fn process_set_authority(
..RpcSendTransactionConfig::default()
},
)
.map_err(|e| format!("Setting authority failed: {}", e))?;
.map_err(|e| format!("Setting authority failed: {e}"))?;
let authority = CliProgramAuthority {
authority: new_authority
@ -1220,7 +1215,7 @@ fn get_buffers(
use_lamports_unit,
});
} else {
return Err(format!("Error parsing Buffer account {}", address).into());
return Err(format!("Error parsing Buffer account {address}").into());
}
}
Ok(CliUpgradeableBuffers {
@ -1269,8 +1264,7 @@ fn get_programs(
let results = get_accounts_with_filter(rpc_client, filters, 0)?;
if results.len() != 1 {
return Err(format!(
"Error: More than one Program associated with ProgramData account {}",
programdata_address
"Error: More than one Program associated with ProgramData account {programdata_address}"
)
.into());
}
@ -1288,9 +1282,7 @@ fn get_programs(
use_lamports_unit,
});
} else {
return Err(
format!("Error parsing ProgramData account {}", programdata_address).into(),
);
return Err(format!("Error parsing ProgramData account {programdata_address}").into());
}
}
Ok(CliUpgradeablePrograms {
@ -1370,10 +1362,10 @@ fn process_show(
use_lamports_unit,
}))
} else {
Err(format!("Program {} has been closed", account_pubkey).into())
Err(format!("Program {account_pubkey} has been closed").into())
}
} else {
Err(format!("Program {} has been closed", account_pubkey).into())
Err(format!("Program {account_pubkey} has been closed").into())
}
} else if let Ok(UpgradeableLoaderState::Buffer { authority_address }) =
account.state()
@ -1392,16 +1384,15 @@ fn process_show(
}))
} else {
Err(format!(
"{} is not an upgradeable loader Buffer or Program account",
account_pubkey
"{account_pubkey} is not an upgradeable loader Buffer or Program account"
)
.into())
}
} else {
Err(format!("{} is not an SBF program", account_pubkey).into())
Err(format!("{account_pubkey} is not an SBF program").into())
}
} else {
Err(format!("Unable to find the account {}", account_pubkey).into())
Err(format!("Unable to find the account {account_pubkey}").into())
}
} else if programs {
let authority_pubkey = if all { None } else { Some(authority_pubkey) };
@ -1430,7 +1421,7 @@ fn process_dump(
if account.owner == bpf_loader::id() || account.owner == bpf_loader_deprecated::id() {
let mut f = File::create(output_location)?;
f.write_all(&account.data)?;
Ok(format!("Wrote program to {}", output_location))
Ok(format!("Wrote program to {output_location}"))
} else if account.owner == bpf_loader_upgradeable::id() {
if let Ok(UpgradeableLoaderState::Program {
programdata_address,
@ -1447,31 +1438,30 @@ fn process_dump(
let program_data = &programdata_account.data[offset..];
let mut f = File::create(output_location)?;
f.write_all(program_data)?;
Ok(format!("Wrote program to {}", output_location))
Ok(format!("Wrote program to {output_location}"))
} else {
Err(format!("Program {} has been closed", account_pubkey).into())
Err(format!("Program {account_pubkey} has been closed").into())
}
} else {
Err(format!("Program {} has been closed", account_pubkey).into())
Err(format!("Program {account_pubkey} has been closed").into())
}
} else if let Ok(UpgradeableLoaderState::Buffer { .. }) = account.state() {
let offset = UpgradeableLoaderState::size_of_buffer_metadata();
let program_data = &account.data[offset..];
let mut f = File::create(output_location)?;
f.write_all(program_data)?;
Ok(format!("Wrote program to {}", output_location))
Ok(format!("Wrote program to {output_location}"))
} else {
Err(format!(
"{} is not an upgradeable loader buffer or program account",
account_pubkey
"{account_pubkey} is not an upgradeable loader buffer or program account"
)
.into())
}
} else {
Err(format!("{} is not an SBF program", account_pubkey).into())
Err(format!("{account_pubkey} is not an SBF program").into())
}
} else {
Err(format!("Unable to find the account {}", account_pubkey).into())
Err(format!("Unable to find the account {account_pubkey}").into())
}
} else {
Err("No account specified".into())
@ -1522,7 +1512,7 @@ fn close(
{
return Err("Closing a program account is not supported by the cluster".into());
} else {
return Err(format!("Close failed: {}", err).into());
return Err(format!("Close failed: {err}").into());
}
}
Ok(())
@ -1618,16 +1608,16 @@ fn process_close(
))
}
} else {
Err(format!("Program {} has been closed", account_pubkey).into())
Err(format!("Program {account_pubkey} has been closed").into())
}
} else {
Err(format!("Program {} has been closed", account_pubkey).into())
Err(format!("Program {account_pubkey} has been closed").into())
}
}
_ => Err(format!("{} is not a Program or Buffer account", account_pubkey).into()),
_ => Err(format!("{account_pubkey} is not a Program or Buffer account").into()),
}
} else {
Err(format!("Unable to find the account {}", account_pubkey).into())
Err(format!("Unable to find the account {account_pubkey}").into())
}
} else {
let buffers = get_buffers(
@ -1996,10 +1986,10 @@ fn do_process_program_upgrade(
fn read_and_verify_elf(program_location: &str) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
let mut file = File::open(program_location)
.map_err(|err| format!("Unable to open program file: {}", err))?;
.map_err(|err| format!("Unable to open program file: {err}"))?;
let mut program_data = Vec::new();
file.read_to_end(&mut program_data)
.map_err(|err| format!("Unable to read program file: {}", err))?;
.map_err(|err| format!("Unable to read program file: {err}"))?;
let mut transaction_context = TransactionContext::new(Vec::new(), Some(Rent::default()), 1, 1);
let invoke_context = InvokeContext::new_mock(&mut transaction_context, &[]);
@ -2012,10 +2002,10 @@ fn read_and_verify_elf(program_location: &str) -> Result<Vec<u8>, Box<dyn std::e
},
register_syscalls(&invoke_context.feature_set, true).unwrap(),
)
.map_err(|err| format!("ELF error: {}", err))?;
.map_err(|err| format!("ELF error: {err}"))?;
let _ = VerifiedExecutable::<RequisiteVerifier, InvokeContext>::from_executable(executable)
.map_err(|err| format!("ELF error: {}", err))?;
.map_err(|err| format!("ELF error: {err}"))?;
Ok(program_data)
}
@ -2132,7 +2122,7 @@ fn send_deploy_messages(
}
let result = rpc_client.send_and_confirm_transaction_with_spinner(&initial_transaction);
log_instruction_custom_error::<SystemError>(result, config)
.map_err(|err| format!("Account allocation failed: {}", err))?;
.map_err(|err| format!("Account allocation failed: {err}"))?;
} else {
return Err("Buffer account not created yet, must provide a key pair".into());
}
@ -2157,7 +2147,7 @@ fn send_deploy_messages(
write_messages,
&[payer_signer, write_signer],
)
.map_err(|err| format!("Data writes to account failed: {}", err))?
.map_err(|err| format!("Data writes to account failed: {err}"))?
.into_iter()
.flatten()
.collect::<Vec<_>>();
@ -2192,7 +2182,7 @@ fn send_deploy_messages(
..RpcSendTransactionConfig::default()
},
)
.map_err(|e| format!("Deploying program failed: {}", e))?;
.map_err(|e| format!("Deploying program failed: {e}"))?;
}
}
@ -2212,22 +2202,13 @@ fn create_ephemeral_keypair(
fn report_ephemeral_mnemonic(words: usize, mnemonic: bip39::Mnemonic) {
let phrase: &str = mnemonic.phrase();
let divider = String::from_utf8(vec![b'='; phrase.len()]).unwrap();
eprintln!(
"{}\nRecover the intermediate account's ephemeral keypair file with",
divider
);
eprintln!(
"`solana-keygen recover` and the following {}-word seed phrase:",
words
);
eprintln!("{}\n{}\n{}", divider, phrase, divider);
eprintln!("{divider}\nRecover the intermediate account's ephemeral keypair file with");
eprintln!("`solana-keygen recover` and the following {words}-word seed phrase:");
eprintln!("{divider}\n{phrase}\n{divider}");
eprintln!("To resume a deploy, pass the recovered keypair as the");
eprintln!("[BUFFER_SIGNER] to `solana program deploy` or `solana program write-buffer'.");
eprintln!("Or to recover the account's lamports, pass it as the");
eprintln!(
"[BUFFER_ACCOUNT_ADDRESS] argument to `solana program close`.\n{}",
divider
);
eprintln!("[BUFFER_ACCOUNT_ADDRESS] argument to `solana program close`.\n{divider}");
}
#[cfg(test)]

View File

@ -1400,12 +1400,9 @@ pub fn process_create_stake_account(
if !sign_only {
if let Ok(stake_account) = rpc_client.get_account(&stake_account_address) {
let err_msg = if stake_account.owner == stake::program::id() {
format!("Stake account {} already exists", stake_account_address)
format!("Stake account {stake_account_address} already exists")
} else {
format!(
"Account {} already exists and is not a stake account",
stake_account_address
)
format!("Account {stake_account_address} already exists and is not a stake account")
};
return Err(CliError::BadParameter(err_msg).into());
}
@ -1415,8 +1412,7 @@ pub fn process_create_stake_account(
if lamports < minimum_balance {
return Err(CliError::BadParameter(format!(
"need at least {} lamports for stake account to be rent exempt, provided lamports: {}",
minimum_balance, lamports
"need at least {minimum_balance} lamports for stake account to be rent exempt, provided lamports: {lamports}"
))
.into());
}
@ -1506,8 +1502,7 @@ pub fn process_stake_authorize(
}
} else {
return Err(CliError::RpcRequestError(format!(
"{:?} is not an Initialized or Delegated stake account",
stake_account_pubkey,
"{stake_account_pubkey:?} is not an Initialized or Delegated stake account",
))
.into());
}
@ -1614,8 +1609,7 @@ pub fn process_deactivate_stake_account(
let stake_account = rpc_client.get_account(&stake_account_address)?;
if stake_account.owner != stake::program::id() {
return Err(CliError::BadParameter(format!(
"{} is not a stake account",
stake_account_address,
"{stake_account_address} is not a stake account",
))
.into());
}
@ -1625,16 +1619,14 @@ pub fn process_deactivate_stake_account(
StakeState::Stake(_, stake) => stake.delegation.voter_pubkey,
_ => {
return Err(CliError::BadParameter(format!(
"{} is not a delegated stake account",
stake_account_address,
"{stake_account_address} is not a delegated stake account",
))
.into())
}
},
Err(err) => {
return Err(CliError::RpcRequestError(format!(
"Account data could not be deserialized to stake state: {}",
err
"Account data could not be deserialized to stake state: {err}"
))
.into())
}
@ -1879,14 +1871,10 @@ pub fn process_split_stake(
if !sign_only {
if let Ok(stake_account) = rpc_client.get_account(&split_stake_account_address) {
let err_msg = if stake_account.owner == stake::program::id() {
format!(
"Stake account {} already exists",
split_stake_account_address
)
format!("Stake account {split_stake_account_address} already exists")
} else {
format!(
"Account {} already exists and is not a stake account",
split_stake_account_address
"Account {split_stake_account_address} already exists and is not a stake account"
)
};
return Err(CliError::BadParameter(err_msg).into());
@ -1897,8 +1885,7 @@ pub fn process_split_stake(
if lamports < minimum_balance {
return Err(CliError::BadParameter(format!(
"need at least {} lamports for stake account to be rent exempt, provided lamports: {}",
minimum_balance, lamports
"need at least {minimum_balance} lamports for stake account to be rent exempt, provided lamports: {lamports}"
))
.into());
}
@ -2016,8 +2003,7 @@ pub fn process_merge_stake(
if let Ok(stake_account) = rpc_client.get_account(stake_account_address) {
if stake_account.owner != stake::program::id() {
return Err(CliError::BadParameter(format!(
"Account {} is not a stake account",
stake_account_address
"Account {stake_account_address} is not a stake account"
))
.into());
}
@ -2126,8 +2112,7 @@ pub fn process_stake_set_lockup(
}
} else {
return Err(CliError::RpcRequestError(format!(
"{:?} is not an Initialized or Delegated stake account",
stake_account_pubkey,
"{stake_account_pubkey:?} is not an Initialized or Delegated stake account",
))
.into());
}
@ -2287,19 +2272,17 @@ fn get_stake_account_state(
.get_account_with_commitment(stake_account_pubkey, commitment_config)?
.value
.ok_or_else(|| {
CliError::RpcRequestError(format!("{:?} account does not exist", stake_account_pubkey))
CliError::RpcRequestError(format!("{stake_account_pubkey:?} account does not exist"))
})?;
if stake_account.owner != stake::program::id() {
return Err(CliError::RpcRequestError(format!(
"{:?} is not a stake account",
stake_account_pubkey,
"{stake_account_pubkey:?} is not a stake account",
))
.into());
}
stake_account.state().map_err(|err| {
CliError::RpcRequestError(format!(
"Account data could not be deserialized to stake state: {}",
err
"Account data could not be deserialized to stake state: {err}"
))
.into()
})
@ -2311,8 +2294,7 @@ pub(crate) fn check_current_authority(
) -> Result<(), CliError> {
if !permitted_authorities.contains(provided_current_authority) {
Err(CliError::RpcRequestError(format!(
"Invalid authority provided: {:?}, expected {:?}",
provided_current_authority, permitted_authorities
"Invalid authority provided: {provided_current_authority:?}, expected {permitted_authorities:?}"
)))
} else {
Ok(())
@ -2396,7 +2378,7 @@ pub(crate) fn fetch_epoch_rewards(
if let Ok(rewards) = rpc_client.get_inflation_reward(&[*address], Some(rewards_epoch)) {
process_reward(&rewards[0])?;
} else {
eprintln!("Rewards not available for epoch {}", rewards_epoch);
eprintln!("Rewards not available for epoch {rewards_epoch}");
}
num_epochs = num_epochs.saturating_sub(1);
}
@ -2414,8 +2396,7 @@ pub fn process_show_stake_account(
let stake_account = rpc_client.get_account(stake_account_address)?;
if stake_account.owner != stake::program::id() {
return Err(CliError::RpcRequestError(format!(
"{:?} is not a stake account",
stake_account_address,
"{stake_account_address:?} is not a stake account",
))
.into());
}
@ -2443,7 +2424,7 @@ pub fn process_show_stake_account(
match fetch_epoch_rewards(rpc_client, stake_account_address, num_epochs) {
Ok(rewards) => Some(rewards),
Err(error) => {
eprintln!("Failed to fetch epoch rewards: {:?}", error);
eprintln!("Failed to fetch epoch rewards: {error:?}");
None
}
}
@ -2453,8 +2434,7 @@ pub fn process_show_stake_account(
Ok(config.output_format.formatted_string(&state))
}
Err(err) => Err(CliError::RpcRequestError(format!(
"Account data could not be deserialized to stake state: {}",
err
"Account data could not be deserialized to stake state: {err}"
))
.into()),
}
@ -2540,8 +2520,7 @@ pub fn process_delegate_stake(
.get_account(vote_account_pubkey)
.map_err(|err| {
CliError::RpcRequestError(format!(
"Vote account not found: {}. error: {}",
vote_account_pubkey, err,
"Vote account not found: {vote_account_pubkey}. error: {err}",
))
})?
.data;
@ -2563,8 +2542,7 @@ pub fn process_delegate_stake(
if root_slot < min_root_slot {
Err(CliError::DynamicProgramError(format!(
"Unable to delegate. Vote account appears delinquent \
because its current root slot, {}, is less than {}",
root_slot, min_root_slot
because its current root slot, {root_slot}, is less than {min_root_slot}"
)))
} else {
Ok(())
@ -2576,7 +2554,7 @@ pub fn process_delegate_stake(
if !force {
sanity_check_result?;
} else {
println!("--force supplied, ignoring: {}", err);
println!("--force supplied, ignoring: {err}");
}
}
}
@ -3469,7 +3447,7 @@ mod tests {
// Test Authorize Subcommand w/ sign-only
let blockhash = Hash::default();
let blockhash_string = format!("{}", blockhash);
let blockhash_string = format!("{blockhash}");
let test_authorize = test_commands.clone().get_matches_from(vec![
"test",
"stake-authorize",
@ -3744,7 +3722,7 @@ mod tests {
);
// Test Authorize Subcommand w/ absentee fee-payer
let sig = fee_payer_keypair.sign_message(&[0u8]);
let signer = format!("{}={}", fee_payer_string, sig);
let signer = format!("{fee_payer_string}={sig}");
let test_authorize = test_commands.clone().get_matches_from(vec![
"test",
"stake-authorize",
@ -3792,9 +3770,9 @@ mod tests {
// Test CreateStakeAccount SubCommand
let custodian = solana_sdk::pubkey::new_rand();
let custodian_string = format!("{}", custodian);
let custodian_string = format!("{custodian}");
let authorized = solana_sdk::pubkey::new_rand();
let authorized_string = format!("{}", authorized);
let authorized_string = format!("{authorized}");
let test_create_stake_account = test_commands.clone().get_matches_from(vec![
"test",
"create-stake-account",
@ -3942,7 +3920,7 @@ mod tests {
let offline_pubkey = offline.pubkey();
let offline_string = offline_pubkey.to_string();
let offline_sig = offline.sign_message(&[3u8]);
let offline_signer = format!("{}={}", offline_pubkey, offline_sig);
let offline_signer = format!("{offline_pubkey}={offline_sig}");
let nonce_hash = Hash::new(&[4u8; 32]);
let nonce_hash_string = nonce_hash.to_string();
let test_create_stake_account2 = test_commands.clone().get_matches_from(vec![
@ -4096,7 +4074,7 @@ mod tests {
// Test Delegate Subcommand w/ Blockhash
let blockhash = Hash::default();
let blockhash_string = format!("{}", blockhash);
let blockhash_string = format!("{blockhash}");
let test_delegate_stake = test_commands.clone().get_matches_from(vec![
"test",
"delegate-stake",
@ -4164,7 +4142,7 @@ mod tests {
// Test Delegate Subcommand w/ absent fee payer
let key1 = solana_sdk::pubkey::new_rand();
let sig1 = Keypair::new().sign_message(&[0u8]);
let signer1 = format!("{}={}", key1, sig1);
let signer1 = format!("{key1}={sig1}");
let test_delegate_stake = test_commands.clone().get_matches_from(vec![
"test",
"delegate-stake",
@ -4208,7 +4186,7 @@ mod tests {
// Test Delegate Subcommand w/ absent fee payer and absent nonce authority
let key2 = solana_sdk::pubkey::new_rand();
let sig2 = Keypair::new().sign_message(&[0u8]);
let signer2 = format!("{}={}", key2, sig2);
let signer2 = format!("{key2}={sig2}");
let test_delegate_stake = test_commands.clone().get_matches_from(vec![
"test",
"delegate-stake",
@ -4624,7 +4602,7 @@ mod tests {
// Test Deactivate Subcommand w/ Blockhash
let blockhash = Hash::default();
let blockhash_string = format!("{}", blockhash);
let blockhash_string = format!("{blockhash}");
let test_deactivate_stake = test_commands.clone().get_matches_from(vec![
"test",
"deactivate-stake",
@ -4688,7 +4666,7 @@ mod tests {
// Test Deactivate Subcommand w/ absent fee payer
let key1 = solana_sdk::pubkey::new_rand();
let sig1 = Keypair::new().sign_message(&[0u8]);
let signer1 = format!("{}={}", key1, sig1);
let signer1 = format!("{key1}={sig1}");
let test_deactivate_stake = test_commands.clone().get_matches_from(vec![
"test",
"deactivate-stake",
@ -4730,7 +4708,7 @@ mod tests {
// Test Deactivate Subcommand w/ absent fee payer and nonce authority
let key2 = solana_sdk::pubkey::new_rand();
let sig2 = Keypair::new().sign_message(&[0u8]);
let signer2 = format!("{}={}", key2, sig2);
let signer2 = format!("{key2}={sig2}");
let test_deactivate_stake = test_commands.clone().get_matches_from(vec![
"test",
"deactivate-stake",
@ -4857,12 +4835,12 @@ mod tests {
let nonce_auth_pubkey = nonce_auth.pubkey();
let nonce_auth_string = nonce_auth_pubkey.to_string();
let nonce_sig = nonce_auth.sign_message(&[0u8]);
let nonce_signer = format!("{}={}", nonce_auth_pubkey, nonce_sig);
let nonce_signer = format!("{nonce_auth_pubkey}={nonce_sig}");
let stake_auth = keypair_from_seed(&[3u8; 32]).unwrap();
let stake_auth_pubkey = stake_auth.pubkey();
let stake_auth_string = stake_auth_pubkey.to_string();
let stake_sig = stake_auth.sign_message(&[0u8]);
let stake_signer = format!("{}={}", stake_auth_pubkey, stake_sig);
let stake_signer = format!("{stake_auth_pubkey}={stake_sig}");
let nonce_hash = Hash::new(&[4u8; 32]);
let nonce_hash_string = nonce_hash.to_string();

View File

@ -33,8 +33,7 @@ use {
pub fn check_details_length(string: String) -> Result<(), String> {
if string.len() > MAX_LONG_FIELD_LENGTH {
Err(format!(
"validator details longer than {:?}-byte limit",
MAX_LONG_FIELD_LENGTH
"validator details longer than {MAX_LONG_FIELD_LENGTH:?}-byte limit"
))
} else {
Ok(())
@ -46,8 +45,7 @@ pub fn check_url(string: String) -> Result<(), String> {
is_url(string.clone())?;
if string.len() > MAX_SHORT_FIELD_LENGTH {
Err(format!(
"url longer than {:?}-byte limit",
MAX_SHORT_FIELD_LENGTH
"url longer than {MAX_SHORT_FIELD_LENGTH:?}-byte limit"
))
} else {
Ok(())
@ -58,8 +56,7 @@ pub fn check_url(string: String) -> Result<(), String> {
pub fn is_short_field(string: String) -> Result<(), String> {
if string.len() > MAX_SHORT_FIELD_LENGTH {
Err(format!(
"validator field longer than {:?}-byte limit",
MAX_SHORT_FIELD_LENGTH
"validator field longer than {MAX_SHORT_FIELD_LENGTH:?}-byte limit"
))
} else {
Ok(())
@ -71,22 +68,16 @@ fn verify_keybase(
keybase_username: &Value,
) -> Result<(), Box<dyn error::Error>> {
if let Some(keybase_username) = keybase_username.as_str() {
let url = format!(
"https://keybase.pub/{}/solana/validator-{:?}",
keybase_username, validator_pubkey
);
let url =
format!("https://keybase.pub/{keybase_username}/solana/validator-{validator_pubkey:?}");
let client = Client::new();
if client.head(&url).send()?.status().is_success() {
Ok(())
} else {
Err(format!("keybase_username could not be confirmed at: {}. Please add this pubkey file to your keybase profile to connect", url).into())
Err(format!("keybase_username could not be confirmed at: {url}. Please add this pubkey file to your keybase profile to connect").into())
}
} else {
Err(format!(
"keybase_username could not be parsed as String: {}",
keybase_username
)
.into())
Err(format!("keybase_username could not be parsed as String: {keybase_username}").into())
}
}
@ -116,7 +107,7 @@ fn parse_validator_info(
account: &Account,
) -> Result<(Pubkey, Map<String, serde_json::value::Value>), Box<dyn error::Error>> {
if account.owner != solana_config_program::id() {
return Err(format!("{} is not a validator info account", pubkey).into());
return Err(format!("{pubkey} is not a validator info account").into());
}
let key_list: ConfigKeys = deserialize(&account.data)?;
if !key_list.keys.is_empty() {
@ -125,7 +116,7 @@ fn parse_validator_info(
let validator_info: Map<_, _> = serde_json::from_str(&validator_info_string)?;
Ok((validator_pubkey, validator_info))
} else {
Err(format!("{} could not be parsed as a validator info account", pubkey).into())
Err(format!("{pubkey} could not be parsed as a validator info account").into())
}
}
@ -251,10 +242,10 @@ pub fn process_set_validator_info(
let result = verify_keybase(&config.signers[0].pubkey(), string);
if result.is_err() {
if force_keybase {
println!("--force supplied, ignoring: {:?}", result);
println!("--force supplied, ignoring: {result:?}");
} else {
result.map_err(|err| {
CliError::BadParameter(format!("Invalid validator keybase username: {}", err))
CliError::BadParameter(format!("Invalid validator keybase username: {err}"))
})?;
}
}
@ -300,10 +291,7 @@ pub fn process_set_validator_info(
let signers = if balance == 0 {
if info_pubkey != info_keypair.pubkey() {
println!(
"Account {:?} does not exist. Generating new keypair...",
info_pubkey
);
println!("Account {info_pubkey:?} does not exist. Generating new keypair...");
info_pubkey = info_keypair.pubkey();
}
vec![config.signers[0], &info_keypair]
@ -362,8 +350,8 @@ pub fn process_set_validator_info(
tx.try_sign(&signers, latest_blockhash)?;
let signature_str = rpc_client.send_and_confirm_transaction_with_spinner(&tx)?;
println!("Success! Validator info published at: {:?}", info_pubkey);
println!("{}", signature_str);
println!("Success! Validator info published at: {info_pubkey:?}");
println!("{signature_str}");
Ok("".to_string())
}
@ -428,8 +416,7 @@ mod tests {
assert_eq!(
check_details_length(long_details),
Err(format!(
"validator details longer than {:?}-byte limit",
MAX_LONG_FIELD_LENGTH
"validator details longer than {MAX_LONG_FIELD_LENGTH:?}-byte limit"
))
);
}

View File

@ -860,11 +860,10 @@ pub fn process_create_vote_account(
{
if let Some(vote_account) = response.value {
let err_msg = if vote_account.owner == solana_vote_program::id() {
format!("Vote account {} already exists", vote_account_address)
format!("Vote account {vote_account_address} already exists")
} else {
format!(
"Account {} already exists and is not a vote account",
vote_account_address
"Account {vote_account_address} already exists and is not a vote account"
)
};
return Err(CliError::BadParameter(err_msg).into());
@ -943,8 +942,7 @@ pub fn process_vote_authorize(
if let Some(signer) = new_authorized_signer {
if signer.is_interactive() {
return Err(CliError::BadParameter(format!(
"invalid new authorized vote signer {:?}. Interactive vote signers not supported",
new_authorized_pubkey
"invalid new authorized vote signer {new_authorized_pubkey:?}. Interactive vote signers not supported"
)).into());
}
}
@ -1181,13 +1179,12 @@ pub(crate) fn get_vote_account(
.get_account_with_commitment(vote_account_pubkey, commitment_config)?
.value
.ok_or_else(|| {
CliError::RpcRequestError(format!("{:?} account does not exist", vote_account_pubkey))
CliError::RpcRequestError(format!("{vote_account_pubkey:?} account does not exist"))
})?;
if vote_account.owner != solana_vote_program::id() {
return Err(CliError::RpcRequestError(format!(
"{:?} is not a vote account",
vote_account_pubkey
"{vote_account_pubkey:?} is not a vote account"
))
.into());
}
@ -1236,7 +1233,7 @@ pub fn process_show_vote_account(
match crate::stake::fetch_epoch_rewards(rpc_client, vote_account_address, num_epochs) {
Ok(rewards) => Some(rewards),
Err(error) => {
eprintln!("Failed to fetch epoch rewards: {:?}", error);
eprintln!("Failed to fetch epoch rewards: {error:?}");
None
}
}
@ -1387,8 +1384,7 @@ pub fn process_close_vote_account(
{
if vote_account.activated_stake != 0 {
return Err(format!(
"Cannot close a vote account with active stake: {}",
vote_account_pubkey
"Cannot close a vote account with active stake: {vote_account_pubkey}"
)
.into());
}
@ -1459,7 +1455,7 @@ mod tests {
let default_signer = DefaultSigner::new("", &default_keypair_file);
let blockhash = Hash::default();
let blockhash_string = format!("{}", blockhash);
let blockhash_string = format!("{blockhash}");
let nonce_account = Pubkey::new_unique();
// Test VoteAuthorize SubCommand

View File

@ -579,7 +579,7 @@ pub fn process_show_account(
let mut f = File::create(output_file)?;
f.write_all(account_string.as_bytes())?;
writeln!(&mut account_string)?;
writeln!(&mut account_string, "Wrote account to {}", output_file)?;
writeln!(&mut account_string, "Wrote account to {output_file}")?;
}
}
OutputFormat::Display | OutputFormat::DisplayVerbose => {
@ -587,7 +587,7 @@ pub fn process_show_account(
let mut f = File::create(output_file)?;
f.write_all(&data)?;
writeln!(&mut account_string)?;
writeln!(&mut account_string, "Wrote account data to {}", output_file)?;
writeln!(&mut account_string, "Wrote account data to {output_file}")?;
} else if !data.is_empty() {
use pretty_hex::*;
writeln!(&mut account_string, "{:?}", data.hex_dump())?;
@ -620,13 +620,13 @@ pub fn process_airdrop(
let result = request_and_confirm_airdrop(rpc_client, config, &pubkey, lamports);
if let Ok(signature) = result {
let signature_cli_message = log_instruction_custom_error::<SystemError>(result, config)?;
println!("{}", signature_cli_message);
println!("{signature_cli_message}");
let current_balance = rpc_client.get_balance(&pubkey)?;
if current_balance < pre_balance.saturating_add(lamports) {
println!("Balance unchanged");
println!("Run `solana confirm -v {:?}` for more info", signature);
println!("Run `solana confirm -v {signature:?}` for more info");
Ok("".to_string())
} else {
Ok(build_balance_message(current_balance, false, true))
@ -701,7 +701,7 @@ pub fn process_confirm(
});
}
Err(err) => {
get_transaction_error = Some(format!("{:?}", err));
get_transaction_error = Some(format!("{err:?}"));
}
}
}
@ -721,7 +721,7 @@ pub fn process_confirm(
};
Ok(config.output_format.formatted_string(&cli_transaction))
}
Err(err) => Err(CliError::RpcRequestError(format!("Unable to confirm: {}", err)).into()),
Err(err) => Err(CliError::RpcRequestError(format!("Unable to confirm: {err}")).into()),
}
}
@ -789,10 +789,9 @@ pub fn process_transfer(
.value;
if recipient_balance == 0 {
return Err(format!(
"The recipient address ({}) is not funded. \
"The recipient address ({to}) is not funded. \
Add `--allow-unfunded-recipient` to complete the transfer \
",
to
"
)
.into());
}

View File

@ -148,7 +148,7 @@ fn test_cli_program_deploy_non_upgradeable() {
"Program {} is no longer upgradeable",
custom_address_keypair.pubkey()
),
format!("{}", err)
format!("{err}")
);
// Attempt to deploy to account with excess balance
@ -178,7 +178,7 @@ fn test_cli_program_deploy_non_upgradeable() {
"Account {} is not an upgradeable program or already in use",
custom_address_keypair.pubkey()
),
format!("{}", err)
format!("{err}")
);
// Use forcing parameter to deploy to account with excess balance

View File

@ -466,7 +466,7 @@ mod tests {
let c = rng.gen_range(1, 255);
let d = rng.gen_range(1, 255);
let addr_str = format!("{}.{}.{}.{}:80", a, b, c, d);
let addr_str = format!("{a}.{b}.{c}.{d}:80");
addr_str.parse().expect("Invalid address")
}

View File

@ -259,10 +259,7 @@ impl TpuClient {
total_transactions,
Some(block_height),
last_valid_block_height,
&format!(
"Waiting for next block, {} transactions pending...",
num_transactions
),
&format!("Waiting for next block, {num_transactions} transactions pending..."),
);
let mut new_block_height = block_height;
while block_height == new_block_height && block_height_refreshes > 0 {
@ -291,10 +288,8 @@ impl TpuClient {
if let Some((i, _)) = pending_transactions.remove(signature) {
confirmed_transactions += 1;
if status.err.is_some() {
progress_bar.println(format!(
"Failed transaction: {:?}",
status
));
progress_bar
.println(format!("Failed transaction: {status:?}"));
}
transaction_errors[i] = status.err;
}
@ -319,8 +314,7 @@ impl TpuClient {
transactions = pending_transactions.into_values().collect();
progress_bar.println(format!(
"Blockhash expired. {} retries remaining",
expired_blockhash_retries
"Blockhash expired. {expired_blockhash_retries} retries remaining"
));
expired_blockhash_retries -= 1;
}

View File

@ -169,7 +169,7 @@ impl ThinClient {
}
Err(io::Error::new(
io::ErrorKind::Other,
format!("retry_transfer failed in {} retries", tries),
format!("retry_transfer failed in {tries} retries"),
)
.into())
}
@ -377,7 +377,7 @@ impl SyncClient for ThinClient {
.map_err(|err| {
io::Error::new(
io::ErrorKind::Other,
format!("send_transaction failed with error {:?}", err),
format!("send_transaction failed with error {err:?}"),
)
})?;
Ok(status)
@ -394,7 +394,7 @@ impl SyncClient for ThinClient {
.map_err(|err| {
io::Error::new(
io::ErrorKind::Other,
format!("send_transaction failed with error {:?}", err),
format!("send_transaction failed with error {err:?}"),
)
})?;
Ok(status)
@ -414,7 +414,7 @@ impl SyncClient for ThinClient {
.map_err(|err| {
io::Error::new(
io::ErrorKind::Other,
format!("send_transaction failed with error {:?}", err),
format!("send_transaction failed with error {err:?}"),
)
})?;
Ok(slot)

View File

@ -490,7 +490,7 @@ impl BankingStage {
let connection_cache = connection_cache.clone();
let bank_forks = bank_forks.clone();
Builder::new()
.name(format!("solBanknStgTx{:02}", i))
.name(format!("solBanknStgTx{i:02}"))
.spawn(move || {
Self::process_loop(
&mut packet_deserializer,
@ -1151,7 +1151,7 @@ impl BankingStage {
starting_transaction_index: None,
};
}
Err(e) => panic!("Poh recorder returned unexpected error: {:?}", e),
Err(e) => panic!("Poh recorder returned unexpected error: {e:?}"),
}
}
@ -3903,7 +3903,7 @@ mod tests {
let mut packets = vec![Packet::default(); 2];
let num_received = recv_mmsg(recv_socket, &mut packets[..]).unwrap_or_default();
assert_eq!(num_received, expected_num_forwarded, "{}", name);
assert_eq!(num_received, expected_num_forwarded, "{name}");
}
exit.store(true, Ordering::Relaxed);
@ -4003,7 +4003,7 @@ mod tests {
let mut packets = vec![Packet::default(); 2];
let num_received = recv_mmsg(recv_socket, &mut packets[..]).unwrap_or_default();
assert_eq!(num_received, expected_ids.len(), "{}", name);
assert_eq!(num_received, expected_ids.len(), "{name}");
for (i, expected_id) in expected_ids.iter().enumerate() {
assert_eq!(packets[i].meta().size, 215);
let recv_transaction: VersionedTransaction =
@ -4011,17 +4011,12 @@ mod tests {
assert_eq!(
recv_transaction.message.recent_blockhash(),
expected_id,
"{}",
name
"{name}"
);
}
let num_unprocessed_packets: usize = unprocessed_packet_batches.len();
assert_eq!(
num_unprocessed_packets, expected_num_unprocessed,
"{}",
name
);
assert_eq!(num_unprocessed_packets, expected_num_unprocessed, "{name}");
}
exit.store(true, Ordering::Relaxed);

View File

@ -292,7 +292,7 @@ impl Tower {
"tower_warn",
(
"warn",
format!("Unable to get vote_state from account {}", key),
format!("Unable to get vote_state from account {key}"),
String
),
);
@ -621,10 +621,7 @@ impl Tower {
// non-descendants of the root every time root is set
assert!(
ancestors.contains(&root_slot),
"ancestors: {:?}, slot: {} root: {}",
ancestors,
slot,
root_slot
"ancestors: {ancestors:?}, slot: {slot} root: {root_slot}"
);
}
}
@ -681,8 +678,7 @@ impl Tower {
// newer snapshots on validator restart
let message = format!(
"bank_forks doesn't have corresponding data for the stray restored \
last vote({}), meaning some inconsistency between saved tower and ledger.",
last_voted_slot
last vote({last_voted_slot}), meaning some inconsistency between saved tower and ledger."
);
warn!("{}", message);
datapoint_warn!("tower_warn", ("warn", message, String));
@ -771,7 +767,7 @@ impl Tower {
// all of them.
empty_ancestors_due_to_minor_unsynced_ledger()
} else {
panic!("no ancestors found with slot: {}", last_voted_slot);
panic!("no ancestors found with slot: {last_voted_slot}");
}
});
@ -788,10 +784,7 @@ impl Tower {
return suspended_decision_due_to_major_unsynced_ledger();
} else {
panic!(
"Should never consider switching to ancestor ({}) of last vote: {}, ancestors({:?})",
switch_slot,
last_voted_slot,
last_vote_ancestors,
"Should never consider switching to ancestor ({switch_slot}) of last vote: {last_voted_slot}, ancestors({last_vote_ancestors:?})",
);
}
}
@ -1106,8 +1099,7 @@ impl Tower {
let message = format!(
"For some reason, we're REPROCESSING slots which has already been \
voted and ROOTED by us; \
VOTING will be SUSPENDED UNTIL {}!",
last_voted_slot,
VOTING will be SUSPENDED UNTIL {last_voted_slot}!",
);
error!("{}", message);
datapoint_error!("tower_error", ("error", message, String));
@ -1371,9 +1363,8 @@ pub fn reconcile_blockstore_roots_with_external_source(
Ordering::Greater => true,
Ordering::Equal => false,
Ordering::Less => panic!(
"last_blockstore_root({}) is skipped while traversing \
blockstore (currently at {}) from external root ({:?})!?",
last_blockstore_root, current, external_source,
"last_blockstore_root({last_blockstore_root}) is skipped while traversing \
blockstore (currently at {current}) from external root ({external_source:?})!?",
),
})
.collect();
@ -2824,7 +2815,7 @@ pub mod test {
.write(true)
.truncate(true)
.open(path)
.unwrap_or_else(|_| panic!("Failed to truncate file: {:?}", path));
.unwrap_or_else(|_| panic!("Failed to truncate file: {path:?}"));
},
);
assert_matches!(loaded, Err(TowerError::SerializeError(_)))

View File

@ -695,7 +695,7 @@ pub mod tests {
test_setup.correct_ancestors_response
);
}
x => panic!("Incorrect decision {:?}", x),
x => panic!("Incorrect decision {x:?}"),
};
}
@ -748,7 +748,7 @@ pub mod tests {
{
repair_status
}
x => panic!("Incorrect decision {:?}", x),
x => panic!("Incorrect decision {x:?}"),
};
// Expect to find everything after 92 in the `correct_ancestors_to_repair`.
@ -783,7 +783,7 @@ pub mod tests {
test_setup.correct_ancestors_response
);
}
x => panic!("Incorrect decision {:?}", x),
x => panic!("Incorrect decision {x:?}"),
};
}
@ -829,7 +829,7 @@ pub mod tests {
expected_mismatched_slots
);
}
x => panic!("Incorrect decision {:?}", x),
x => panic!("Incorrect decision {x:?}"),
};
}

View File

@ -302,7 +302,7 @@ impl HeaviestSubtreeForkChoice {
let root_fork_info = self.fork_infos.get_mut(&new_root);
root_fork_info
.unwrap_or_else(|| panic!("New root: {:?}, didn't exist in fork choice", new_root))
.unwrap_or_else(|| panic!("New root: {new_root:?}, didn't exist in fork choice"))
.parent = None;
self.tree_root = new_root;
self.last_root_time = Instant::now();
@ -929,9 +929,8 @@ impl HeaviestSubtreeForkChoice {
// validator has been running, so we must be able to fetch best_slots for all of
// them.
panic!(
"a bank at last_voted_slot({:?}) is a frozen bank so must have been \
"a bank at last_voted_slot({last_voted_slot_hash:?}) is a frozen bank so must have been \
added to heaviest_subtree_fork_choice at time of freezing",
last_voted_slot_hash,
)
} else {
// fork_infos doesn't have corresponding data for the stale stray last vote,

View File

@ -93,7 +93,7 @@ impl OptimisticConfirmationVerifier {
}
pub fn format_optimistic_confirmed_slot_violation_log(slot: Slot) -> String {
format!("Optimistically confirmed slot {} was not rooted", slot)
format!("Optimistically confirmed slot {slot} was not rooted")
}
pub fn log_unrooted_optimistic_slots(

View File

@ -234,6 +234,6 @@ mod test {
#[test]
fn test_slot_poh_timestamp_fmt() {
let t = SlotPohTimestamp::default();
assert_eq!(format!("{}", t), "SlotPohTimestamp: start=0 end=0 full=0");
assert_eq!(format!("{t}"), "SlotPohTimestamp: start=0 end=0 full=0");
}
}

View File

@ -399,7 +399,7 @@ impl ProgressMap {
pub fn get_propagated_stats_must_exist(&self, slot: Slot) -> &PropagatedStats {
self.get_propagated_stats(slot)
.unwrap_or_else(|| panic!("slot={} must exist in ProgressMap", slot))
.unwrap_or_else(|| panic!("slot={slot} must exist in ProgressMap"))
}
pub fn get_fork_stats(&self, slot: Slot) -> Option<&ForkStats> {

View File

@ -138,8 +138,7 @@ pub fn get_closest_completion(
(
"error",
format!(
"last_index + 1 < shred_count. last_index={} shred_count={}",
last_index, shred_count,
"last_index + 1 < shred_count. last_index={last_index} shred_count={shred_count}",
),
String
),

View File

@ -99,7 +99,7 @@ const MAX_REPAIR_RETRY_LOOP_ATTEMPTS: usize = 10;
lazy_static! {
static ref PAR_THREAD_POOL: ThreadPool = rayon::ThreadPoolBuilder::new()
.num_threads(MAX_CONCURRENT_FORKS_TO_REPLAY)
.thread_name(|ix| format!("solReplay{:02}", ix))
.thread_name(|ix| format!("solReplay{ix:02}"))
.build()
.unwrap();
}
@ -1796,13 +1796,13 @@ impl ReplayStage {
if is_serious {
datapoint_error!(
"replay-stage-mark_dead_slot",
("error", format!("error: {:?}", err), String),
("error", format!("error: {err:?}"), String),
("slot", slot, i64)
);
} else {
datapoint_info!(
"replay-stage-mark_dead_slot",
("error", format!("error: {:?}", err), String),
("error", format!("error: {err:?}"), String),
("slot", slot, i64)
);
}
@ -1815,7 +1815,7 @@ impl ReplayStage {
rpc_subscriptions.notify_slot_update(SlotUpdate::Dead {
slot,
err: format!("error: {:?}", err),
err: format!("error: {err:?}"),
timestamp: timestamp(),
});
let dead_state = DeadState::new_from_state(
@ -2134,7 +2134,7 @@ impl ReplayStage {
tower.refresh_last_vote_tx_blockhash(recent_blockhash);
// Send the votes to the TPU and gossip for network propagation
let hash_string = format!("{}", recent_blockhash);
let hash_string = format!("{recent_blockhash}");
datapoint_info!(
"refresh_vote",
("last_voted_slot", last_voted_slot, i64),
@ -2894,7 +2894,7 @@ impl ReplayStage {
// Otherwise we have to check the votes for confirmation
let mut propagated_stats = progress
.get_propagated_stats_mut(slot)
.unwrap_or_else(|| panic!("slot={} must exist in ProgressMap", slot));
.unwrap_or_else(|| panic!("slot={slot} must exist in ProgressMap"));
if propagated_stats.slot_vote_tracker.is_none() {
propagated_stats.slot_vote_tracker = vote_tracker.get_slot_vote_tracker(slot);

View File

@ -364,7 +364,7 @@ pub fn retransmitter(
let num_threads = get_thread_count().min(8).max(sockets.len());
let thread_pool = ThreadPoolBuilder::new()
.num_threads(num_threads)
.thread_name(|i| format!("solRetransmit{:02}", i))
.thread_name(|i| format!("solRetransmit{i:02}"))
.build()
.unwrap();
Builder::new()

View File

@ -243,7 +243,7 @@ mod tests {
// Create temporary placeholder directory for all test files
fn make_tmp_dir_path() -> PathBuf {
let out_dir = std::env::var("FARF_DIR").unwrap_or_else(|_| "farf".to_string());
let path = PathBuf::from(format!("{}/tmp/test_package_snapshots", out_dir));
let path = PathBuf::from(format!("{out_dir}/tmp/test_package_snapshots"));
// whack any possible collision
let _ignored = std::fs::remove_dir_all(&path);
@ -282,7 +282,7 @@ mod tests {
// Create some fake snapshot
let snapshots_paths: Vec<_> = (0..5)
.map(|i| {
let snapshot_file_name = format!("{}", i);
let snapshot_file_name = format!("{i}");
let snapshots_dir = snapshots_dir.join(&snapshot_file_name);
fs::create_dir_all(&snapshots_dir).unwrap();
let fake_snapshot_path = snapshots_dir.join(&snapshot_file_name);

View File

@ -138,13 +138,13 @@ impl FileTowerStorage {
// Old filename for towers pre 1.9 (VoteStateUpdate)
pub fn old_filename(&self, node_pubkey: &Pubkey) -> PathBuf {
self.tower_path
.join(format!("tower-{}", node_pubkey))
.join(format!("tower-{node_pubkey}"))
.with_extension("bin")
}
pub fn filename(&self, node_pubkey: &Pubkey) -> PathBuf {
self.tower_path
.join(format!("tower-1_9-{}", node_pubkey))
.join(format!("tower-1_9-{node_pubkey}"))
.with_extension("bin")
}
@ -266,8 +266,8 @@ impl EtcdTowerStorage {
}
fn get_keys(node_pubkey: &Pubkey) -> (String, String) {
let instance_key = format!("{}/instance", node_pubkey);
let tower_key = format!("{}/tower", node_pubkey);
let instance_key = format!("{node_pubkey}/instance");
let tower_key = format!("{node_pubkey}/tower");
(instance_key, tower_key)
}
@ -311,7 +311,7 @@ impl TowerStorage for EtcdTowerStorage {
if !response.succeeded() {
return Err(TowerError::IoError(io::Error::new(
io::ErrorKind::Other,
format!("Lost etcd instance lock for {}", node_pubkey),
format!("Lost etcd instance lock for {node_pubkey}"),
)));
}

View File

@ -392,8 +392,7 @@ impl Validator {
if !config.no_os_network_stats_reporting {
if let Err(e) = verify_net_stats_access() {
return Err(format!(
"Failed to access Network stats: {}. Bypass check with --no-os-network-stats-reporting.",
e,
"Failed to access Network stats: {e}. Bypass check with --no-os-network-stats-reporting.",
));
}
}
@ -409,7 +408,7 @@ impl Validator {
match result {
Ok(geyser_plugin_service) => Some(geyser_plugin_service),
Err(err) => {
return Err(format!("Failed to load the Geyser plugin: {:?}", err));
return Err(format!("Failed to load the Geyser plugin: {err:?}"));
}
}
} else {
@ -430,7 +429,7 @@ impl Validator {
}
if rayon::ThreadPoolBuilder::new()
.thread_name(|ix| format!("solRayonGlob{:02}", ix))
.thread_name(|ix| format!("solRayonGlob{ix:02}"))
.build_global()
.is_err()
{
@ -447,8 +446,7 @@ impl Validator {
if !ledger_path.is_dir() {
return Err(format!(
"ledger directory does not exist or is not accessible: {:?}",
ledger_path
"ledger directory does not exist or is not accessible: {ledger_path:?}"
));
}
@ -903,7 +901,7 @@ impl Validator {
&start_progress,
) {
Ok(waited) => waited,
Err(e) => return Err(format!("wait_for_supermajority failed: {:?}", e)),
Err(e) => return Err(format!("wait_for_supermajority failed: {e:?}")),
};
let ledger_metric_report_service =
@ -1232,9 +1230,8 @@ fn check_poh_speed(
info!("PoH speed check: Will sleep {}ns per slot.", extra_ns);
} else {
return Err(format!(
"PoH is slower than cluster target tick rate! mine: {} cluster: {}. \
"PoH is slower than cluster target tick rate! mine: {my_ns_per_slot} cluster: {target_ns_per_slot}. \
If you wish to continue, try --no-poh-speed-test",
my_ns_per_slot, target_ns_per_slot,
));
}
}
@ -1273,10 +1270,8 @@ fn post_process_restored_tower(
// intentionally fail to restore tower; we're supposedly in a new hard fork; past
// out-of-chain vote state doesn't make sense at all
// what if --wait-for-supermajority again if the validator restarted?
let message = format!(
"Hard fork is detected; discarding tower restoration result: {:?}",
tower
);
let message =
format!("Hard fork is detected; discarding tower restoration result: {tower:?}");
datapoint_error!("tower_error", ("error", message, String),);
error!("{}", message);
@ -1306,15 +1301,14 @@ fn post_process_restored_tower(
if !err.is_file_missing() {
datapoint_error!(
"tower_error",
("error", format!("Unable to restore tower: {}", err), String),
("error", format!("Unable to restore tower: {err}"), String),
);
}
if should_require_tower && voting_has_been_active {
return Err(format!(
"Requested mandatory tower restore failed: {}. \
"Requested mandatory tower restore failed: {err}. \
And there is an existing vote_account containing actual votes. \
Aborting due to possible conflicting duplicate votes",
err
Aborting due to possible conflicting duplicate votes"
));
}
if err.is_file_missing() && !voting_has_been_active {
@ -1380,10 +1374,7 @@ fn load_blockstore(
if let Some(expected_genesis_hash) = config.expected_genesis_hash {
if genesis_hash != expected_genesis_hash {
return Err(format!(
"genesis hash mismatch: hash={} expected={}. Delete the ledger directory to continue: {:?}",
genesis_hash,
expected_genesis_hash,
ledger_path,
"genesis hash mismatch: hash={genesis_hash} expected={expected_genesis_hash}. Delete the ledger directory to continue: {ledger_path:?}",
));
}
}
@ -1599,7 +1590,7 @@ impl<'a> ProcessBlockStore<'a> {
self.cache_block_meta_sender.as_ref(),
&self.accounts_background_request_sender,
) {
return Err(format!("Failed to load ledger: {:?}", e));
return Err(format!("Failed to load ledger: {e:?}"));
}
exit.store(true, Ordering::Relaxed);
@ -1617,10 +1608,7 @@ impl<'a> ProcessBlockStore<'a> {
self.blockstore,
&mut self.original_blockstore_root,
) {
return Err(format!(
"Failed to reconcile blockstore with tower: {:?}",
e
));
return Err(format!("Failed to reconcile blockstore with tower: {e:?}"));
}
}
@ -1645,8 +1633,7 @@ impl<'a> ProcessBlockStore<'a> {
&mut self.original_blockstore_root,
) {
return Err(format!(
"Failed to reconcile blockstore with hard fork: {:?}",
e
"Failed to reconcile blockstore with hard fork: {e:?}"
));
}
}
@ -1715,7 +1702,7 @@ fn maybe_warp_slot(
snapshot_config.maximum_incremental_snapshot_archives_to_retain,
) {
Ok(archive_info) => archive_info,
Err(e) => return Err(format!("Unable to create snapshot: {}", e)),
Err(e) => return Err(format!("Unable to create snapshot: {e}")),
};
info!(
"created snapshot: {}",

View File

@ -405,7 +405,7 @@ impl WindowService {
};
let thread_pool = rayon::ThreadPoolBuilder::new()
.num_threads(get_thread_count().min(8))
.thread_name(|i| format!("solWinInsert{:02}", i))
.thread_name(|i| format!("solWinInsert{i:02}"))
.build()
.unwrap();
let reed_solomon_cache = ReedSolomonCache::default();

View File

@ -439,7 +439,7 @@ mod tests {
let shared_batch_id = current_batch_id.clone();
let shared_finished_count = finished_batch_count.clone();
let insert_thread = Builder::new()
.name(format!("insert_shreds-{}", i))
.name(format!("insert_shreds-{i}"))
.spawn(move || {
let start = Instant::now();
let mut now = Instant::now();

View File

@ -1094,9 +1094,7 @@ fn test_snapshots_with_background_services(
{
assert!(
timer.elapsed() < MAX_WAIT_DURATION,
"Waiting for full snapshot {} exceeded the {:?} maximum wait duration!",
slot,
MAX_WAIT_DURATION,
"Waiting for full snapshot {slot} exceeded the {MAX_WAIT_DURATION:?} maximum wait duration!",
);
std::thread::sleep(Duration::from_secs(1));
}
@ -1114,9 +1112,7 @@ fn test_snapshots_with_background_services(
{
assert!(
timer.elapsed() < MAX_WAIT_DURATION,
"Waiting for incremental snapshot {} exceeded the {:?} maximum wait duration!",
slot,
MAX_WAIT_DURATION,
"Waiting for incremental snapshot {slot} exceeded the {MAX_WAIT_DURATION:?} maximum wait duration!",
);
std::thread::sleep(Duration::from_secs(1));
}

View File

@ -538,7 +538,7 @@ fn create_payers<T: 'static + BenchTpsClient + Send + Sync>(
let res =
generate_and_fund_keypairs(client.unwrap().clone(), &funding_key, size, 1_000_000)
.unwrap_or_else(|e| {
eprintln!("Error could not fund keys: {:?}", e);
eprintln!("Error could not fund keys: {e:?}");
exit(1);
});
res.into_iter().map(Some).collect()
@ -591,11 +591,11 @@ fn run_dos_transactions<T: 'static + BenchTpsClient + Send + Sync>(
})
.collect();
if let Err(err) = sender_thread.join() {
println!("join() failed with: {:?}", err);
println!("join() failed with: {err:?}");
}
for t_generator in tx_generator_threads {
if let Err(err) = t_generator.join() {
println!("join() failed with: {:?}", err);
println!("join() failed with: {err:?}");
}
}
}

View File

@ -69,7 +69,7 @@ pub fn download_file<'a, 'b>(
progress_notify_callback: &'a mut DownloadProgressCallbackOption<'b>,
) -> Result<(), String> {
if destination_file.is_file() {
return Err(format!("{:?} already exists", destination_file));
return Err(format!("{destination_file:?} already exists"));
}
let download_start = Instant::now();
@ -88,7 +88,7 @@ pub fn download_file<'a, 'b>(
let progress_bar = new_spinner_progress_bar();
if use_progress_bar {
progress_bar.set_message(format!("{}Downloading {}...", TRUCK, url));
progress_bar.set_message(format!("{TRUCK}Downloading {url}..."));
}
let response = reqwest::blocking::Client::new()
@ -119,7 +119,7 @@ pub fn download_file<'a, 'b>(
.expect("ProgresStyle::template direct input to be correct")
.progress_chars("=> "),
);
progress_bar.set_message(format!("{}Downloading~ {}", TRUCK, url));
progress_bar.set_message(format!("{TRUCK}Downloading~ {url}"));
} else {
info!("Downloading {} bytes from {}", download_size, url);
}
@ -212,7 +212,7 @@ pub fn download_file<'a, 'b>(
File::create(&temp_destination_file)
.and_then(|mut file| std::io::copy(&mut source, &mut file))
.map_err(|err| format!("Unable to write {:?}: {:?}", temp_destination_file, err))?;
.map_err(|err| format!("Unable to write {temp_destination_file:?}: {err:?}"))?;
source.progress_bar.finish_and_clear();
info!(
@ -227,7 +227,7 @@ pub fn download_file<'a, 'b>(
);
std::fs::rename(temp_destination_file, destination_file)
.map_err(|err| format!("Unable to rename: {:?}", err))?;
.map_err(|err| format!("Unable to rename: {err:?}"))?;
Ok(())
}
@ -243,7 +243,7 @@ pub fn download_genesis_if_missing(
let _ignored = fs::remove_dir_all(&tmp_genesis_path);
download_file(
&format!("http://{}/{}", rpc_addr, DEFAULT_GENESIS_ARCHIVE),
&format!("http://{rpc_addr}/{DEFAULT_GENESIS_ARCHIVE}"),
&tmp_genesis_package,
use_progress_bar,
&mut None,

View File

@ -46,7 +46,7 @@ use {
lazy_static! {
static ref PAR_THREAD_POOL: ThreadPool = rayon::ThreadPoolBuilder::new()
.num_threads(get_max_thread_count())
.thread_name(|ix| format!("solEntry{:02}", ix))
.thread_name(|ix| format!("solEntry{ix:02}"))
.build()
.unwrap();
}
@ -678,7 +678,7 @@ impl EntrySlice for [Entry] {
);
},
_ => {
panic!("unsupported simd len: {}", simd_len);
panic!("unsupported simd len: {simd_len}");
}
}
let entry_start = i * simd_len;

View File

@ -367,8 +367,7 @@ pub async fn run_faucet(
listener.as_ref().map(|listener| listener.local_addr().unwrap())
.map_err(|err| {
format!(
"Unable to bind faucet to {:?}, check the address is not already in use: {}",
faucet_addr, err
"Unable to bind faucet to {faucet_addr:?}, check the address is not already in use: {err}"
)
})
)

View File

@ -236,7 +236,7 @@ fn do_derive_abi_enum_visitor(input: ItemEnum) -> TokenStream {
});
}
let type_str = format!("{}", type_name);
let type_str = format!("{type_name}");
(quote! {
impl #impl_generics ::solana_frozen_abi::abi_example::AbiEnumVisitor for #type_name #ty_generics #where_clause {
fn visit_for_abi(&self, digester: &mut ::solana_frozen_abi::abi_digester::AbiDigester) -> ::solana_frozen_abi::abi_digester::DigestResult {
@ -310,7 +310,7 @@ fn quote_for_test(
#[cfg(RUSTC_WITH_SPECIALIZATION)]
fn test_mod_name(type_name: &Ident) -> Ident {
Ident::new(&format!("{}_frozen_abi", type_name), Span::call_site())
Ident::new(&format!("{type_name}_frozen_abi"), Span::call_site())
}
#[cfg(RUSTC_WITH_SPECIALIZATION)]

View File

@ -180,7 +180,7 @@ impl AbiDigester {
v: &T,
) -> Result<(), DigestError> {
let field_type_name = shorten_serialize_with(type_name::<T>());
self.update_with_string(format!("field {}: {}", key, field_type_name));
self.update_with_string(format!("field {key}: {field_type_name}"));
self.create_child()?
.digest_data(v)
.map(|_| ())
@ -198,7 +198,7 @@ impl AbiDigester {
label: &'static str,
variant: &'static str,
) -> Result<(), DigestError> {
assert!(self.for_enum, "derive AbiEnumVisitor or implement it for the enum, which contains a variant ({}) named {}", label, variant);
assert!(self.for_enum, "derive AbiEnumVisitor or implement it for the enum, which contains a variant ({label}) named {variant}");
Ok(())
}
@ -220,7 +220,7 @@ impl AbiDigester {
error!("Bad thread name detected for dumping; Maybe, --test-threads=1? Sorry, SOLANA_ABI_DUMP_DIR doesn't work under 1; increase it");
}
let path = format!("{}/{}_{}", dir, thread_name, hash,);
let path = format!("{dir}/{thread_name}_{hash}",);
let mut file = std::fs::File::create(path).unwrap();
for buf in (*self.data_types.borrow()).iter() {
file.write_all(buf.as_bytes()).unwrap();
@ -337,7 +337,7 @@ impl Serializer for AbiDigester {
fn serialize_unit_variant(mut self, _name: Sstr, index: u32, variant: Sstr) -> DigestResult {
self.check_for_enum("unit_variant", variant)?;
self.update_with_string(format!("variant({}) {} (unit)", index, variant));
self.update_with_string(format!("variant({index}) {variant} (unit)"));
Ok(self)
}
@ -379,17 +379,17 @@ impl Serializer for AbiDigester {
len, 1,
"Exactly 1 seq element is needed to generate the ABI digest precisely"
);
self.update_with_string(format!("seq (elements = {})", len));
self.update_with_string(format!("seq (elements = {len})"));
self.create_child()
}
fn serialize_tuple(mut self, len: usize) -> DigestResult {
self.update_with_string(format!("tuple (elements = {})", len));
self.update_with_string(format!("tuple (elements = {len})"));
self.create_child()
}
fn serialize_tuple_struct(mut self, name: Sstr, len: usize) -> DigestResult {
self.update_with_string(format!("struct {} (fields = {}) (tuple)", name, len));
self.update_with_string(format!("struct {name} (fields = {len}) (tuple)"));
self.create_child()
}
@ -401,7 +401,7 @@ impl Serializer for AbiDigester {
len: usize,
) -> DigestResult {
self.check_for_enum("tuple_variant", variant)?;
self.update_with_string(format!("variant({}) {} (fields = {})", i, variant, len));
self.update_with_string(format!("variant({i}) {variant} (fields = {len})"));
self.create_child()
}
@ -411,12 +411,12 @@ impl Serializer for AbiDigester {
len, 1,
"Exactly 1 map entry is needed to generate the ABI digest precisely"
);
self.update_with_string(format!("map (entries = {})", len));
self.update_with_string(format!("map (entries = {len})"));
self.create_child()
}
fn serialize_struct(mut self, name: Sstr, len: usize) -> DigestResult {
self.update_with_string(format!("struct {} (fields = {})", name, len));
self.update_with_string(format!("struct {name} (fields = {len})"));
self.create_child()
}
@ -428,10 +428,7 @@ impl Serializer for AbiDigester {
len: usize,
) -> DigestResult {
self.check_for_enum("struct_variant", variant)?;
self.update_with_string(format!(
"variant({}) struct {} (fields = {})",
i, variant, len
));
self.update_with_string(format!("variant({i}) struct {variant} (fields = {len})"));
self.create_child()
}
}

View File

@ -266,15 +266,9 @@ impl<T: Default + Serialize> TypeErasedExample<T> for Placeholder {
let normalized_type_name = normalize_type_name(original_type_name);
if normalized_type_name.starts_with("solana") {
panic!(
"derive or implement AbiExample/AbiEnumVisitor for {}",
original_type_name
);
panic!("derive or implement AbiExample/AbiEnumVisitor for {original_type_name}");
} else {
panic!(
"new unrecognized type for ABI digest!: {}",
original_type_name
)
panic!("new unrecognized type for ABI digest!: {original_type_name}")
}
}
}

View File

@ -17,8 +17,7 @@ fn check_genesis_hash(
if let Some(expected_genesis_hash) = expected_genesis_hash {
if expected_genesis_hash != genesis_hash {
return Err(format!(
"Genesis hash mismatch: expected {} but downloaded genesis hash is {}",
expected_genesis_hash, genesis_hash,
"Genesis hash mismatch: expected {expected_genesis_hash} but downloaded genesis hash is {genesis_hash}",
));
}
}
@ -31,7 +30,7 @@ fn load_local_genesis(
expected_genesis_hash: Option<Hash>,
) -> Result<GenesisConfig, String> {
let existing_genesis = GenesisConfig::load(ledger_path)
.map_err(|err| format!("Failed to load genesis config: {}", err))?;
.map_err(|err| format!("Failed to load genesis config: {err}"))?;
check_genesis_hash(&existing_genesis, expected_genesis_hash)?;
Ok(existing_genesis)
@ -59,14 +58,14 @@ pub fn download_then_check_genesis_hash(
ledger_path,
max_genesis_archive_unpacked_size,
)
.map_err(|err| format!("Failed to unpack downloaded genesis config: {}", err))?;
.map_err(|err| format!("Failed to unpack downloaded genesis config: {err}"))?;
let downloaded_genesis = GenesisConfig::load(ledger_path)
.map_err(|err| format!("Failed to load downloaded genesis config: {}", err))?;
.map_err(|err| format!("Failed to load downloaded genesis config: {err}"))?;
check_genesis_hash(&downloaded_genesis, expected_genesis_hash)?;
std::fs::rename(tmp_genesis_package, genesis_package)
.map_err(|err| format!("Unable to rename: {:?}", err))?;
.map_err(|err| format!("Unable to rename: {err:?}"))?;
downloaded_genesis
} else {

View File

@ -17,7 +17,7 @@ impl AddressGenerator {
}
pub fn nth(&self, nth: usize) -> Pubkey {
Pubkey::create_with_seed(&self.base_pubkey, &format!("{}", nth), &self.program_id).unwrap()
Pubkey::create_with_seed(&self.base_pubkey, &format!("{nth}"), &self.program_id).unwrap()
}
#[allow(clippy::should_implement_trait)]

View File

@ -64,13 +64,13 @@ pub fn load_genesis_accounts(file: &str, genesis_config: &mut GenesisConfig) ->
let genesis_accounts: HashMap<String, Base64Account> =
serde_yaml::from_reader(accounts_file)
.map_err(|err| io::Error::new(io::ErrorKind::Other, format!("{:?}", err)))?;
.map_err(|err| io::Error::new(io::ErrorKind::Other, format!("{err:?}")))?;
for (key, account_details) in genesis_accounts {
let pubkey = pubkey_from_str(key.as_str()).map_err(|err| {
io::Error::new(
io::ErrorKind::Other,
format!("Invalid pubkey/keypair {}: {:?}", key, err),
format!("Invalid pubkey/keypair {key}: {err:?}"),
)
})?;
@ -401,8 +401,7 @@ fn main() -> Result<(), Box<dyn error::Error>> {
Err(io::Error::new(
io::ErrorKind::Other,
format!(
"error: insufficient {}: {} for rent exemption, requires {}",
name, lamports, exempt
"error: insufficient {name}: {lamports} for rent exemption, requires {exempt}"
),
))
} else {
@ -592,12 +591,12 @@ fn main() -> Result<(), Box<dyn error::Error>> {
match address_loader_program {
[address, loader, program] => {
let address = address.parse::<Pubkey>().unwrap_or_else(|err| {
eprintln!("Error: invalid address {}: {}", address, err);
eprintln!("Error: invalid address {address}: {err}");
process::exit(1);
});
let loader = loader.parse::<Pubkey>().unwrap_or_else(|err| {
eprintln!("Error: invalid loader {}: {}", loader, err);
eprintln!("Error: invalid loader {loader}: {err}");
process::exit(1);
});
@ -605,7 +604,7 @@ fn main() -> Result<(), Box<dyn error::Error>> {
File::open(program)
.and_then(|mut file| file.read_to_end(&mut program_data))
.unwrap_or_else(|err| {
eprintln!("Error: failed to read {}: {}", program, err);
eprintln!("Error: failed to read {program}: {err}");
process::exit(1);
});
genesis_config.add_account(
@ -632,7 +631,7 @@ fn main() -> Result<(), Box<dyn error::Error>> {
LedgerColumnOptions::default(),
)?;
println!("{}", genesis_config);
println!("{genesis_config}");
Ok(())
}

View File

@ -140,8 +140,7 @@ impl GeyserPluginService {
Ok(file) => file,
Err(err) => {
return Err(GeyserPluginServiceError::CannotOpenConfigFile(format!(
"Failed to open the plugin config file {:?}, error: {:?}",
geyser_plugin_config_file, err
"Failed to open the plugin config file {geyser_plugin_config_file:?}, error: {err:?}"
)));
}
};
@ -149,8 +148,7 @@ impl GeyserPluginService {
let mut contents = String::new();
if let Err(err) = file.read_to_string(&mut contents) {
return Err(GeyserPluginServiceError::CannotReadConfigFile(format!(
"Failed to read the plugin config file {:?}, error: {:?}",
geyser_plugin_config_file, err
"Failed to read the plugin config file {geyser_plugin_config_file:?}, error: {err:?}"
)));
}
@ -158,8 +156,7 @@ impl GeyserPluginService {
Ok(value) => value,
Err(err) => {
return Err(GeyserPluginServiceError::InvalidConfigFileFormat(format!(
"The config file {:?} is not in a valid Json5 format, error: {:?}",
geyser_plugin_config_file, err
"The config file {geyser_plugin_config_file:?} is not in a valid Json5 format, error: {err:?}"
)));
}
};
@ -171,8 +168,7 @@ impl GeyserPluginService {
if libpath.is_relative() {
let config_dir = geyser_plugin_config_file.parent().ok_or_else(|| {
GeyserPluginServiceError::CannotOpenConfigFile(format!(
"Failed to resolve parent of {:?}",
geyser_plugin_config_file,
"Failed to resolve parent of {geyser_plugin_config_file:?}",
))
})?;
libpath = config_dir.join(libpath);
@ -186,10 +182,7 @@ impl GeyserPluginService {
unsafe {
let result = plugin_manager.load_plugin(libpath.to_str().unwrap(), config_file);
if let Err(err) = result {
let msg = format!(
"Failed to load the plugin library: {:?}, error: {:?}",
libpath, err
);
let msg = format!("Failed to load the plugin library: {libpath:?}, error: {err:?}");
return Err(GeyserPluginServiceError::PluginLoadError(msg));
}
}

View File

@ -844,15 +844,12 @@ impl ClusterInfo {
nodes.join(""),
nodes.len().saturating_sub(shred_spy_nodes),
if total_spy_nodes > 0 {
format!("\nSpies: {}", total_spy_nodes)
format!("\nSpies: {total_spy_nodes}")
} else {
"".to_string()
},
if different_shred_nodes > 0 {
format!(
"\nNodes with different shred version: {}",
different_shred_nodes
)
format!("\nNodes with different shred version: {different_shred_nodes}")
} else {
"".to_string()
}
@ -1714,7 +1711,7 @@ impl ClusterInfo {
) -> JoinHandle<()> {
let thread_pool = ThreadPoolBuilder::new()
.num_threads(std::cmp::min(get_thread_count(), 8))
.thread_name(|i| format!("solRunGossip{:02}", i))
.thread_name(|i| format!("solRunGossip{i:02}"))
.build()
.unwrap();
Builder::new()
@ -2620,7 +2617,7 @@ impl ClusterInfo {
) -> JoinHandle<()> {
let thread_pool = ThreadPoolBuilder::new()
.num_threads(get_thread_count().min(8))
.thread_name(|i| format!("solGossipCons{:02}", i))
.thread_name(|i| format!("solGossipCons{i:02}"))
.build()
.unwrap();
let run_consume = move || {
@ -2652,7 +2649,7 @@ impl ClusterInfo {
let recycler = PacketBatchRecycler::default();
let thread_pool = ThreadPoolBuilder::new()
.num_threads(get_thread_count().min(8))
.thread_name(|i| format!("solGossipWork{:02}", i))
.thread_name(|i| format!("solGossipWork{i:02}"))
.build()
.unwrap();
Builder::new()
@ -3568,8 +3565,7 @@ RPC Enabled Nodes: 1"#;
let size = serialized_size(&pull_response).unwrap();
assert!(
PULL_RESPONSE_MIN_SERIALIZED_SIZE as u64 <= size,
"pull-response serialized size: {}",
size
"pull-response serialized size: {size}"
);
}
}

View File

@ -1129,13 +1129,9 @@ mod tests {
assert!(num_inserts > crds.table.len());
let (num_nodes, num_votes, num_epoch_slots) = check_crds_value_indices(&mut rng, &crds);
assert!(num_nodes * 3 < crds.table.len());
assert!(num_nodes > 100, "num nodes: {}", num_nodes);
assert!(num_votes > 100, "num votes: {}", num_votes);
assert!(
num_epoch_slots > 100,
"num epoch slots: {}",
num_epoch_slots
);
assert!(num_nodes > 100, "num nodes: {num_nodes}");
assert!(num_votes > 100, "num votes: {num_votes}");
assert!(num_epoch_slots > 100, "num epoch slots: {num_epoch_slots}");
// Remove values one by one and assert that nodes indices stay valid.
while !crds.table.is_empty() {
let index = rng.gen_range(0, crds.table.len());

View File

@ -968,7 +968,7 @@ pub(crate) mod tests {
}
}
let crds = RwLock::new(crds);
assert!(num_inserts > 30_000, "num inserts: {}", num_inserts);
assert!(num_inserts > 30_000, "num inserts: {num_inserts}");
let filters = crds_gossip_pull.build_crds_filters(&thread_pool, &crds, MAX_BLOOM_SIZE);
assert_eq!(filters.len(), MIN_NUM_BLOOM_FILTERS.max(32));
let crds = crds.read().unwrap();
@ -995,7 +995,7 @@ pub(crate) mod tests {
}
assert_eq!(num_hits, 1);
}
assert!(false_positives < 150_000, "fp: {}", false_positives);
assert!(false_positives < 150_000, "fp: {false_positives}");
}
#[test]
@ -1164,7 +1164,7 @@ pub(crate) mod tests {
.take(100)
.filter(|peer| peer != old)
.count();
assert!(count < 2, "count of peer != old: {}", count);
assert!(count < 2, "count of peer != old: {count}");
}
#[test]

View File

@ -504,8 +504,8 @@ impl fmt::Display for CrdsValueLabel {
CrdsValueLabel::AccountsHashes(_) => write!(f, "AccountsHashes({})", self.pubkey()),
CrdsValueLabel::LegacyVersion(_) => write!(f, "LegacyVersion({})", self.pubkey()),
CrdsValueLabel::Version(_) => write!(f, "Version({})", self.pubkey()),
CrdsValueLabel::NodeInstance(pk) => write!(f, "NodeInstance({})", pk),
CrdsValueLabel::DuplicateShred(ix, pk) => write!(f, "DuplicateShred({}, {})", ix, pk),
CrdsValueLabel::NodeInstance(pk) => write!(f, "NodeInstance({pk})"),
CrdsValueLabel::DuplicateShred(ix, pk) => write!(f, "DuplicateShred({ix}, {pk})"),
CrdsValueLabel::IncrementalSnapshotHashes(_) => {
write!(f, "IncrementalSnapshotHashes({})", self.pubkey())
}

View File

@ -158,17 +158,14 @@ fn parse_gossip_host(matches: &ArgMatches, entrypoint_addr: Option<SocketAddr>)
.value_of("gossip_host")
.map(|gossip_host| {
solana_net_utils::parse_host(gossip_host).unwrap_or_else(|e| {
eprintln!("failed to parse gossip-host: {}", e);
eprintln!("failed to parse gossip-host: {e}");
exit(1);
})
})
.unwrap_or_else(|| {
if let Some(entrypoint_addr) = entrypoint_addr {
solana_net_utils::get_public_ip_addr(&entrypoint_addr).unwrap_or_else(|err| {
eprintln!(
"Failed to contact cluster entrypoint {}: {}",
entrypoint_addr, err
);
eprintln!("Failed to contact cluster entrypoint {entrypoint_addr}: {err}");
exit(1);
})
} else {
@ -192,26 +189,20 @@ fn process_spy_results(
} else {
" or more"
};
eprintln!(
"Error: Insufficient validators discovered. Expecting {}{}",
num, add,
);
eprintln!("Error: Insufficient validators discovered. Expecting {num}{add}",);
exit(1);
}
}
if let Some(node) = pubkey {
if !validators.iter().any(|x| x.id == node) {
eprintln!("Error: Could not find node {:?}", node);
eprintln!("Error: Could not find node {node:?}");
exit(1);
}
}
}
if let Some(num_nodes_exactly) = num_nodes_exactly {
if validators.len() > num_nodes_exactly {
eprintln!(
"Error: Extra nodes discovered. Expecting exactly {}",
num_nodes_exactly
);
eprintln!("Error: Extra nodes discovered. Expecting exactly {num_nodes_exactly}");
exit(1);
}
}
@ -269,7 +260,7 @@ fn process_spy(matches: &ArgMatches, socket_addr_space: SocketAddrSpace) -> std:
fn parse_entrypoint(matches: &ArgMatches) -> Option<SocketAddr> {
matches.value_of("entrypoint").map(|entrypoint| {
solana_net_utils::parse_host_port(entrypoint).unwrap_or_else(|e| {
eprintln!("failed to parse entrypoint address: {}", e);
eprintln!("failed to parse entrypoint address: {e}");
exit(1);
})
})
@ -314,7 +305,7 @@ fn process_rpc_url(
}
for rpc_addr in rpc_addrs {
println!("http://{}", rpc_addr);
println!("http://{rpc_addr}");
if any {
break;
}

View File

@ -227,8 +227,7 @@ fn run_simulation(stakes: &[u64], fanout: usize) {
for (id, (layer1_done, recv, r)) in batch.iter_mut() {
assert!(
now.elapsed().as_secs() < timeout,
"Timed out with {:?} remaining nodes",
remaining
"Timed out with {remaining:?} remaining nodes"
);
let cluster = c_info.clone_with_id(id);
if !*layer1_done {

View File

@ -607,7 +607,7 @@ fn network_run_pull(
fn build_gossip_thread_pool() -> ThreadPool {
ThreadPoolBuilder::new()
.num_threads(get_thread_count().min(2))
.thread_name(|i| format!("gossipTest{:02}", i))
.thread_name(|i| format!("gossipTest{i:02}"))
.build()
.unwrap()
}

View File

@ -17,7 +17,7 @@ fn press_enter() {
fn main() {
solana_install::main_init().unwrap_or_else(|err| {
println!("Error: {}", err);
println!("Error: {err}");
press_enter();
exit(1);
});

View File

@ -89,7 +89,7 @@ fn download_to_temp(
Ok(hasher.result())
}
let url = Url::parse(url).map_err(|err| format!("Unable to parse {}: {}", url, err))?;
let url = Url::parse(url).map_err(|err| format!("Unable to parse {url}: {err}"))?;
let temp_dir = TempDir::new()?;
let temp_file = temp_dir.path().join("download");
@ -100,7 +100,7 @@ fn download_to_temp(
.build()?;
let progress_bar = new_spinner_progress_bar();
progress_bar.set_message(format!("{}Downloading...", TRUCK));
progress_bar.set_message(format!("{TRUCK}Downloading..."));
let response = client.get(url.as_str()).send()?;
let download_size = {
@ -121,7 +121,7 @@ fn download_to_temp(
.expect("ProgresStyle::template direct input to be correct")
.progress_chars("=> "),
);
progress_bar.set_message(format!("{}Downloading", TRUCK));
progress_bar.set_message(format!("{TRUCK}Downloading"));
struct DownloadProgress<R> {
progress_bar: ProgressBar,
@ -146,7 +146,7 @@ fn download_to_temp(
std::io::copy(&mut source, &mut file)?;
let temp_file_sha256 = sha256_file_digest(&temp_file)
.map_err(|err| format!("Unable to hash {:?}: {}", temp_file, err))?;
.map_err(|err| format!("Unable to hash {temp_file:?}: {err}"))?;
if expected_sha256.is_some() && expected_sha256 != Some(&temp_file_sha256) {
return Err(io::Error::new(io::ErrorKind::Other, "Incorrect hash").into());
@ -164,7 +164,7 @@ fn extract_release_archive(
use {bzip2::bufread::BzDecoder, tar::Archive};
let progress_bar = new_spinner_progress_bar();
progress_bar.set_message(format!("{}Extracting...", PACKAGE));
progress_bar.set_message(format!("{PACKAGE}Extracting..."));
if extract_dir.exists() {
let _ = fs::remove_dir_all(extract_dir);
@ -189,9 +189,9 @@ fn extract_release_archive(
fn load_release_version(version_yml: &Path) -> Result<ReleaseVersion, String> {
let file = File::open(version_yml)
.map_err(|err| format!("Unable to open {:?}: {:?}", version_yml, err))?;
.map_err(|err| format!("Unable to open {version_yml:?}: {err:?}"))?;
let version: ReleaseVersion = serde_yaml::from_reader(file)
.map_err(|err| format!("Unable to parse {:?}: {:?}", version_yml, err))?;
.map_err(|err| format!("Unable to parse {version_yml:?}: {err:?}"))?;
Ok(version)
}
@ -273,13 +273,13 @@ fn get_update_manifest(
) -> Result<UpdateManifest, String> {
let data = rpc_client
.get_account_data(update_manifest_pubkey)
.map_err(|err| format!("Unable to fetch update manifest: {}", err))?;
.map_err(|err| format!("Unable to fetch update manifest: {err}"))?;
let config_data = get_config_data(&data)
.map_err(|err| format!("Unable to get at config_data to update manifest: {}", err))?;
.map_err(|err| format!("Unable to get at config_data to update manifest: {err}"))?;
let signed_update_manifest =
SignedUpdateManifest::deserialize(update_manifest_pubkey, config_data)
.map_err(|err| format!("Unable to deserialize update manifest: {}", err))?;
.map_err(|err| format!("Unable to deserialize update manifest: {err}"))?;
Ok(signed_update_manifest.manifest)
}
@ -448,7 +448,7 @@ fn add_to_path(new_path: &str) -> bool {
#[cfg(unix)]
fn add_to_path(new_path: &str) -> bool {
let shell_export_string = format!("\nexport PATH=\"{}:$PATH\"", new_path);
let shell_export_string = format!("\nexport PATH=\"{new_path}:$PATH\"");
let mut modified_rcfiles = false;
// Look for sh, bash, and zsh rc files
@ -488,7 +488,7 @@ fn add_to_path(new_path: &str) -> bool {
match read_file(&rcfile) {
Err(err) => {
println!("Unable to read {:?}: {}", rcfile, err);
println!("Unable to read {rcfile:?}: {err}");
}
Ok(contents) => {
if !contents.contains(&shell_export_string) {
@ -506,14 +506,14 @@ fn add_to_path(new_path: &str) -> bool {
.create(true)
.open(dest)?;
writeln!(&mut dest_file, "{}", line)?;
writeln!(&mut dest_file, "{line}")?;
dest_file.sync_data()?;
Ok(())
}
append_file(&rcfile, &shell_export_string).unwrap_or_else(|err| {
format!("Unable to append to {:?}: {}", rcfile, err);
format!("Unable to append to {rcfile:?}: {err}");
});
modified_rcfiles = true;
}
@ -597,9 +597,9 @@ fn release_channel_version_url(release_channel: &str) -> String {
fn print_update_manifest(update_manifest: &UpdateManifest) {
let when = Local.timestamp(update_manifest.timestamp_secs as i64, 0);
println_name_value(&format!("{}release date:", BULLET), &when.to_string());
println_name_value(&format!("{BULLET}release date:"), &when.to_string());
println_name_value(
&format!("{}download URL:", BULLET),
&format!("{BULLET}download URL:"),
&update_manifest.download_url,
);
}
@ -619,7 +619,7 @@ pub fn info(config_file: &str, local_info_only: bool, eval: bool) -> Result<(),
ExplicitRelease::Channel(channel) => channel,
})
.and_then(|channel| {
println!("SOLANA_INSTALL_ACTIVE_CHANNEL={}", channel,);
println!("SOLANA_INSTALL_ACTIVE_CHANNEL={channel}",);
Option::<String>::None
});
return Ok(());
@ -636,7 +636,7 @@ pub fn info(config_file: &str, local_info_only: bool, eval: bool) -> Result<(),
load_release_version(&config.active_release_dir().join("version.yml"))
{
println_name_value(
&format!("{}Release commit:", BULLET),
&format!("{BULLET}Release commit:"),
&release_version.commit[0..7],
);
}
@ -645,16 +645,16 @@ pub fn info(config_file: &str, local_info_only: bool, eval: bool) -> Result<(),
if let Some(explicit_release) = &config.explicit_release {
match explicit_release {
ExplicitRelease::Semver(release_semver) => {
println_name_value(&format!("{}Release version:", BULLET), release_semver);
println_name_value(&format!("{BULLET}Release version:"), release_semver);
println_name_value(
&format!("{}Release URL:", BULLET),
&format!("{BULLET}Release URL:"),
&github_release_download_url(release_semver),
);
}
ExplicitRelease::Channel(release_channel) => {
println_name_value(&format!("{}Release channel:", BULLET), release_channel);
println_name_value(&format!("{BULLET}Release channel:"), release_channel);
println_name_value(
&format!("{}Release URL:", BULLET),
&format!("{BULLET}Release URL:"),
&release_channel_download_url(release_channel),
);
}
@ -693,9 +693,9 @@ pub fn deploy(
update_manifest_keypair_file: &str,
) -> Result<(), String> {
let from_keypair = read_keypair_file(from_keypair_file)
.map_err(|err| format!("Unable to read {}: {}", from_keypair_file, err))?;
.map_err(|err| format!("Unable to read {from_keypair_file}: {err}"))?;
let update_manifest_keypair = read_keypair_file(update_manifest_keypair_file)
.map_err(|err| format!("Unable to read {}: {}", update_manifest_keypair_file, err))?;
.map_err(|err| format!("Unable to read {update_manifest_keypair_file}: {err}"))?;
println_name_value("JSON RPC URL:", json_rpc_url);
println_name_value(
@ -706,23 +706,20 @@ pub fn deploy(
// Confirm the `json_rpc_url` is good and that `from_keypair` is a valid account
let rpc_client = RpcClient::new(json_rpc_url.to_string());
let progress_bar = new_spinner_progress_bar();
progress_bar.set_message(format!("{}Checking cluster...", LOOKING_GLASS));
progress_bar.set_message(format!("{LOOKING_GLASS}Checking cluster..."));
let balance = rpc_client
.get_balance(&from_keypair.pubkey())
.map_err(|err| {
format!(
"Unable to get the account balance of {}: {}",
from_keypair_file, err
)
format!("Unable to get the account balance of {from_keypair_file}: {err}")
})?;
progress_bar.finish_and_clear();
if balance == 0 {
return Err(format!("{} account balance is empty", from_keypair_file));
return Err(format!("{from_keypair_file} account balance is empty"));
}
// Download the release
let (temp_dir, temp_archive, temp_archive_sha256) = download_to_temp(download_url, None)
.map_err(|err| format!("Unable to download {}: {}", download_url, err))?;
.map_err(|err| format!("Unable to download {download_url}: {err}"))?;
if let Ok(update_manifest) = get_update_manifest(&rpc_client, &update_manifest_keypair.pubkey())
{
@ -739,23 +736,16 @@ pub fn deploy(
// Extract it and load the release version metadata
let temp_release_dir = temp_dir.path().join("archive");
extract_release_archive(&temp_archive, &temp_release_dir).map_err(|err| {
format!(
"Unable to extract {:?} into {:?}: {}",
temp_archive, temp_release_dir, err
)
format!("Unable to extract {temp_archive:?} into {temp_release_dir:?}: {err}")
})?;
let release_target = load_release_target(&temp_release_dir).map_err(|err| {
format!(
"Unable to load release target from {:?}: {}",
temp_release_dir, err
)
})?;
let release_target = load_release_target(&temp_release_dir)
.map_err(|err| format!("Unable to load release target from {temp_release_dir:?}: {err}"))?;
println_name_value("Update target:", &release_target);
let progress_bar = new_spinner_progress_bar();
progress_bar.set_message(format!("{}Deploying update...", PACKAGE));
progress_bar.set_message(format!("{PACKAGE}Deploying update..."));
// Construct an update manifest for the release
let mut update_manifest = SignedUpdateManifest {
@ -772,14 +762,14 @@ pub fn deploy(
// Store the new update manifest on the cluster
new_update_manifest(&rpc_client, &from_keypair, &update_manifest_keypair)
.map_err(|err| format!("Unable to create update manifest: {}", err))?;
.map_err(|err| format!("Unable to create update manifest: {err}"))?;
store_update_manifest(
&rpc_client,
&from_keypair,
&update_manifest_keypair,
&update_manifest,
)
.map_err(|err| format!("Unable to store update manifest: {:?}", err))?;
.map_err(|err| format!("Unable to store update manifest: {err:?}"))?;
progress_bar.finish_and_clear();
println!(" {}{}", SPARKLE, style("Deployment successful").bold());
@ -838,7 +828,7 @@ pub fn gc(config_file: &str) -> Result<(), String> {
.expect("ProgresStyle::template direct input to be correct")
.progress_chars("=> "),
);
progress_bar.set_message(format!("{}Removing old releases", RECYCLING));
progress_bar.set_message(format!("{RECYCLING}Removing old releases"));
for (release, _modified_type) in old_releases {
progress_bar.inc(1);
let _ = fs::remove_dir_all(release);
@ -884,8 +874,8 @@ fn check_for_newer_github_release(
let url = reqwest::Url::parse_with_params(
"https://api.github.com/repos/solana-labs/solana/releases",
&[
("per_page", &format!("{}", PER_PAGE)),
("page", &format!("{}", page)),
("per_page", &format!("{PER_PAGE}")),
("page", &format!("{page}")),
],
)
.unwrap();
@ -947,7 +937,7 @@ pub fn init_or_update(config_file: &str, is_init: bool, check_only: bool) -> Res
match explicit_release {
ExplicitRelease::Semver(current_release_semver) => {
let progress_bar = new_spinner_progress_bar();
progress_bar.set_message(format!("{}Checking for updates...", LOOKING_GLASS));
progress_bar.set_message(format!("{LOOKING_GLASS}Checking for updates..."));
let github_release = check_for_newer_github_release(
semver::VersionReq::parse(&format!(
@ -967,19 +957,18 @@ pub fn init_or_update(config_file: &str, is_init: bool, check_only: bool) -> Res
match github_release {
None => {
return Err(format!("Unknown release: {}", current_release_semver));
return Err(format!("Unknown release: {current_release_semver}"));
}
Some(release_semver) => {
if release_semver == *current_release_semver {
if let Ok(active_release_version) = load_release_version(
&config.active_release_dir().join("version.yml"),
) {
if format!("v{}", current_release_semver)
if format!("v{current_release_semver}")
== active_release_version.channel
{
println!(
"Install is up to date. {} is the latest compatible release",
release_semver
"Install is up to date. {release_semver} is the latest compatible release"
);
return Ok(false);
}
@ -1004,7 +993,7 @@ pub fn init_or_update(config_file: &str, is_init: bool, check_only: bool) -> Res
let (_temp_dir, temp_file, _temp_archive_sha256) =
download_to_temp(&version_url, None)
.map_err(|err| format!("Unable to download {}: {}", version_url, err))?;
.map_err(|err| format!("Unable to download {version_url}: {err}"))?;
let update_release_version = load_release_version(&temp_file)?;
@ -1069,7 +1058,7 @@ pub fn init_or_update(config_file: &str, is_init: bool, check_only: bool) -> Res
}
} else {
let progress_bar = new_spinner_progress_bar();
progress_bar.set_message(format!("{}Checking for updates...", LOOKING_GLASS));
progress_bar.set_message(format!("{LOOKING_GLASS}Checking for updates..."));
let rpc_client = RpcClient::new(config.json_rpc_url.clone());
let update_manifest = get_update_manifest(&rpc_client, &config.update_manifest_pubkey)?;
progress_bar.finish_and_clear();
@ -1111,7 +1100,7 @@ pub fn init_or_update(config_file: &str, is_init: bool, check_only: bool) -> Res
println!(
" {}{}",
WRAPPED_PRESENT,
style(format!("Update available: {}", updated_version)).bold()
style(format!("Update available: {updated_version}")).bold()
);
return Ok(true);
}
@ -1119,24 +1108,17 @@ pub fn init_or_update(config_file: &str, is_init: bool, check_only: bool) -> Res
if let Some((download_url, archive_sha256)) = download_url_and_sha256 {
let (_temp_dir, temp_archive, _temp_archive_sha256) =
download_to_temp(&download_url, archive_sha256.as_ref())
.map_err(|err| format!("Unable to download {}: {}", download_url, err))?;
.map_err(|err| format!("Unable to download {download_url}: {err}"))?;
extract_release_archive(&temp_archive, &release_dir).map_err(|err| {
format!(
"Unable to extract {:?} to {:?}: {}",
temp_archive, release_dir, err
)
format!("Unable to extract {temp_archive:?} to {release_dir:?}: {err}")
})?;
}
let release_target = load_release_target(&release_dir).map_err(|err| {
format!(
"Unable to load release target from {:?}: {}",
release_dir, err
)
})?;
let release_target = load_release_target(&release_dir)
.map_err(|err| format!("Unable to load release target from {release_dir:?}: {err}"))?;
if release_target != crate::build_env::TARGET {
return Err(format!("Incompatible update target: {}", release_target));
return Err(format!("Incompatible update target: {release_target}"));
}
// Trigger an update to the modification time for `release_dir`
@ -1167,13 +1149,13 @@ pub fn init_or_update(config_file: &str, is_init: bool, check_only: bool) -> Res
println!(
" {}{}",
SPARKLE,
style(format!("{} initialized", updated_version)).bold()
style(format!("{updated_version} initialized")).bold()
);
} else {
println!(
" {}{}",
SPARKLE,
style(format!("Update successful to {}", updated_version)).bold()
style(format!("Update successful to {updated_version}")).bold()
);
}
Ok(true)
@ -1212,14 +1194,14 @@ pub fn run(
Some(mut child) => match child.try_wait() {
Ok(Some(status)) => {
println_name_value(
&format!("{} exited with:", program_name),
&format!("{program_name} exited with:"),
&status.to_string(),
);
None
}
Ok(None) => Some(child),
Err(err) => {
eprintln!("Error attempting to wait for program to exit: {}", err);
eprintln!("Error attempting to wait for program to exit: {err}");
None
}
},
@ -1230,7 +1212,7 @@ pub fn run(
{
Ok(child) => Some(child),
Err(err) => {
eprintln!("Failed to spawn {}: {:?}", program_name, err);
eprintln!("Failed to spawn {program_name}: {err:?}");
None
}
}
@ -1243,13 +1225,13 @@ pub fn run(
// Update successful, kill current process so it will be restart
if let Some(ref mut child) = child_option {
stop_process(child).unwrap_or_else(|err| {
eprintln!("Failed to stop child: {:?}", err);
eprintln!("Failed to stop child: {err:?}");
});
}
}
Ok(false) => {} // No update available
Err(err) => {
eprintln!("Failed to apply update: {:?}", err);
eprintln!("Failed to apply update: {err:?}");
}
};
now = Instant::now();
@ -1259,7 +1241,7 @@ pub fn run(
// Handle SIGTERM...
if let Some(ref mut child) = child_option {
stop_process(child).unwrap_or_else(|err| {
eprintln!("Failed to stop child: {:?}", err);
eprintln!("Failed to stop child: {err:?}");
});
}
std::process::exit(0);

View File

@ -47,17 +47,17 @@ impl Config {
fn _load(config_file: &str) -> Result<Self, io::Error> {
let file = File::open(config_file)?;
let config = serde_yaml::from_reader(file)
.map_err(|err| io::Error::new(io::ErrorKind::Other, format!("{:?}", err)))?;
.map_err(|err| io::Error::new(io::ErrorKind::Other, format!("{err:?}")))?;
Ok(config)
}
pub fn load(config_file: &str) -> Result<Self, String> {
Self::_load(config_file).map_err(|err| format!("Unable to load {}: {:?}", config_file, err))
Self::_load(config_file).map_err(|err| format!("Unable to load {config_file}: {err:?}"))
}
fn _save(&self, config_file: &str) -> Result<(), io::Error> {
let serialized = serde_yaml::to_string(self)
.map_err(|err| io::Error::new(io::ErrorKind::Other, format!("{:?}", err)))?;
.map_err(|err| io::Error::new(io::ErrorKind::Other, format!("{err:?}")))?;
if let Some(outdir) = Path::new(&config_file).parent() {
create_dir_all(outdir)?;
@ -71,7 +71,7 @@ impl Config {
pub fn save(&self, config_file: &str) -> Result<(), String> {
self._save(config_file)
.map_err(|err| format!("Unable to save {}: {:?}", config_file, err))
.map_err(|err| format!("Unable to save {config_file}: {err:?}"))
}
pub fn active_release_dir(&self) -> &PathBuf {
@ -104,7 +104,7 @@ mod test {
let json_rpc_url = "https://api.mainnet-beta.solana.com";
let pubkey = Pubkey::default();
let config_name = "config.yaml";
let config_path = format!("{}/{}", root_dir, config_name);
let config_path = format!("{root_dir}/{config_name}");
let config = Config::new(&root_dir, json_rpc_url, &pubkey, None);
@ -154,10 +154,9 @@ update_manifest_pubkey:
current_update_manifest: null
update_poll_secs: 3600
explicit_release: null
releases_dir: {}/releases
active_release_dir: {}/active_release
",
root_dir, root_dir
releases_dir: {root_dir}/releases
active_release_dir: {root_dir}/active_release
"
),
);
}

View File

@ -20,14 +20,14 @@ mod update_manifest;
pub fn is_semver(semver: &str) -> Result<(), String> {
match semver::Version::parse(semver) {
Ok(_) => Ok(()),
Err(err) => Err(format!("{:?}", err)),
Err(err) => Err(format!("{err:?}")),
}
}
pub fn is_release_channel(channel: &str) -> Result<(), String> {
match channel {
"edge" | "beta" | "stable" => Ok(()),
_ => Err(format!("Invalid release channel {}", channel)),
_ => Err(format!("Invalid release channel {channel}")),
}
}

View File

@ -45,25 +45,25 @@ pub fn stop_process(process: &mut Child) -> Result<(), io::Error> {
}
}
Err(EINVAL) => {
println!("Invalid signal. Killing process {}", pid);
println!("Invalid signal. Killing process {pid}");
kill_process(process)?;
}
Err(EPERM) => {
return Err(io::Error::new(
ErrorKind::InvalidInput,
format!("Insufficient permissions to signal process {}", pid),
format!("Insufficient permissions to signal process {pid}"),
));
}
Err(ESRCH) => {
return Err(io::Error::new(
ErrorKind::InvalidInput,
format!("Process {} does not exist", pid),
format!("Process {pid} does not exist"),
));
}
Err(e) => {
return Err(io::Error::new(
ErrorKind::InvalidInput,
format!("Unexpected error {}", e),
format!("Unexpected error {e}"),
));
}
};

View File

@ -127,7 +127,7 @@ impl KeyGenerationCommonArgs for Command<'_> {
fn check_for_overwrite(outfile: &str, matches: &ArgMatches) {
let force = matches.is_present("force");
if !force && Path::new(outfile).exists() {
eprintln!("Refusing to overwrite {} without --force flag", outfile);
eprintln!("Refusing to overwrite {outfile} without --force flag");
exit(1);
}
}
@ -159,7 +159,7 @@ fn output_keypair(
write_keypair(keypair, &mut stdout)?;
} else {
write_keypair_file(keypair, outfile)?;
println!("Wrote {} keypair to {}", source, outfile);
println!("Wrote {source} keypair to {outfile}");
}
Ok(())
}
@ -254,7 +254,7 @@ fn acquire_passphrase_and_message(
}
fn grind_print_info(grind_matches: &[GrindMatch], num_threads: usize) {
println!("Searching with {} threads for:", num_threads);
println!("Searching with {num_threads} threads for:");
for gm in grind_matches {
let mut msg = Vec::<String>::new();
if gm.count.load(Ordering::Relaxed) > 1 {
@ -587,7 +587,7 @@ fn do_main(matches: &ArgMatches) -> Result<(), Box<dyn error::Error>> {
check_for_overwrite(outfile, matches);
write_pubkey_file(outfile, pubkey)?;
} else {
println!("{}", pubkey);
println!("{pubkey}");
}
}
("new", matches) => {
@ -629,7 +629,7 @@ fn do_main(matches: &ArgMatches) -> Result<(), Box<dyn error::Error>> {
if let Some(outfile) = outfile {
output_keypair(&keypair, outfile, "new")
.map_err(|err| format!("Unable to write {}: {}", outfile, err))?;
.map_err(|err| format!("Unable to write {outfile}: {err}"))?;
}
if !silent {
@ -840,9 +840,9 @@ fn do_main(matches: &ArgMatches) -> Result<(), Box<dyn error::Error>> {
let pubkey_bs58 = matches.value_of("pubkey").unwrap();
let pubkey = bs58::decode(pubkey_bs58).into_vec().unwrap();
if signature.verify(&pubkey, &simple_message) {
println!("Verification for public key: {}: Success", pubkey_bs58);
println!("Verification for public key: {pubkey_bs58}: Success");
} else {
println!("Verification for public key: {}: Failed", pubkey_bs58);
println!("Verification for public key: {pubkey_bs58}: Failed");
exit(1);
}
}

View File

@ -45,7 +45,7 @@ async fn upload(
) -> Result<(), Box<dyn std::error::Error>> {
let bigtable = solana_storage_bigtable::LedgerStorage::new_with_config(config)
.await
.map_err(|err| format!("Failed to connect to storage: {:?}", err))?;
.map_err(|err| format!("Failed to connect to storage: {err:?}"))?;
let config = ConfirmedBlockUploadConfig {
force_reupload,
@ -83,7 +83,7 @@ async fn delete_slots(
let dry_run = config.read_only;
let bigtable = solana_storage_bigtable::LedgerStorage::new_with_config(config)
.await
.map_err(|err| format!("Failed to connect to storage: {:?}", err))?;
.map_err(|err| format!("Failed to connect to storage: {err:?}"))?;
solana_ledger::bigtable_delete::delete_confirmed_blocks(bigtable, slots, dry_run).await
}
@ -93,7 +93,7 @@ async fn first_available_block(
) -> Result<(), Box<dyn std::error::Error>> {
let bigtable = solana_storage_bigtable::LedgerStorage::new_with_config(config).await?;
match bigtable.get_first_available_block().await? {
Some(block) => println!("{}", block),
Some(block) => println!("{block}"),
None => println!("No blocks available"),
}
@ -107,7 +107,7 @@ async fn block(
) -> Result<(), Box<dyn std::error::Error>> {
let bigtable = solana_storage_bigtable::LedgerStorage::new_with_config(config)
.await
.map_err(|err| format!("Failed to connect to storage: {:?}", err))?;
.map_err(|err| format!("Failed to connect to storage: {err:?}"))?;
let confirmed_block = bigtable.get_confirmed_block(slot).await?;
let encoded_block = confirmed_block
@ -121,10 +121,7 @@ async fn block(
)
.map_err(|err| match err {
EncodeError::UnsupportedTransactionVersion(version) => {
format!(
"Failed to process unsupported transaction version ({}) in block",
version
)
format!("Failed to process unsupported transaction version ({version}) in block")
}
})?;
@ -143,10 +140,10 @@ async fn blocks(
) -> Result<(), Box<dyn std::error::Error>> {
let bigtable = solana_storage_bigtable::LedgerStorage::new_with_config(config)
.await
.map_err(|err| format!("Failed to connect to storage: {:?}", err))?;
.map_err(|err| format!("Failed to connect to storage: {err:?}"))?;
let slots = bigtable.get_confirmed_blocks(starting_slot, limit).await?;
println!("{:?}", slots);
println!("{slots:?}");
println!("{} blocks found", slots.len());
Ok(())
@ -160,7 +157,7 @@ async fn compare_blocks(
) -> Result<(), Box<dyn std::error::Error>> {
let owned_bigtable = solana_storage_bigtable::LedgerStorage::new_with_config(config)
.await
.map_err(|err| format!("failed to connect to owned bigtable: {:?}", err))?;
.map_err(|err| format!("failed to connect to owned bigtable: {err:?}"))?;
let owned_bigtable_slots = owned_bigtable
.get_confirmed_blocks(starting_slot, limit)
.await?;
@ -170,7 +167,7 @@ async fn compare_blocks(
);
let reference_bigtable = solana_storage_bigtable::LedgerStorage::new_with_config(ref_config)
.await
.map_err(|err| format!("failed to connect to reference bigtable: {:?}", err))?;
.map_err(|err| format!("failed to connect to reference bigtable: {err:?}"))?;
let reference_bigtable_slots = reference_bigtable
.get_confirmed_blocks(starting_slot, limit)
@ -201,7 +198,7 @@ async fn confirm(
) -> Result<(), Box<dyn std::error::Error>> {
let bigtable = solana_storage_bigtable::LedgerStorage::new_with_config(config)
.await
.map_err(|err| format!("Failed to connect to storage: {:?}", err))?;
.map_err(|err| format!("Failed to connect to storage: {err:?}"))?;
let transaction_status = bigtable.get_signature_status(signature).await?;
@ -227,7 +224,7 @@ async fn confirm(
}
Ok(None) => {}
Err(err) => {
get_transaction_error = Some(format!("{:?}", err));
get_transaction_error = Some(format!("{err:?}"));
}
}
}
@ -280,7 +277,7 @@ pub async fn transaction_history(
result.memo.unwrap_or_default(),
match result.err {
None => "Confirmed".to_string(),
Some(err) => format!("Failed: {:?}", err),
Some(err) => format!("Failed: {err:?}"),
}
);
} else {
@ -321,7 +318,7 @@ pub async fn transaction_history(
}
match bigtable.get_confirmed_block(result.slot).await {
Err(err) => {
println!(" Unable to get confirmed transaction details: {}", err);
println!(" Unable to get confirmed transaction details: {err}");
break;
}
Ok(confirmed_block) => {
@ -786,7 +783,7 @@ pub fn bigtable_process_command(
};
future.unwrap_or_else(|err| {
eprintln!("{:?}", err);
eprintln!("{err:?}");
exit(1);
});
}

View File

@ -140,7 +140,7 @@ fn output_slot_rewards(blockstore: &Blockstore, slot: Slot, method: &LedgerOutpu
" {:<44} {:^15} {}◎{:<14.9} ◎{:<18.9} {}",
reward.pubkey,
if let Some(reward_type) = reward.reward_type {
format!("{}", reward_type)
format!("{reward_type}")
} else {
"-".to_string()
},
@ -149,7 +149,7 @@ fn output_slot_rewards(blockstore: &Blockstore, slot: Slot, method: &LedgerOutpu
lamports_to_sol(reward.post_balance),
reward
.commission
.map(|commission| format!("{:>9}%", commission))
.map(|commission| format!("{commission:>9}%"))
.unwrap_or_else(|| " -".to_string())
);
}
@ -175,7 +175,7 @@ fn output_entry(
entry.transactions.len()
);
for (transactions_index, transaction) in entry.transactions.into_iter().enumerate() {
println!(" Transaction {}", transactions_index);
println!(" Transaction {transactions_index}");
let tx_signature = transaction.signatures[0];
let tx_status_meta = blockstore
.read_transaction_status((tx_signature, slot))
@ -225,12 +225,12 @@ fn output_slot(
let (entries, num_shreds, is_full) = blockstore
.get_slot_entries_with_shred_info(slot, 0, allow_dead_slots)
.map_err(|err| format!("Failed to load entries for slot {}: {:?}", slot, err))?;
.map_err(|err| format!("Failed to load entries for slot {slot}: {err:?}"))?;
if *method == LedgerOutputMethod::Print {
if let Ok(Some(meta)) = blockstore.meta(slot) {
if verbose_level >= 1 {
println!(" {:?} is_full: {}", meta, is_full);
println!(" {meta:?} is_full: {is_full}");
} else {
println!(
" num_shreds: {}, parent_slot: {:?}, next_slots: {:?}, num_entries: {}, is_full: {}",
@ -289,10 +289,7 @@ fn output_slot(
}
}
println!(
" Transactions: {}, hashes: {}, block_hash: {}",
transactions, num_hashes, blockhash,
);
println!(" Transactions: {transactions}, hashes: {num_hashes}, block_hash: {blockhash}",);
for (pubkey, count) in program_ids.iter() {
*all_program_ids.entry(*pubkey).or_insert(0) += count;
}
@ -315,10 +312,7 @@ fn output_ledger(
let slot_iterator = blockstore
.slot_meta_iterator(starting_slot)
.unwrap_or_else(|err| {
eprintln!(
"Failed to load entries starting from slot {}: {:?}",
starting_slot, err
);
eprintln!("Failed to load entries starting from slot {starting_slot}: {err:?}");
exit(1);
});
@ -355,7 +349,7 @@ fn output_ledger(
verbose_level,
&mut all_program_ids,
) {
eprintln!("{}", err);
eprintln!("{err}");
}
num_printed += 1;
if num_printed >= num_slots as usize {
@ -387,12 +381,12 @@ fn output_account(
print_account_data: bool,
encoding: UiAccountEncoding,
) {
println!("{}:", pubkey);
println!("{pubkey}:");
println!(" balance: {} SOL", lamports_to_sol(account.lamports()));
println!(" owner: '{}'", account.owner());
println!(" executable: {}", account.executable());
if let Some(slot) = modified_slot {
println!(" slot: {}", slot);
println!(" slot: {slot}");
}
println!(" rent_epoch: {}", account.rent_epoch());
println!(" data_len: {}", account.data().len());
@ -400,7 +394,7 @@ fn output_account(
let account_data = UiAccount::encode(pubkey, account, encoding, None, None).data;
match account_data {
UiAccountData::Binary(data, data_encoding) => {
println!(" data: '{}'", data);
println!(" data: '{data}'");
println!(
" encoding: {}",
serde_json::to_string(&data_encoding).unwrap()
@ -420,12 +414,12 @@ fn output_account(
fn render_dot(dot: String, output_file: &str, output_format: &str) -> io::Result<()> {
let mut child = Command::new("dot")
.arg(format!("-T{}", output_format))
.arg(format!("-o{}", output_file))
.arg(format!("-T{output_format}"))
.arg(format!("-o{output_file}"))
.stdin(Stdio::piped())
.spawn()
.map_err(|err| {
eprintln!("Failed to spawn dot: {:?}", err);
eprintln!("Failed to spawn dot: {err:?}");
err
})?;
@ -944,7 +938,7 @@ fn open_blockstore(
})
}
Err(err) => {
eprintln!("Failed to open blockstore at {:?}: {:?}", ledger_path, err);
eprintln!("Failed to open blockstore at {ledger_path:?}: {err:?}");
exit(1);
}
}
@ -988,10 +982,10 @@ fn print_blockstore_file_metadata(
) -> Result<(), String> {
let live_files = blockstore
.live_files_metadata()
.map_err(|err| format!("{:?}", err))?;
.map_err(|err| format!("{err:?}"))?;
// All files under live_files_metadata are prefixed with "/".
let sst_file_name = file_name.as_ref().map(|name| format!("/{}", name));
let sst_file_name = file_name.as_ref().map(|name| format!("/{name}"));
for file in live_files {
if sst_file_name.is_none() || file.name.eq(sst_file_name.as_ref().unwrap()) {
println!(
@ -1011,8 +1005,7 @@ fn print_blockstore_file_metadata(
}
if sst_file_name.is_some() {
return Err(format!(
"Failed to find or load the metadata of the specified file {:?}",
file_name
"Failed to find or load the metadata of the specified file {file_name:?}"
));
}
Ok(())
@ -1075,10 +1068,7 @@ fn load_bank_forks(
// Check if we have the slot data necessary to replay from starting_slot to >= halt_slot.
// - This will not catch the case when loading from genesis without a full slot 0.
if !blockstore.slot_range_connected(starting_slot, halt_slot) {
eprintln!(
"Unable to load bank forks at slot {} due to disconnected blocks.",
halt_slot,
);
eprintln!("Unable to load bank forks at slot {halt_slot} due to disconnected blocks.",);
exit(1);
}
}
@ -1123,7 +1113,7 @@ fn load_bank_forks(
let geyser_service =
GeyserPluginService::new(confirmed_bank_receiver, &geyser_config_files).unwrap_or_else(
|err| {
eprintln!("Failed to setup Geyser service: {:?}", err);
eprintln!("Failed to setup Geyser service: {err:?}");
exit(1);
},
);
@ -1195,7 +1185,7 @@ fn compute_slot_cost(blockstore: &Blockstore, slot: Slot) -> Result<(), String>
let (entries, _num_shreds, _is_full) = blockstore
.get_slot_entries_with_shred_info(slot, 0, false)
.map_err(|err| format!(" Slot: {}, Failed to load entries, err {:?}", slot, err))?;
.map_err(|err| format!(" Slot: {slot}, Failed to load entries, err {err:?}"))?;
let num_entries = entries.len();
let mut num_transactions = 0;
@ -1229,8 +1219,7 @@ fn compute_slot_cost(blockstore: &Blockstore, slot: Slot) -> Result<(), String>
let result = cost_tracker.try_add(&tx_cost);
if result.is_err() {
println!(
"Slot: {}, CostModel rejected transaction {:?}, reason {:?}",
slot, transaction, result,
"Slot: {slot}, CostModel rejected transaction {transaction:?}, reason {result:?}",
);
}
for (program_id, _instruction) in transaction.message().program_instructions_iter()
@ -1241,10 +1230,9 @@ fn compute_slot_cost(blockstore: &Blockstore, slot: Slot) -> Result<(), String>
}
println!(
"Slot: {}, Entries: {}, Transactions: {}, Programs {}",
slot, num_entries, num_transactions, num_programs,
"Slot: {slot}, Entries: {num_entries}, Transactions: {num_transactions}, Programs {num_programs}",
);
println!(" Programs: {:?}", program_ids);
println!(" Programs: {program_ids:?}");
Ok(())
}
@ -1868,8 +1856,7 @@ fn main() {
Ok(())
} else {
Err(format!(
"Unable to parse as a number or the keyword ROOT, provided: {}",
value
"Unable to parse as a number or the keyword ROOT, provided: {value}"
))
}
})
@ -2312,8 +2299,7 @@ fn main() {
"Shred storage type of target_db cannot be inferred, \
the default RocksLevel will be used. \
If you want to use FIFO shred_storage_type on an empty target_db, \
create {} foldar the specified target_db directory.",
BLOCKSTORE_DIRECTORY_ROCKS_FIFO,
create {BLOCKSTORE_DIRECTORY_ROCKS_FIFO} foldar the specified target_db directory.",
),
);
@ -2358,7 +2344,7 @@ fn main() {
);
}
} else {
println!("{}", genesis_config);
println!("{genesis_config}");
}
}
("genesis-hash", Some(arg_matches)) => {
@ -2391,7 +2377,7 @@ fn main() {
LedgerColumnOptions::default(),
)
.unwrap_or_else(|err| {
eprintln!("Failed to write genesis config: {:?}", err);
eprintln!("Failed to write genesis config: {err:?}");
exit(1);
});
@ -2438,7 +2424,7 @@ fn main() {
);
}
Err(err) => {
eprintln!("Failed to load ledger: {:?}", err);
eprintln!("Failed to load ledger: {err:?}");
exit(1);
}
}
@ -2517,7 +2503,7 @@ fn main() {
println!("{}", &bank_forks.read().unwrap().working_bank().hash());
}
Err(err) => {
eprintln!("Failed to load ledger: {:?}", err);
eprintln!("Failed to load ledger: {err:?}");
exit(1);
}
}
@ -2533,7 +2519,7 @@ fn main() {
force_update_to_open,
);
for slot in slots {
println!("Slot {}", slot);
println!("Slot {slot}");
if let Err(err) = output_slot(
&blockstore,
slot,
@ -2542,7 +2528,7 @@ fn main() {
verbose_level,
&mut HashMap::new(),
) {
eprintln!("{}", err);
eprintln!("{err}");
}
}
}
@ -2576,7 +2562,7 @@ fn main() {
);
let starting_slot = value_t_or_exit!(arg_matches, "starting_slot", Slot);
for slot in blockstore.dead_slots_iterator(starting_slot).unwrap() {
println!("{}", slot);
println!("{slot}");
}
}
("duplicate-slots", Some(arg_matches)) => {
@ -2589,7 +2575,7 @@ fn main() {
);
let starting_slot = value_t_or_exit!(arg_matches, "starting_slot", Slot);
for slot in blockstore.duplicate_slots_iterator(starting_slot).unwrap() {
println!("{}", slot);
println!("{slot}");
}
}
("set-dead-slot", Some(arg_matches)) => {
@ -2603,8 +2589,8 @@ fn main() {
);
for slot in slots {
match blockstore.set_dead_slot(slot) {
Ok(_) => println!("Slot {} dead", slot),
Err(err) => eprintln!("Failed to set slot {} dead slot: {:?}", slot, err),
Ok(_) => println!("Slot {slot} dead"),
Err(err) => eprintln!("Failed to set slot {slot} dead slot: {err:?}"),
}
}
}
@ -2619,9 +2605,9 @@ fn main() {
);
for slot in slots {
match blockstore.remove_dead_slot(slot) {
Ok(_) => println!("Slot {} not longer marked dead", slot),
Ok(_) => println!("Slot {slot} not longer marked dead"),
Err(err) => {
eprintln!("Failed to remove dead flag for slot {}, {:?}", slot, err)
eprintln!("Failed to remove dead flag for slot {slot}, {err:?}")
}
}
}
@ -2690,10 +2676,7 @@ fn main() {
for ((slot1, frozen_log), (slot2, full_log)) in frozen.iter().zip(full.iter()) {
assert_eq!(slot1, slot2);
println!(
"Slot: {}\n, full: {}\n, frozen: {}",
slot1, full_log, frozen_log
);
println!("Slot: {slot1}\n, full: {full_log}\n, frozen: {frozen_log}");
}
}
("verify", Some(arg_matches)) => {
@ -2819,7 +2802,7 @@ fn main() {
incremental_snapshot_archive_path,
)
.unwrap_or_else(|err| {
eprintln!("Ledger verification failed: {:?}", err);
eprintln!("Ledger verification failed: {err:?}");
exit(1);
});
if print_accounts_stats {
@ -2877,12 +2860,12 @@ fn main() {
};
match result {
Ok(_) => println!("Wrote {}", output_file),
Err(err) => eprintln!("Unable to write {}: {}", output_file, err),
Ok(_) => println!("Wrote {output_file}"),
Err(err) => eprintln!("Unable to write {output_file}: {err}"),
}
}
Err(err) => {
eprintln!("Failed to load ledger: {:?}", err);
eprintln!("Failed to load ledger: {err:?}");
exit(1);
}
}
@ -2924,8 +2907,7 @@ fn main() {
if bootstrap_validator_stake_lamports < minimum_stake_lamports {
eprintln!(
"Error: insufficient --bootstrap-validator-stake-lamports. \
Minimum amount is {}",
minimum_stake_lamports
Minimum amount is {minimum_stake_lamports}"
);
exit(1);
}
@ -2941,7 +2923,7 @@ fn main() {
SnapshotVersion::default(),
|s| {
s.parse::<SnapshotVersion>().unwrap_or_else(|e| {
eprintln!("Error: {}", e);
eprintln!("Error: {e}");
exit(1)
})
},
@ -2951,7 +2933,7 @@ fn main() {
let archive_format_str =
value_t_or_exit!(arg_matches, "snapshot_archive_format", String);
ArchiveFormat::from_cli_arg(&archive_format_str).unwrap_or_else(|| {
panic!("Archive format not recognized: {}", archive_format_str)
panic!("Archive format not recognized: {archive_format_str}")
})
};
@ -2988,8 +2970,7 @@ fn main() {
.is_none()
{
eprintln!(
"Error: snapshot slot {} does not exist in blockstore or is not full.",
snapshot_slot,
"Error: snapshot slot {snapshot_slot} does not exist in blockstore or is not full.",
);
exit(1);
}
@ -2998,8 +2979,7 @@ fn main() {
let ending_slot = value_t_or_exit!(arg_matches, "ending_slot", Slot);
if ending_slot <= snapshot_slot {
eprintln!(
"Error: ending_slot ({}) must be greater than snapshot_slot ({})",
ending_slot, snapshot_slot
"Error: ending_slot ({ending_slot}) must be greater than snapshot_slot ({snapshot_slot})"
);
exit(1);
}
@ -3057,7 +3037,7 @@ fn main() {
.unwrap()
.get(snapshot_slot)
.unwrap_or_else(|| {
eprintln!("Error: Slot {} is not available", snapshot_slot);
eprintln!("Error: Slot {snapshot_slot} is not available");
exit(1);
});
@ -3110,8 +3090,7 @@ fn main() {
for address in accounts_to_remove {
let mut account = bank.get_account(&address).unwrap_or_else(|| {
eprintln!(
"Error: Account does not exist, unable to remove it: {}",
address
"Error: Account does not exist, unable to remove it: {address}"
);
exit(1);
});
@ -3227,8 +3206,7 @@ fn main() {
if let Some(warp_slot) = warp_slot {
if warp_slot < minimum_warp_slot {
eprintln!(
"Error: --warp-slot too close. Must be >= {}",
minimum_warp_slot
"Error: --warp-slot too close. Must be >= {minimum_warp_slot}"
);
exit(1);
}
@ -3300,7 +3278,7 @@ fn main() {
maximum_incremental_snapshot_archives_to_retain,
)
.unwrap_or_else(|err| {
eprintln!("Unable to create incremental snapshot: {}", err);
eprintln!("Unable to create incremental snapshot: {err}");
exit(1);
});
@ -3324,7 +3302,7 @@ fn main() {
maximum_incremental_snapshot_archives_to_retain,
)
.unwrap_or_else(|err| {
eprintln!("Unable to create snapshot: {}", err);
eprintln!("Unable to create snapshot: {err}");
exit(1);
});
@ -3355,7 +3333,7 @@ fn main() {
);
}
Err(err) => {
eprintln!("Failed to load ledger: {:?}", err);
eprintln!("Failed to load ledger: {err:?}");
exit(1);
}
}
@ -3386,7 +3364,7 @@ fn main() {
incremental_snapshot_archive_path,
)
.unwrap_or_else(|err| {
eprintln!("Failed to load ledger: {:?}", err);
eprintln!("Failed to load ledger: {err:?}");
exit(1);
});
@ -3447,7 +3425,7 @@ fn main() {
json_serializer.end().unwrap();
}
if summarize {
println!("\n{:#?}", total_accounts_stats);
println!("\n{total_accounts_stats:#?}");
}
}
("capitalization", Some(arg_matches)) => {
@ -3478,7 +3456,7 @@ fn main() {
let bank_forks = bank_forks.read().unwrap();
let slot = bank_forks.working_bank().slot();
let bank = bank_forks.get(slot).unwrap_or_else(|| {
eprintln!("Error: Slot {} is not available", slot);
eprintln!("Error: Slot {slot} is not available");
exit(1);
});
@ -3698,10 +3676,10 @@ fn main() {
}
InflationPointCalculationEvent::Skipped(skipped_reason) => {
if detail.skipped_reasons.is_empty() {
detail.skipped_reasons = format!("{:?}", skipped_reason);
detail.skipped_reasons = format!("{skipped_reason:?}");
} else {
use std::fmt::Write;
let _ = write!(&mut detail.skipped_reasons, "/{:?}", skipped_reason);
let _ = write!(&mut detail.skipped_reasons, "/{skipped_reason:?}");
}
}
}
@ -3806,7 +3784,7 @@ fn main() {
detail_ref.as_ref().map(|detail_ref| detail_ref.value());
println!(
"{:<45}({}): {} => {} (+{} {:>4.9}%) {:?}",
format!("{}", pubkey), // format! is needed to pad/justify correctly.
format!("{pubkey}"), // format! is needed to pad/justify correctly.
base_account.owner(),
Sol(base_account.lamports()),
Sol(warped_account.lamports()),
@ -3853,7 +3831,7 @@ fn main() {
fn format_or_na<T: std::fmt::Display>(
data: Option<T>,
) -> String {
data.map(|data| format!("{}", data))
data.map(|data| format!("{data}"))
.unwrap_or_else(|| "N/A".to_owned())
}
let mut point_details = detail
@ -3872,7 +3850,7 @@ fn main() {
base_bank.cluster_type()
),
rewarded_epoch: base_bank.epoch(),
account: format!("{}", pubkey),
account: format!("{pubkey}"),
owner: format!("{}", base_account.owner()),
old_balance: base_account.lamports(),
new_balance: warped_account.lamports(),
@ -3979,7 +3957,7 @@ fn main() {
}
}
Err(err) => {
eprintln!("Failed to load ledger: {:?}", err);
eprintln!("Failed to load ledger: {err:?}");
exit(1);
}
}
@ -4015,17 +3993,14 @@ fn main() {
*slots.last().unwrap()
}
Err(err) => {
eprintln!("Unable to read the Ledger: {:?}", err);
eprintln!("Unable to read the Ledger: {err:?}");
exit(1);
}
},
};
if end_slot < start_slot {
eprintln!(
"end slot {} is less than start slot {}",
end_slot, start_slot
);
eprintln!("end slot {end_slot} is less than start slot {start_slot}");
exit(1);
}
info!(
@ -4134,7 +4109,7 @@ fn main() {
.for_each(|(i, (slot, hash))| {
if i < num_roots {
output_file
.write_all(format!("{:?}: {:?}\n", slot, hash).as_bytes())
.write_all(format!("{slot:?}: {hash:?}\n").as_bytes())
.expect("failed to write");
}
});
@ -4160,7 +4135,7 @@ fn main() {
let datetime: DateTime<Utc> = t.into();
datetime.to_rfc3339()
};
let hash_str = format!("{}", hash);
let hash_str = format!("{hash}");
println!("{:>20} {:>44} {:>32}", slot, &hash_str, &time_str);
}
}
@ -4188,10 +4163,9 @@ fn main() {
let num_slots = start_root - end_root - 1; // Adjust by one since start_root need not be checked
if arg_matches.is_present("end_root") && num_slots > max_slots {
eprintln!(
"Requested range {} too large, max {}. \
"Requested range {num_slots} too large, max {max_slots}. \
Either adjust `--until` value, or pass a larger `--repair-limit` \
to override the limit",
num_slots, max_slots,
);
exit(1);
}
@ -4203,19 +4177,16 @@ fn main() {
if !roots_to_fix.is_empty() {
eprintln!("{} slots to be rooted", roots_to_fix.len());
for chunk in roots_to_fix.chunks(100) {
eprintln!("{:?}", chunk);
eprintln!("{chunk:?}");
blockstore
.set_roots(roots_to_fix.iter())
.unwrap_or_else(|err| {
eprintln!("Unable to set roots {:?}: {}", roots_to_fix, err);
eprintln!("Unable to set roots {roots_to_fix:?}: {err}");
exit(1);
});
}
} else {
println!(
"No missing roots found in range {} to {}",
end_root, start_root
);
println!("No missing roots found in range {end_root} to {start_root}");
}
}
("bounds", Some(arg_matches)) => {
@ -4244,10 +4215,10 @@ fn main() {
last
);
if all {
println!("Non-empty slots: {:?}", slots);
println!("Non-empty slots: {slots:?}");
}
} else {
println!("Ledger has data for slot {:?}", first);
println!("Ledger has data for slot {first:?}");
}
}
if let Ok(rooted) = blockstore.rooted_slot_iterator(0) {
@ -4270,16 +4241,15 @@ fn main() {
}
}
println!(
" with {} rooted slots from {:?} to {:?}",
total_rooted, first_rooted, last_rooted
" with {total_rooted} rooted slots from {first_rooted:?} to {last_rooted:?}"
);
println!(" and {} slots past the last root", count_past_root);
println!(" and {count_past_root} slots past the last root");
} else {
println!(" with no rooted slots");
}
}
Err(err) => {
eprintln!("Unable to read the Ledger: {:?}", err);
eprintln!("Unable to read the Ledger: {err:?}");
exit(1);
}
};
@ -4317,7 +4287,7 @@ fn main() {
for slot in slots {
if let Err(err) = compute_slot_cost(&blockstore, slot) {
eprintln!("{}", err);
eprintln!("{err}");
}
}
}
@ -4331,7 +4301,7 @@ fn main() {
);
let sst_file_name = arg_matches.value_of("file_name");
if let Err(err) = print_blockstore_file_metadata(&blockstore, &sst_file_name) {
eprintln!("{}", err);
eprintln!("{err}");
}
}
("", _) => {

View File

@ -46,7 +46,7 @@ pub async fn delete_confirmed_blocks(
measure.stop();
info!("{}", measure);
if failures > 0 {
Err(format!("Incomplete deletion, {} operations failed", failures).into())
Err(format!("Incomplete deletion, {failures} operations failed").into())
} else {
Ok(())
}

View File

@ -55,20 +55,13 @@ pub async fn upload_confirmed_blocks(
let blockstore_slots: Vec<_> = blockstore
.rooted_slot_iterator(starting_slot)
.map_err(|err| {
format!(
"Failed to load entries starting from slot {}: {:?}",
starting_slot, err
)
format!("Failed to load entries starting from slot {starting_slot}: {err:?}")
})?
.map_while(|slot| (slot <= ending_slot).then_some(slot))
.collect();
if blockstore_slots.is_empty() {
return Err(format!(
"Ledger has no slots from {} to {:?}",
starting_slot, ending_slot
)
.into());
return Err(format!("Ledger has no slots from {starting_slot} to {ending_slot:?}").into());
}
let first_blockstore_slot = blockstore_slots.first().unwrap();
@ -274,7 +267,7 @@ pub async fn upload_confirmed_blocks(
);
if failures > 0 {
Err(format!("Incomplete upload, {} operations failed", failures).into())
Err(format!("Incomplete upload, {failures} operations failed").into())
} else {
Ok(last_slot)
}

View File

@ -91,12 +91,12 @@ pub use {
lazy_static! {
static ref PAR_THREAD_POOL: ThreadPool = rayon::ThreadPoolBuilder::new()
.num_threads(get_max_thread_count())
.thread_name(|ix| format!("solBstore{:02}", ix))
.thread_name(|ix| format!("solBstore{ix:02}"))
.build()
.unwrap();
static ref PAR_THREAD_POOL_ALL_CPUS: ThreadPool = rayon::ThreadPoolBuilder::new()
.num_threads(num_cpus::get())
.thread_name(|ix| format!("solBstoreAll{:02}", ix))
.thread_name(|ix| format!("solBstoreAll{ix:02}"))
.build()
.unwrap();
}
@ -468,7 +468,7 @@ impl Blockstore {
(
slot,
deserialize(&slot_meta_bytes).unwrap_or_else(|e| {
panic!("Could not deserialize SlotMeta for slot {}: {:?}", slot, e)
panic!("Could not deserialize SlotMeta for slot {slot}: {e:?}")
}),
)
}))
@ -727,7 +727,7 @@ impl Blockstore {
slot,
erasure_meta,
false,
format!("still need: {}", needed),
format!("still need: {needed}"),
0,
);
}
@ -1452,8 +1452,7 @@ impl Blockstore {
(
"error",
format!(
"Leader {:?}, slot {}: received index {} >= slot.last_index {:?}, shred_source: {:?}",
leader_pubkey, slot, shred_index, last_index, shred_source
"Leader {leader_pubkey:?}, slot {slot}: received index {shred_index} >= slot.last_index {last_index:?}, shred_source: {shred_source:?}"
),
String
)
@ -1601,7 +1600,7 @@ impl Blockstore {
let shred = self.data_shred_cf.get_bytes((slot, index))?;
let shred = shred.map(ShredData::resize_stored_shred).transpose();
shred.map_err(|err| {
let err = format!("Invalid stored shred: {}", err);
let err = format!("Invalid stored shred: {err}");
let err = Box::new(bincode::ErrorKind::Custom(err));
BlockstoreError::InvalidShredData(err)
})
@ -1946,7 +1945,7 @@ impl Blockstore {
let blockhash = slot_entries
.last()
.map(|entry| entry.hash)
.unwrap_or_else(|| panic!("Rooted slot {:?} must have blockhash", slot));
.unwrap_or_else(|| panic!("Rooted slot {slot:?} must have blockhash"));
let slot_transaction_iterator = slot_entries
.into_iter()
.flat_map(|entry| entry.transactions)
@ -2451,7 +2450,7 @@ impl Blockstore {
let block = self.get_complete_block(slot, false).map_err(|err| {
BlockstoreError::Io(IoError::new(
ErrorKind::Other,
format!("Unable to get block: {}", err),
format!("Unable to get block: {err}"),
))
})?;
@ -2915,14 +2914,13 @@ impl Blockstore {
}
return Err(BlockstoreError::InvalidShredData(Box::new(
bincode::ErrorKind::Custom(format!(
"Missing shred for slot {}, index {}",
slot, idx
"Missing shred for slot {slot}, index {idx}"
)),
)));
}
Shred::new_from_serialized_shred(shred_bytes.unwrap()).map_err(|err| {
BlockstoreError::InvalidShredData(Box::new(bincode::ErrorKind::Custom(
format!("Could not reconstruct shred from shred payload: {:?}", err),
format!("Could not reconstruct shred from shred payload: {err:?}"),
)))
})
})
@ -2933,16 +2931,14 @@ impl Blockstore {
let deshred_payload = Shredder::deshred(&data_shreds).map_err(|e| {
BlockstoreError::InvalidShredData(Box::new(bincode::ErrorKind::Custom(format!(
"Could not reconstruct data block from constituent shreds, error: {:?}",
e
"Could not reconstruct data block from constituent shreds, error: {e:?}"
))))
})?;
debug!("{:?} shreds in last FEC set", data_shreds.len(),);
bincode::deserialize::<Vec<Entry>>(&deshred_payload).map_err(|e| {
BlockstoreError::InvalidShredData(Box::new(bincode::ErrorKind::Custom(format!(
"could not reconstruct entries: {:?}",
e
"could not reconstruct entries: {e:?}"
))))
})
}
@ -3933,44 +3929,38 @@ pub fn create_new_ledger(
fs::rename(
ledger_path.join(DEFAULT_GENESIS_ARCHIVE),
ledger_path.join(format!("{}.failed", DEFAULT_GENESIS_ARCHIVE)),
ledger_path.join(format!("{DEFAULT_GENESIS_ARCHIVE}.failed")),
)
.unwrap_or_else(|e| {
let _ = write!(
&mut error_messages,
"/failed to stash problematic {}: {}",
DEFAULT_GENESIS_ARCHIVE, e
"/failed to stash problematic {DEFAULT_GENESIS_ARCHIVE}: {e}"
);
});
fs::rename(
ledger_path.join(DEFAULT_GENESIS_FILE),
ledger_path.join(format!("{}.failed", DEFAULT_GENESIS_FILE)),
ledger_path.join(format!("{DEFAULT_GENESIS_FILE}.failed")),
)
.unwrap_or_else(|e| {
let _ = write!(
&mut error_messages,
"/failed to stash problematic {}: {}",
DEFAULT_GENESIS_FILE, e
"/failed to stash problematic {DEFAULT_GENESIS_FILE}: {e}"
);
});
fs::rename(
ledger_path.join(blockstore_dir),
ledger_path.join(format!("{}.failed", blockstore_dir)),
ledger_path.join(format!("{blockstore_dir}.failed")),
)
.unwrap_or_else(|e| {
let _ = write!(
&mut error_messages,
"/failed to stash problematic {}: {}",
blockstore_dir, e
"/failed to stash problematic {blockstore_dir}: {e}"
);
});
return Err(BlockstoreError::Io(IoError::new(
ErrorKind::Other,
format!(
"Error checking to unpack genesis archive: {}{}",
unpack_err, error_messages
),
format!("Error checking to unpack genesis archive: {unpack_err}{error_messages}"),
)));
}
}
@ -8113,7 +8103,7 @@ pub mod tests {
assert!(sig_infos.found_before);
let results = sig_infos.infos;
assert_eq!(results.len(), 1);
assert_eq!(results[0], all0[i], "Unexpected result for {}", i);
assert_eq!(results[0], all0[i], "Unexpected result for {i}");
}
// Fetch all signatures for address 0 individually using `until`
for i in 0..all0.len() {
@ -8136,7 +8126,7 @@ pub mod tests {
.unwrap()
.infos;
assert_eq!(results.len(), 1);
assert_eq!(results[0], all0[i], "Unexpected result for {}", i);
assert_eq!(results[0], all0[i], "Unexpected result for {i}");
}
let sig_infos = blockstore
@ -8284,7 +8274,7 @@ pub mod tests {
.unwrap()
.infos;
assert_eq!(results.len(), 1);
assert_eq!(results[0], all0[i], "Unexpected result for {}", i);
assert_eq!(results[0], all0[i], "Unexpected result for {i}");
}
// Fetch all signatures for address 0 individually using `until`
for i in 0..all0.len() {
@ -8307,7 +8297,7 @@ pub mod tests {
.unwrap()
.infos;
assert_eq!(results.len(), 1);
assert_eq!(results[0], all0[i], "Unexpected result for {}", i);
assert_eq!(results[0], all0[i], "Unexpected result for {i}");
}
assert!(blockstore
@ -9546,7 +9536,7 @@ pub mod tests {
// Check that each thread processed their task before continuing
for _ in 1..=2 {
let res = signal_receiver.recv().unwrap();
assert!(res.is_ok(), "race condition: {:?}", res);
assert!(res.is_ok(), "race condition: {res:?}");
}
}

View File

@ -56,7 +56,7 @@ impl From<&str> for BlockstoreRecoveryMode {
"absolute_consistency" => BlockstoreRecoveryMode::AbsoluteConsistency,
"point_in_time" => BlockstoreRecoveryMode::PointInTime,
"skip_any_corrupted_record" => BlockstoreRecoveryMode::SkipAnyCorruptedRecord,
bad_mode => panic!("Invalid recovery mode: {}", bad_mode),
bad_mode => panic!("Invalid recovery mode: {bad_mode}"),
}
}
}

View File

@ -110,7 +110,7 @@ struct ReplayEntry {
lazy_static! {
static ref PAR_THREAD_POOL: ThreadPool = rayon::ThreadPoolBuilder::new()
.num_threads(get_max_thread_count())
.thread_name(|ix| format!("solBstoreProc{:02}", ix))
.thread_name(|ix| format!("solBstoreProc{ix:02}"))
.build()
.unwrap();
}
@ -146,7 +146,7 @@ fn get_first_error(
"validator_process_entry_error",
(
"error",
format!("error: {:?}, transaction: {:?}", err, transaction),
format!("error: {err:?}, transaction: {transaction:?}"),
String
)
);
@ -626,8 +626,7 @@ fn process_entries_with_callback(
(
"error",
format!(
"Lock accounts error, entry conflicts with itself, txs: {:?}",
transactions
"Lock accounts error, entry conflicts with itself, txs: {transactions:?}"
),
String
)
@ -869,7 +868,7 @@ pub fn process_blockstore_from_root(
let mut num_slots_processed = 0;
if let Some(start_slot_meta) = blockstore
.meta(start_slot)
.unwrap_or_else(|_| panic!("Failed to get meta for slot {}", start_slot))
.unwrap_or_else(|_| panic!("Failed to get meta for slot {start_slot}"))
{
num_slots_processed = load_frozen_forks(
bank_forks,
@ -4552,10 +4551,7 @@ pub mod tests {
assert_eq!(err, expected_err);
}
(result, expected_result) => {
panic!(
"actual result {:?} != expected result {:?}",
result, expected_result
);
panic!("actual result {result:?} != expected result {expected_result:?}");
}
}
}

View File

@ -24,7 +24,7 @@ use {
lazy_static! {
static ref PAR_THREAD_POOL: ThreadPool = rayon::ThreadPoolBuilder::new()
.num_threads(get_thread_count())
.thread_name(|ix| format!("solShredder{:02}", ix))
.thread_name(|ix| format!("solShredder{ix:02}"))
.build()
.unwrap();
}

View File

@ -26,7 +26,7 @@ const SIGN_SHRED_GPU_MIN: usize = 256;
lazy_static! {
static ref SIGVERIFY_THREAD_POOL: ThreadPool = rayon::ThreadPoolBuilder::new()
.num_threads(get_thread_count())
.thread_name(|ix| format!("solSvrfyShred{:02}", ix))
.thread_name(|ix| format!("solSvrfyShred{ix:02}"))
.build()
.unwrap();
}

View File

@ -118,9 +118,7 @@ impl LocalCluster {
if let Some(max_wait_duration) = max_wait_duration {
assert!(
timer.elapsed() < max_wait_duration,
"Waiting for next {:?} snapshot exceeded the {:?} maximum wait duration!",
next_snapshot_type,
max_wait_duration,
"Waiting for next {next_snapshot_type:?} snapshot exceeded the {max_wait_duration:?} maximum wait duration!",
);
}
sleep(Duration::from_secs(5));

View File

@ -63,7 +63,7 @@ pub fn restore_tower(tower_path: &Path, node_pubkey: &Pubkey) -> Option<Tower> {
if tower_err.is_file_missing() {
return None;
} else {
panic!("tower restore failed...: {:?}", tower_err);
panic!("tower restore failed...: {tower_err:?}");
}
}
// actually saved tower must have at least one vote.
@ -98,7 +98,7 @@ pub fn open_blockstore(ledger_path: &Path) -> Blockstore {
},
)
.unwrap_or_else(|e| {
panic!("Failed to open ledger at {:?}, err: {}", ledger_path, e);
panic!("Failed to open ledger at {ledger_path:?}, err: {e}");
})
})
}

View File

@ -1710,7 +1710,7 @@ fn test_optimistic_confirmation_violation_detection() {
}
sleep(Duration::from_millis(10));
}
print!("{}", output);
print!("{output}");
assert!(success);
} else {
panic!("dumped log and disabled testing");
@ -2598,8 +2598,7 @@ fn test_votes_land_in_fork_during_long_partition() {
// refreshing to refresh the vote on blockhash expiration for the vote
// transaction.
start.elapsed() <= Duration::from_millis(max_wait),
"Went too long {} ms without a root",
max_wait,
"Went too long {max_wait} ms without a root",
);
let lighter_validator_blockstore = open_blockstore(&lighter_validator_ledger_path);
if lighter_validator_blockstore.is_root(context.heavier_fork_slot) {

View File

@ -238,7 +238,7 @@ fn test_ledger_cleanup_service() {
.unwrap()
.for_each(|_| slots += 1);
// with 3 nodes up to 3 slots can be in progress and not complete so max slots in blockstore should be up to 103
assert!(slots <= 103, "got {}", slots);
assert!(slots <= 103, "got {slots}");
}
}

View File

@ -188,7 +188,7 @@ fn analyze_logs(matches: &ArgMatches) {
})
.unwrap_or_default();
if !diff.is_empty() {
println!("{}", diff);
println!("{diff}");
}
});
}

View File

@ -88,30 +88,30 @@ mod tests {
start: Instant::now(),
duration: 1,
};
assert_eq!(format!("{}", measure), "test_ns took 1ns");
assert_eq!(format!("{measure}"), "test_ns took 1ns");
let measure = Measure {
name: "test_us",
start: Instant::now(),
duration: 1000,
};
assert_eq!(format!("{}", measure), "test_us took 1us");
assert_eq!(format!("{measure}"), "test_us took 1us");
let measure = Measure {
name: "test_ms",
start: Instant::now(),
duration: 1000 * 1000,
};
assert_eq!(format!("{}", measure), "test_ms took 1ms");
assert_eq!(format!("{measure}"), "test_ms took 1ms");
let measure = Measure {
name: "test_s",
start: Instant::now(),
duration: 1000 * 1000 * 1000,
};
assert_eq!(format!("{}", measure), "test_s took 1.0s");
assert_eq!(format!("{measure}"), "test_s took 1.0s");
let measure = Measure::start("test_not_stopped");
assert_eq!(format!("{}", measure), "test_not_stopped running");
assert_eq!(format!("{measure}"), "test_not_stopped running");
}
}

View File

@ -45,7 +45,7 @@ fn main() {
.collect();
for result in &elapsed {
println!("compute_merkle_root(us),{}", result);
println!("compute_merkle_root(us),{result}");
}
println!(
"compute_merkle_root(us) avg: {}",

View File

@ -98,7 +98,7 @@ pub fn serialize_points(points: &Vec<DataPoint>, host_id: &str) -> String {
for point in points {
let _ = write!(line, "{},host_id={}", &point.name, host_id);
for (name, value) in point.tags.iter() {
let _ = write!(line, ",{}={}", name, value);
let _ = write!(line, ",{name}={value}");
}
let mut first = true;
@ -108,7 +108,7 @@ pub fn serialize_points(points: &Vec<DataPoint>, host_id: &str) -> String {
}
let timestamp = point.timestamp.duration_since(UNIX_EPOCH);
let nanos = timestamp.unwrap().as_nanos();
let _ = writeln!(line, " {}", nanos);
let _ = writeln!(line, " {nanos}");
}
line
}
@ -390,13 +390,13 @@ impl MetricsConfig {
fn get_metrics_config() -> Result<MetricsConfig, String> {
let mut config = MetricsConfig::default();
let config_var = env::var("SOLANA_METRICS_CONFIG")
.map_err(|err| format!("SOLANA_METRICS_CONFIG: {}", err))?;
let config_var =
env::var("SOLANA_METRICS_CONFIG").map_err(|err| format!("SOLANA_METRICS_CONFIG: {err}"))?;
for pair in config_var.split(',') {
let nv: Vec<_> = pair.split('=').collect();
if nv.len() != 2 {
return Err(format!("SOLANA_METRICS_CONFIG is invalid: '{}'", pair));
return Err(format!("SOLANA_METRICS_CONFIG is invalid: '{pair}'"));
}
let v = nv[1].to_string();
match nv[0] {
@ -404,7 +404,7 @@ fn get_metrics_config() -> Result<MetricsConfig, String> {
"db" => config.db = v,
"u" => config.username = v,
"p" => config.password = v,
_ => return Err(format!("SOLANA_METRICS_CONFIG is invalid: '{}'", pair)),
_ => return Err(format!("SOLANA_METRICS_CONFIG is invalid: '{pair}'")),
}
}

View File

@ -24,9 +24,9 @@ pub enum PohTimingPoint {
impl fmt::Display for PohTimingPoint {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
PohTimingPoint::PohSlotStart(t) => write!(f, "poh_start={}", t),
PohTimingPoint::PohSlotEnd(t) => write!(f, "poh_end ={}", t),
PohTimingPoint::FullSlotReceived(t) => write!(f, "poh_full ={}", t),
PohTimingPoint::PohSlotStart(t) => write!(f, "poh_start={t}"),
PohTimingPoint::PohSlotEnd(t) => write!(f, "poh_end ={t}"),
PohTimingPoint::FullSlotReceived(t) => write!(f, "poh_full ={t}"),
}
}
}
@ -115,7 +115,7 @@ mod test {
assert_eq!(p.root_slot, Some(101));
assert_eq!(p.timing_point, PohTimingPoint::PohSlotStart(100));
assert_eq!(
format!("{}", p),
format!("{p}"),
"PohTimingPoint: poh_start=100, slot=100, root_slot=101"
);
@ -125,7 +125,7 @@ mod test {
assert_eq!(p.root_slot, None);
assert_eq!(p.timing_point, PohTimingPoint::PohSlotStart(100));
assert_eq!(
format!("{}", p),
format!("{p}"),
"PohTimingPoint: poh_start=100, slot=100, root_slot=0"
);
@ -135,7 +135,7 @@ mod test {
assert_eq!(p.root_slot, Some(101));
assert_eq!(p.timing_point, PohTimingPoint::PohSlotEnd(100));
assert_eq!(
format!("{}", p),
format!("{p}"),
"PohTimingPoint: poh_end =100, slot=100, root_slot=101"
);
@ -145,7 +145,7 @@ mod test {
assert_eq!(p.root_slot, None);
assert_eq!(p.timing_point, PohTimingPoint::PohSlotEnd(100));
assert_eq!(
format!("{}", p),
format!("{p}"),
"PohTimingPoint: poh_end =100, slot=100, root_slot=0"
);
@ -155,7 +155,7 @@ mod test {
assert_eq!(p.root_slot, Some(101));
assert_eq!(p.timing_point, PohTimingPoint::FullSlotReceived(100));
assert_eq!(
format!("{}", p),
format!("{p}"),
"PohTimingPoint: poh_full =100, slot=100, root_slot=101"
);
@ -166,7 +166,7 @@ mod test {
assert_eq!(p.timing_point, PohTimingPoint::FullSlotReceived(100));
assert_eq!(
format!("{}", p),
format!("{p}"),
"PohTimingPoint: poh_full =100, slot=100, root_slot=0"
);
}

View File

@ -49,7 +49,7 @@ impl NetworkTopology {
println!("Configure partition map (must add up to 100, e.g. [70, 20, 10]):");
let partitions_str = match io::stdin().read_line(&mut input) {
Ok(_) => input,
Err(error) => panic!("error: {}", error),
Err(error) => panic!("error: {error}"),
};
let partitions: Vec<u8> = serde_json::from_str(&partitions_str)
@ -59,11 +59,11 @@ impl NetworkTopology {
for i in 0..partitions.len() - 1 {
for j in i + 1..partitions.len() {
println!("Configure interconnect ({} <-> {}):", i, j);
println!("Configure interconnect ({i} <-> {j}):");
let mut input = String::new();
let mut interconnect_config = match io::stdin().read_line(&mut input) {
Ok(_) => input,
Err(error) => panic!("error: {}", error),
Err(error) => panic!("error: {error}"),
};
if interconnect_config.ends_with('\n') {
@ -121,14 +121,14 @@ impl NetworkTopology {
for j in i + 1..partitions.len() {
let drop_config = if max_packet_drop > 0 {
let packet_drop = rng.gen_range(0, max_packet_drop + 1);
format!("loss {}% 25% ", packet_drop)
format!("loss {packet_drop}% 25% ")
} else {
String::default()
};
let config = if max_packet_delay > 0 {
let packet_delay = rng.gen_range(0, max_packet_delay + 1);
format!("{}delay {}ms 10ms", drop_config, packet_delay)
format!("{drop_config}delay {packet_delay}ms 10ms")
} else {
drop_config
};
@ -397,7 +397,7 @@ fn shape_network_steps(
"my_index: {}, network_size: {}, partitions: {:?}",
my_index, network_size, topology.partitions
);
println!("My partition is {}", my_partition);
println!("My partition is {my_partition}");
cleanup_network(interface);
@ -407,7 +407,7 @@ fn shape_network_steps(
}
let num_bands = topology.partitions.len() + 1;
let default_filter_class = format!("1:{}", num_bands);
let default_filter_class = format!("1:{num_bands}");
if !topology.interconnects.is_empty() {
let num_bands_str = num_bands.to_string();
// Redirect ingress traffic to the virtual interface ifb0 so we can
@ -426,7 +426,7 @@ fn shape_network_steps(
println!("Setting up interconnects");
for i in &topology.interconnects {
if i.b as usize == my_partition {
println!("interconnects: {:#?}", i);
println!("interconnects: {i:#?}");
let tos = partition_id_to_tos(i.a as usize);
if tos == 0 {
println!("Incorrect value of TOS/Partition in config {}", i.a);
@ -478,7 +478,7 @@ fn configure(matches: &ArgMatches) {
let topology = serde_json::to_string(&config).expect("Failed to write as JSON");
println!("{}", topology);
println!("{topology}");
}
fn main() {

View File

@ -14,12 +14,12 @@ fn main() {
let host_port = matches.value_of("host_port").unwrap();
let addr = solana_net_utils::parse_host_port(host_port)
.unwrap_or_else(|_| panic!("failed to parse {}", host_port));
.unwrap_or_else(|_| panic!("failed to parse {host_port}"));
match solana_net_utils::get_public_ip_addr(&addr) {
Ok(ip) => println!("{}", ip),
Ok(ip) => println!("{ip}"),
Err(err) => {
eprintln!("{}: {}", addr, err);
eprintln!("{addr}: {err}");
std::process::exit(1)
}
}

Some files were not shown because too many files have changed in this diff Show More