Deprecate commitment variants (#14797)

* Deprecate commitment variants

* Add new CommitmentConfig builders

* Add helpers to avoid allowing deprecated variants

* Remove deprecated transaction-status code

* Include new commitment variants in runtime commitment; allow deprecated as long as old variants persist

* Remove deprecated banks code

* Remove deprecated variants in core; allow deprecated in rpc/rpc-subscriptions for now

* Heavier hand with rpc/rpc-subscription commitment

* Remove deprecated variants from local-cluster

* Remove deprecated variants from various tools

* Remove deprecated variants from validator

* Update docs

* Remove deprecated client code

* Add new variants to cli; remove deprecated variants as possible

* Don't send new commitment variants to old clusters

* Retain deprecated method in test_validator_saves_tower

* Fix clippy matches! suggestion for BPF solana-sdk legacy compile test

* Refactor node version check to handle commitment variants and transaction encoding

* Hide deprecated variants from cli help

* Add cli App comments
This commit is contained in:
Tyera Eulberg 2021-01-26 12:23:07 -07:00 committed by GitHub
parent e08d2e6fcc
commit ffa5c7dcc8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
37 changed files with 540 additions and 322 deletions

View File

@ -122,7 +122,7 @@ impl BanksClient {
pub fn get_fees( pub fn get_fees(
&mut self, &mut self,
) -> impl Future<Output = io::Result<(FeeCalculator, Hash, Slot)>> + '_ { ) -> impl Future<Output = io::Result<(FeeCalculator, Hash, Slot)>> + '_ {
self.get_fees_with_commitment_and_context(context::current(), CommitmentLevel::Root) self.get_fees_with_commitment_and_context(context::current(), CommitmentLevel::default())
} }
/// Return the cluster rent /// Return the cluster rent
@ -196,7 +196,7 @@ impl BanksClient {
/// Return the most recent rooted slot height. All transactions at or below this height /// Return the most recent rooted slot height. All transactions at or below this height
/// are said to be finalized. The cluster will not fork to a higher slot height. /// are said to be finalized. The cluster will not fork to a higher slot height.
pub fn get_root_slot(&mut self) -> impl Future<Output = io::Result<Slot>> + '_ { pub fn get_root_slot(&mut self) -> impl Future<Output = io::Result<Slot>> + '_ {
self.get_slot_with_context(context::current(), CommitmentLevel::Root) self.get_slot_with_context(context::current(), CommitmentLevel::default())
} }
/// Return the account at the given address at the slot corresponding to the given /// Return the account at the given address at the slot corresponding to the given

View File

@ -167,11 +167,11 @@ impl Banks for BanksServer {
_: Context, _: Context,
signature: Signature, signature: Signature,
) -> Option<TransactionStatus> { ) -> Option<TransactionStatus> {
let bank = self.bank(CommitmentLevel::Recent); let bank = self.bank(CommitmentLevel::Processed);
let (slot, status) = bank.get_signature_status_slot(&signature)?; let (slot, status) = bank.get_signature_status_slot(&signature)?;
let r_block_commitment_cache = self.block_commitment_cache.read().unwrap(); let r_block_commitment_cache = self.block_commitment_cache.read().unwrap();
let optimistically_confirmed_bank = self.bank(CommitmentLevel::SingleGossip); let optimistically_confirmed_bank = self.bank(CommitmentLevel::Confirmed);
let optimistically_confirmed = let optimistically_confirmed =
optimistically_confirmed_bank.get_signature_status_slot(&signature); optimistically_confirmed_bank.get_signature_status_slot(&signature);

View File

@ -390,7 +390,7 @@ fn swapper<T>(
while client while client
.get_balance_with_commitment( .get_balance_with_commitment(
&trade_infos[trade_index].trade_account, &trade_infos[trade_index].trade_account,
CommitmentConfig::recent(), CommitmentConfig::processed(),
) )
.unwrap_or(0) .unwrap_or(0)
== 0 == 0
@ -445,7 +445,7 @@ fn swapper<T>(
account_group = (account_group + 1) % account_groups as usize; account_group = (account_group + 1) % account_groups as usize;
let (blockhash, _fee_calculator, _last_valid_slot) = client let (blockhash, _fee_calculator, _last_valid_slot) = client
.get_recent_blockhash_with_commitment(CommitmentConfig::recent()) .get_recent_blockhash_with_commitment(CommitmentConfig::processed())
.expect("Failed to get blockhash"); .expect("Failed to get blockhash");
let to_swap_txs: Vec<_> = to_swap let to_swap_txs: Vec<_> = to_swap
.par_iter() .par_iter()
@ -571,7 +571,7 @@ fn trader<T>(
account_group = (account_group + 1) % account_groups as usize; account_group = (account_group + 1) % account_groups as usize;
let (blockhash, _fee_calculator, _last_valid_slot) = client let (blockhash, _fee_calculator, _last_valid_slot) = client
.get_recent_blockhash_with_commitment(CommitmentConfig::recent()) .get_recent_blockhash_with_commitment(CommitmentConfig::processed())
.expect("Failed to get blockhash"); .expect("Failed to get blockhash");
trades.chunks(chunk_size).for_each(|chunk| { trades.chunks(chunk_size).for_each(|chunk| {
@ -658,7 +658,7 @@ where
{ {
for s in &tx.signatures { for s in &tx.signatures {
if let Ok(Some(r)) = if let Ok(Some(r)) =
sync_client.get_signature_status_with_commitment(s, CommitmentConfig::recent()) sync_client.get_signature_status_with_commitment(s, CommitmentConfig::processed())
{ {
match r { match r {
Ok(_) => { Ok(_) => {
@ -681,7 +681,7 @@ fn verify_funding_transfer<T: SyncClient + ?Sized>(
if verify_transaction(client, tx) { if verify_transaction(client, tx) {
for a in &tx.message().account_keys[1..] { for a in &tx.message().account_keys[1..] {
if client if client
.get_balance_with_commitment(a, CommitmentConfig::recent()) .get_balance_with_commitment(a, CommitmentConfig::processed())
.unwrap_or(0) .unwrap_or(0)
>= amount >= amount
{ {
@ -764,7 +764,7 @@ pub fn fund_keys<T: Client>(client: &T, source: &Keypair, dests: &[Arc<Keypair>]
); );
let (blockhash, _fee_calculator, _last_valid_slot) = client let (blockhash, _fee_calculator, _last_valid_slot) = client
.get_recent_blockhash_with_commitment(CommitmentConfig::recent()) .get_recent_blockhash_with_commitment(CommitmentConfig::processed())
.expect("blockhash"); .expect("blockhash");
to_fund_txs.par_iter_mut().for_each(|(k, tx)| { to_fund_txs.par_iter_mut().for_each(|(k, tx)| {
tx.sign(&[*k], blockhash); tx.sign(&[*k], blockhash);
@ -803,7 +803,7 @@ pub fn fund_keys<T: Client>(client: &T, source: &Keypair, dests: &[Arc<Keypair>]
funded.append(&mut new_funded); funded.append(&mut new_funded);
funded.retain(|(k, b)| { funded.retain(|(k, b)| {
client client
.get_balance_with_commitment(&k.pubkey(), CommitmentConfig::recent()) .get_balance_with_commitment(&k.pubkey(), CommitmentConfig::processed())
.unwrap_or(0) .unwrap_or(0)
> lamports > lamports
&& *b > lamports && *b > lamports
@ -857,7 +857,7 @@ pub fn create_token_accounts<T: Client>(
let mut retries = 0; let mut retries = 0;
while !to_create_txs.is_empty() { while !to_create_txs.is_empty() {
let (blockhash, _fee_calculator, _last_valid_slot) = client let (blockhash, _fee_calculator, _last_valid_slot) = client
.get_recent_blockhash_with_commitment(CommitmentConfig::recent()) .get_recent_blockhash_with_commitment(CommitmentConfig::processed())
.expect("Failed to get blockhash"); .expect("Failed to get blockhash");
to_create_txs to_create_txs
.par_iter_mut() .par_iter_mut()
@ -903,7 +903,7 @@ pub fn create_token_accounts<T: Client>(
let mut new_notfunded: Vec<(&Arc<Keypair>, &Keypair)> = vec![]; let mut new_notfunded: Vec<(&Arc<Keypair>, &Keypair)> = vec![];
for f in &notfunded { for f in &notfunded {
if client if client
.get_balance_with_commitment(&f.1.pubkey(), CommitmentConfig::recent()) .get_balance_with_commitment(&f.1.pubkey(), CommitmentConfig::processed())
.unwrap_or(0) .unwrap_or(0)
== 0 == 0
{ {
@ -968,7 +968,7 @@ pub fn airdrop_lamports<T: Client>(
id: &Keypair, id: &Keypair,
amount: u64, amount: u64,
) { ) {
let balance = client.get_balance_with_commitment(&id.pubkey(), CommitmentConfig::recent()); let balance = client.get_balance_with_commitment(&id.pubkey(), CommitmentConfig::processed());
let balance = balance.unwrap_or(0); let balance = balance.unwrap_or(0);
if balance >= amount { if balance >= amount {
return; return;
@ -986,7 +986,7 @@ pub fn airdrop_lamports<T: Client>(
let mut tries = 0; let mut tries = 0;
loop { loop {
let (blockhash, _fee_calculator, _last_valid_slot) = client let (blockhash, _fee_calculator, _last_valid_slot) = client
.get_recent_blockhash_with_commitment(CommitmentConfig::recent()) .get_recent_blockhash_with_commitment(CommitmentConfig::processed())
.expect("Failed to get blockhash"); .expect("Failed to get blockhash");
match request_airdrop_transaction(&faucet_addr, &id.pubkey(), amount_to_drop, blockhash) { match request_airdrop_transaction(&faucet_addr, &id.pubkey(), amount_to_drop, blockhash) {
Ok(transaction) => { Ok(transaction) => {
@ -995,14 +995,14 @@ pub fn airdrop_lamports<T: Client>(
for _ in 0..30 { for _ in 0..30 {
if let Ok(Some(_)) = client.get_signature_status_with_commitment( if let Ok(Some(_)) = client.get_signature_status_with_commitment(
&signature, &signature,
CommitmentConfig::recent(), CommitmentConfig::processed(),
) { ) {
break; break;
} }
sleep(Duration::from_millis(100)); sleep(Duration::from_millis(100));
} }
if client if client
.get_balance_with_commitment(&id.pubkey(), CommitmentConfig::recent()) .get_balance_with_commitment(&id.pubkey(), CommitmentConfig::processed())
.unwrap_or(0) .unwrap_or(0)
>= amount >= amount
{ {

View File

@ -47,7 +47,7 @@ pub type SharedTransactions = Arc<RwLock<VecDeque<Vec<(Transaction, u64)>>>>;
fn get_recent_blockhash<T: Client>(client: &T) -> (Hash, FeeCalculator) { fn get_recent_blockhash<T: Client>(client: &T) -> (Hash, FeeCalculator) {
loop { loop {
match client.get_recent_blockhash_with_commitment(CommitmentConfig::recent()) { match client.get_recent_blockhash_with_commitment(CommitmentConfig::processed()) {
Ok((blockhash, fee_calculator, _last_valid_slot)) => { Ok((blockhash, fee_calculator, _last_valid_slot)) => {
return (blockhash, fee_calculator) return (blockhash, fee_calculator)
} }
@ -496,7 +496,7 @@ fn do_tx_transfers<T: Client>(
fn verify_funding_transfer<T: Client>(client: &Arc<T>, tx: &Transaction, amount: u64) -> bool { fn verify_funding_transfer<T: Client>(client: &Arc<T>, tx: &Transaction, amount: u64) -> bool {
for a in &tx.message().account_keys[1..] { for a in &tx.message().account_keys[1..] {
match client.get_balance_with_commitment(a, CommitmentConfig::recent()) { match client.get_balance_with_commitment(a, CommitmentConfig::processed()) {
Ok(balance) => return balance >= amount, Ok(balance) => return balance >= amount,
Err(err) => error!("failed to get balance {:?}", err), Err(err) => error!("failed to get balance {:?}", err),
} }
@ -761,7 +761,7 @@ pub fn airdrop_lamports<T: Client>(
}; };
let current_balance = client let current_balance = client
.get_balance_with_commitment(&id.pubkey(), CommitmentConfig::recent()) .get_balance_with_commitment(&id.pubkey(), CommitmentConfig::processed())
.unwrap_or_else(|e| { .unwrap_or_else(|e| {
info!("airdrop error {}", e); info!("airdrop error {}", e);
starting_balance starting_balance
@ -966,7 +966,7 @@ mod tests {
for kp in &keypairs { for kp in &keypairs {
assert_eq!( assert_eq!(
client client
.get_balance_with_commitment(&kp.pubkey(), CommitmentConfig::recent()) .get_balance_with_commitment(&kp.pubkey(), CommitmentConfig::processed())
.unwrap(), .unwrap(),
lamports lamports
); );

View File

@ -42,7 +42,7 @@ impl Default for Config {
"System Program".to_string(), "System Program".to_string(),
); );
let commitment = "singleGossip".to_string(); let commitment = "confirmed".to_string();
Self { Self {
json_rpc_url, json_rpc_url,

View File

@ -437,7 +437,7 @@ impl CliConfig<'_> {
} }
fn default_commitment() -> CommitmentConfig { fn default_commitment() -> CommitmentConfig {
CommitmentConfig::single_gossip() CommitmentConfig::confirmed()
} }
fn first_nonempty_setting( fn first_nonempty_setting(
@ -532,10 +532,10 @@ impl CliConfig<'_> {
pub fn recent_for_tests() -> Self { pub fn recent_for_tests() -> Self {
Self { Self {
commitment: CommitmentConfig::recent(), commitment: CommitmentConfig::processed(),
send_transaction_config: RpcSendTransactionConfig { send_transaction_config: RpcSendTransactionConfig {
skip_preflight: true, skip_preflight: true,
preflight_commitment: Some(CommitmentConfig::recent().commitment), preflight_commitment: Some(CommitmentConfig::processed().commitment),
..RpcSendTransactionConfig::default() ..RpcSendTransactionConfig::default()
}, },
..Self::default() ..Self::default()
@ -558,7 +558,7 @@ impl Default for CliConfig<'_> {
rpc_timeout: Duration::from_secs(u64::from_str(DEFAULT_RPC_TIMEOUT_SECONDS).unwrap()), rpc_timeout: Duration::from_secs(u64::from_str(DEFAULT_RPC_TIMEOUT_SECONDS).unwrap()),
verbose: false, verbose: false,
output_format: OutputFormat::Display, output_format: OutputFormat::Display,
commitment: CommitmentConfig::single_gossip(), commitment: CommitmentConfig::confirmed(),
send_transaction_config: RpcSendTransactionConfig::default(), send_transaction_config: RpcSendTransactionConfig::default(),
address_labels: HashMap::new(), address_labels: HashMap::new(),
} }

View File

@ -902,7 +902,7 @@ pub fn process_get_block(
let slot = if let Some(slot) = slot { let slot = if let Some(slot) = slot {
slot slot
} else { } else {
rpc_client.get_slot_with_commitment(CommitmentConfig::max())? rpc_client.get_slot_with_commitment(CommitmentConfig::finalized())?
}; };
let mut block = let mut block =
@ -980,7 +980,7 @@ pub fn process_get_block_time(
let slot = if let Some(slot) = slot { let slot = if let Some(slot) = slot {
slot slot
} else { } else {
rpc_client.get_slot_with_commitment(CommitmentConfig::max())? rpc_client.get_slot_with_commitment(CommitmentConfig::finalized())?
}; };
let timestamp = rpc_client.get_block_time(slot)?; let timestamp = rpc_client.get_block_time(slot)?;
let block_time = CliBlockTime { slot, timestamp }; let block_time = CliBlockTime { slot, timestamp };
@ -1029,7 +1029,7 @@ pub fn process_show_block_production(
slot_limit: Option<u64>, slot_limit: Option<u64>,
) -> ProcessResult { ) -> ProcessResult {
let epoch_schedule = rpc_client.get_epoch_schedule()?; let epoch_schedule = rpc_client.get_epoch_schedule()?;
let epoch_info = rpc_client.get_epoch_info_with_commitment(CommitmentConfig::max())?; let epoch_info = rpc_client.get_epoch_info_with_commitment(CommitmentConfig::finalized())?;
let epoch = epoch.unwrap_or(epoch_info.epoch); let epoch = epoch.unwrap_or(epoch_info.epoch);
if epoch > epoch_info.epoch { if epoch > epoch_info.epoch {
@ -1088,7 +1088,7 @@ pub fn process_show_block_production(
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 let leader_schedule = rpc_client
.get_leader_schedule_with_commitment(Some(start_slot), CommitmentConfig::root())?; .get_leader_schedule_with_commitment(Some(start_slot), CommitmentConfig::finalized())?;
if leader_schedule.is_none() { 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());
} }

View File

@ -300,10 +300,20 @@ fn main() -> Result<(), Box<dyn error::Error>> {
Arg::with_name("commitment") Arg::with_name("commitment")
.long("commitment") .long("commitment")
.takes_value(true) .takes_value(true)
.possible_values(&["recent", "single", "singleGossip", "root", "max"]) .possible_values(&[
"processed",
"confirmed",
"finalized",
"recent", // Deprecated as of v1.5.5
"single", // Deprecated as of v1.5.5
"singleGossip", // Deprecated as of v1.5.5
"root", // Deprecated as of v1.5.5
"max", // Deprecated as of v1.5.5
])
.value_name("COMMITMENT_LEVEL") .value_name("COMMITMENT_LEVEL")
.hide_possible_values(true)
.global(true) .global(true)
.help("Return information at the selected commitment level"), .help("Return information at the selected commitment level [possible values: processed, confirmed, finalized]"),
) )
.arg( .arg(
Arg::with_name("verbose") Arg::with_name("verbose")

View File

@ -5,7 +5,7 @@ use std::{thread::sleep, time::Duration};
pub fn check_recent_balance(expected_balance: u64, client: &RpcClient, pubkey: &Pubkey) { pub fn check_recent_balance(expected_balance: u64, client: &RpcClient, pubkey: &Pubkey) {
(0..5).for_each(|tries| { (0..5).for_each(|tries| {
let balance = client let balance = client
.get_balance_with_commitment(pubkey, CommitmentConfig::recent()) .get_balance_with_commitment(pubkey, CommitmentConfig::processed())
.unwrap() .unwrap()
.value; .value;
if balance == expected_balance { if balance == expected_balance {
@ -20,7 +20,7 @@ pub fn check_recent_balance(expected_balance: u64, client: &RpcClient, pubkey: &
pub fn check_ready(rpc_client: &RpcClient) { pub fn check_ready(rpc_client: &RpcClient) {
while rpc_client while rpc_client
.get_slot_with_commitment(CommitmentConfig::recent()) .get_slot_with_commitment(CommitmentConfig::processed())
.unwrap() .unwrap()
< 5 < 5
{ {

View File

@ -64,7 +64,7 @@ fn full_battery_tests(
let faucet_addr = receiver.recv().unwrap(); let faucet_addr = receiver.recv().unwrap();
let rpc_client = let rpc_client =
RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::recent()); RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::processed());
let json_rpc_url = test_validator.rpc_url(); let json_rpc_url = test_validator.rpc_url();
let mut config_payer = CliConfig::recent_for_tests(); let mut config_payer = CliConfig::recent_for_tests();
@ -230,7 +230,7 @@ fn test_create_account_with_seed() {
// Setup accounts // Setup accounts
let rpc_client = let rpc_client =
RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::recent()); RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::processed());
request_and_confirm_airdrop( request_and_confirm_airdrop(
&rpc_client, &rpc_client,
&faucet_addr, &faucet_addr,
@ -280,7 +280,7 @@ fn test_create_account_with_seed() {
let nonce_hash = nonce_utils::get_account_with_commitment( let nonce_hash = nonce_utils::get_account_with_commitment(
&rpc_client, &rpc_client,
&nonce_address, &nonce_address,
CommitmentConfig::recent(), CommitmentConfig::processed(),
) )
.and_then(|ref a| nonce_utils::data_from_account(a)) .and_then(|ref a| nonce_utils::data_from_account(a))
.unwrap() .unwrap()

View File

@ -34,7 +34,7 @@ fn test_cli_program_deploy_non_upgradeable() {
let faucet_addr = receiver.recv().unwrap(); let faucet_addr = receiver.recv().unwrap();
let rpc_client = let rpc_client =
RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::recent()); RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::processed());
let mut file = File::open(pathbuf.to_str().unwrap()).unwrap(); let mut file = File::open(pathbuf.to_str().unwrap()).unwrap();
let mut program_data = Vec::new(); let mut program_data = Vec::new();
@ -155,7 +155,7 @@ fn test_cli_program_deploy_no_authority() {
let faucet_addr = receiver.recv().unwrap(); let faucet_addr = receiver.recv().unwrap();
let rpc_client = let rpc_client =
RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::recent()); RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::processed());
let mut file = File::open(pathbuf.to_str().unwrap()).unwrap(); let mut file = File::open(pathbuf.to_str().unwrap()).unwrap();
let mut program_data = Vec::new(); let mut program_data = Vec::new();
@ -243,7 +243,7 @@ fn test_cli_program_deploy_with_authority() {
let faucet_addr = receiver.recv().unwrap(); let faucet_addr = receiver.recv().unwrap();
let rpc_client = let rpc_client =
RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::recent()); RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::processed());
let mut file = File::open(pathbuf.to_str().unwrap()).unwrap(); let mut file = File::open(pathbuf.to_str().unwrap()).unwrap();
let mut program_data = Vec::new(); let mut program_data = Vec::new();
@ -574,7 +574,7 @@ fn test_cli_program_write_buffer() {
let faucet_addr = receiver.recv().unwrap(); let faucet_addr = receiver.recv().unwrap();
let rpc_client = let rpc_client =
RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::recent()); RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::processed());
let mut file = File::open(pathbuf.to_str().unwrap()).unwrap(); let mut file = File::open(pathbuf.to_str().unwrap()).unwrap();
let mut program_data = Vec::new(); let mut program_data = Vec::new();
@ -829,7 +829,7 @@ fn test_cli_program_set_buffer_authority() {
let faucet_addr = receiver.recv().unwrap(); let faucet_addr = receiver.recv().unwrap();
let rpc_client = let rpc_client =
RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::recent()); RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::processed());
let mut file = File::open(pathbuf.to_str().unwrap()).unwrap(); let mut file = File::open(pathbuf.to_str().unwrap()).unwrap();
let mut program_data = Vec::new(); let mut program_data = Vec::new();

View File

@ -32,7 +32,7 @@ fn test_cli_request_airdrop() {
sig_response.unwrap(); sig_response.unwrap();
let rpc_client = let rpc_client =
RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::recent()); RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::processed());
let balance = rpc_client let balance = rpc_client
.get_balance(&bob_config.signers[0].pubkey()) .get_balance(&bob_config.signers[0].pubkey())

View File

@ -33,7 +33,7 @@ fn test_stake_delegation_force() {
let faucet_addr = receiver.recv().unwrap(); let faucet_addr = receiver.recv().unwrap();
let rpc_client = let rpc_client =
RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::recent()); RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::processed());
let default_signer = Keypair::new(); let default_signer = Keypair::new();
let mut config = CliConfig::recent_for_tests(); let mut config = CliConfig::recent_for_tests();
@ -122,7 +122,7 @@ fn test_seed_stake_delegation_and_deactivation() {
let faucet_addr = receiver.recv().unwrap(); let faucet_addr = receiver.recv().unwrap();
let rpc_client = let rpc_client =
RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::recent()); RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::processed());
let validator_keypair = keypair_from_seed(&[0u8; 32]).unwrap(); let validator_keypair = keypair_from_seed(&[0u8; 32]).unwrap();
let mut config_validator = CliConfig::recent_for_tests(); let mut config_validator = CliConfig::recent_for_tests();
@ -202,7 +202,7 @@ fn test_stake_delegation_and_deactivation() {
let faucet_addr = receiver.recv().unwrap(); let faucet_addr = receiver.recv().unwrap();
let rpc_client = let rpc_client =
RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::recent()); RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::processed());
let validator_keypair = Keypair::new(); let validator_keypair = Keypair::new();
let mut config_validator = CliConfig::recent_for_tests(); let mut config_validator = CliConfig::recent_for_tests();
@ -278,7 +278,7 @@ fn test_offline_stake_delegation_and_deactivation() {
let faucet_addr = receiver.recv().unwrap(); let faucet_addr = receiver.recv().unwrap();
let rpc_client = let rpc_client =
RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::recent()); RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::processed());
let mut config_validator = CliConfig::recent_for_tests(); let mut config_validator = CliConfig::recent_for_tests();
config_validator.json_rpc_url = test_validator.rpc_url(); config_validator.json_rpc_url = test_validator.rpc_url();
@ -411,7 +411,7 @@ fn test_nonced_stake_delegation_and_deactivation() {
let faucet_addr = receiver.recv().unwrap(); let faucet_addr = receiver.recv().unwrap();
let rpc_client = let rpc_client =
RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::recent()); RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::processed());
let config_keypair = keypair_from_seed(&[0u8; 32]).unwrap(); let config_keypair = keypair_from_seed(&[0u8; 32]).unwrap();
let mut config = CliConfig::recent_for_tests(); let mut config = CliConfig::recent_for_tests();
@ -465,7 +465,7 @@ fn test_nonced_stake_delegation_and_deactivation() {
let nonce_hash = nonce_utils::get_account_with_commitment( let nonce_hash = nonce_utils::get_account_with_commitment(
&rpc_client, &rpc_client,
&nonce_account.pubkey(), &nonce_account.pubkey(),
CommitmentConfig::recent(), CommitmentConfig::processed(),
) )
.and_then(|ref a| nonce_utils::data_from_account(a)) .and_then(|ref a| nonce_utils::data_from_account(a))
.unwrap() .unwrap()
@ -493,7 +493,7 @@ fn test_nonced_stake_delegation_and_deactivation() {
let nonce_hash = nonce_utils::get_account_with_commitment( let nonce_hash = nonce_utils::get_account_with_commitment(
&rpc_client, &rpc_client,
&nonce_account.pubkey(), &nonce_account.pubkey(),
CommitmentConfig::recent(), CommitmentConfig::processed(),
) )
.and_then(|ref a| nonce_utils::data_from_account(a)) .and_then(|ref a| nonce_utils::data_from_account(a))
.unwrap() .unwrap()
@ -526,7 +526,7 @@ fn test_stake_authorize() {
let faucet_addr = receiver.recv().unwrap(); let faucet_addr = receiver.recv().unwrap();
let rpc_client = let rpc_client =
RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::recent()); RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::processed());
let default_signer = Keypair::new(); let default_signer = Keypair::new();
let mut config = CliConfig::recent_for_tests(); let mut config = CliConfig::recent_for_tests();
@ -706,7 +706,7 @@ fn test_stake_authorize() {
let nonce_hash = nonce_utils::get_account_with_commitment( let nonce_hash = nonce_utils::get_account_with_commitment(
&rpc_client, &rpc_client,
&nonce_account.pubkey(), &nonce_account.pubkey(),
CommitmentConfig::recent(), CommitmentConfig::processed(),
) )
.and_then(|ref a| nonce_utils::data_from_account(a)) .and_then(|ref a| nonce_utils::data_from_account(a))
.unwrap() .unwrap()
@ -756,7 +756,7 @@ fn test_stake_authorize() {
let new_nonce_hash = nonce_utils::get_account_with_commitment( let new_nonce_hash = nonce_utils::get_account_with_commitment(
&rpc_client, &rpc_client,
&nonce_account.pubkey(), &nonce_account.pubkey(),
CommitmentConfig::recent(), CommitmentConfig::processed(),
) )
.and_then(|ref a| nonce_utils::data_from_account(a)) .and_then(|ref a| nonce_utils::data_from_account(a))
.unwrap() .unwrap()
@ -776,7 +776,7 @@ fn test_stake_authorize_with_fee_payer() {
let faucet_addr = receiver.recv().unwrap(); let faucet_addr = receiver.recv().unwrap();
let rpc_client = let rpc_client =
RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::recent()); RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::processed());
let default_signer = Keypair::new(); let default_signer = Keypair::new();
let default_pubkey = default_signer.pubkey(); let default_pubkey = default_signer.pubkey();
@ -898,7 +898,7 @@ fn test_stake_split() {
let faucet_addr = receiver.recv().unwrap(); let faucet_addr = receiver.recv().unwrap();
let rpc_client = let rpc_client =
RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::recent()); RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::processed());
let default_signer = Keypair::new(); let default_signer = Keypair::new();
let offline_signer = Keypair::new(); let offline_signer = Keypair::new();
@ -975,7 +975,7 @@ fn test_stake_split() {
let nonce_hash = nonce_utils::get_account_with_commitment( let nonce_hash = nonce_utils::get_account_with_commitment(
&rpc_client, &rpc_client,
&nonce_account.pubkey(), &nonce_account.pubkey(),
CommitmentConfig::recent(), CommitmentConfig::processed(),
) )
.and_then(|ref a| nonce_utils::data_from_account(a)) .and_then(|ref a| nonce_utils::data_from_account(a))
.unwrap() .unwrap()
@ -1042,7 +1042,7 @@ fn test_stake_set_lockup() {
let faucet_addr = receiver.recv().unwrap(); let faucet_addr = receiver.recv().unwrap();
let rpc_client = let rpc_client =
RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::recent()); RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::processed());
let default_signer = Keypair::new(); let default_signer = Keypair::new();
let offline_signer = Keypair::new(); let offline_signer = Keypair::new();
@ -1227,7 +1227,7 @@ fn test_stake_set_lockup() {
let nonce_hash = nonce_utils::get_account_with_commitment( let nonce_hash = nonce_utils::get_account_with_commitment(
&rpc_client, &rpc_client,
&nonce_account.pubkey(), &nonce_account.pubkey(),
CommitmentConfig::recent(), CommitmentConfig::processed(),
) )
.and_then(|ref a| nonce_utils::data_from_account(a)) .and_then(|ref a| nonce_utils::data_from_account(a))
.unwrap() .unwrap()
@ -1294,7 +1294,7 @@ fn test_offline_nonced_create_stake_account_and_withdraw() {
let faucet_addr = receiver.recv().unwrap(); let faucet_addr = receiver.recv().unwrap();
let rpc_client = let rpc_client =
RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::recent()); RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::processed());
let mut config = CliConfig::recent_for_tests(); let mut config = CliConfig::recent_for_tests();
let default_signer = keypair_from_seed(&[1u8; 32]).unwrap(); let default_signer = keypair_from_seed(&[1u8; 32]).unwrap();
config.signers = vec![&default_signer]; config.signers = vec![&default_signer];
@ -1342,7 +1342,7 @@ fn test_offline_nonced_create_stake_account_and_withdraw() {
let nonce_hash = nonce_utils::get_account_with_commitment( let nonce_hash = nonce_utils::get_account_with_commitment(
&rpc_client, &rpc_client,
&nonce_account.pubkey(), &nonce_account.pubkey(),
CommitmentConfig::recent(), CommitmentConfig::processed(),
) )
.and_then(|ref a| nonce_utils::data_from_account(a)) .and_then(|ref a| nonce_utils::data_from_account(a))
.unwrap() .unwrap()
@ -1397,7 +1397,7 @@ fn test_offline_nonced_create_stake_account_and_withdraw() {
let nonce_hash = nonce_utils::get_account_with_commitment( let nonce_hash = nonce_utils::get_account_with_commitment(
&rpc_client, &rpc_client,
&nonce_account.pubkey(), &nonce_account.pubkey(),
CommitmentConfig::recent(), CommitmentConfig::processed(),
) )
.and_then(|ref a| nonce_utils::data_from_account(a)) .and_then(|ref a| nonce_utils::data_from_account(a))
.unwrap() .unwrap()
@ -1445,7 +1445,7 @@ fn test_offline_nonced_create_stake_account_and_withdraw() {
let nonce_hash = nonce_utils::get_account_with_commitment( let nonce_hash = nonce_utils::get_account_with_commitment(
&rpc_client, &rpc_client,
&nonce_account.pubkey(), &nonce_account.pubkey(),
CommitmentConfig::recent(), CommitmentConfig::processed(),
) )
.and_then(|ref a| nonce_utils::data_from_account(a)) .and_then(|ref a| nonce_utils::data_from_account(a))
.unwrap() .unwrap()

View File

@ -30,7 +30,7 @@ fn test_transfer() {
let faucet_addr = receiver.recv().unwrap(); let faucet_addr = receiver.recv().unwrap();
let rpc_client = let rpc_client =
RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::recent()); RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::processed());
let default_signer = Keypair::new(); let default_signer = Keypair::new();
let default_offline_signer = Keypair::new(); let default_offline_signer = Keypair::new();
@ -145,7 +145,7 @@ fn test_transfer() {
let nonce_hash = nonce_utils::get_account_with_commitment( let nonce_hash = nonce_utils::get_account_with_commitment(
&rpc_client, &rpc_client,
&nonce_account.pubkey(), &nonce_account.pubkey(),
CommitmentConfig::recent(), CommitmentConfig::processed(),
) )
.and_then(|ref a| nonce_utils::data_from_account(a)) .and_then(|ref a| nonce_utils::data_from_account(a))
.unwrap() .unwrap()
@ -173,7 +173,7 @@ fn test_transfer() {
let new_nonce_hash = nonce_utils::get_account_with_commitment( let new_nonce_hash = nonce_utils::get_account_with_commitment(
&rpc_client, &rpc_client,
&nonce_account.pubkey(), &nonce_account.pubkey(),
CommitmentConfig::recent(), CommitmentConfig::processed(),
) )
.and_then(|ref a| nonce_utils::data_from_account(a)) .and_then(|ref a| nonce_utils::data_from_account(a))
.unwrap() .unwrap()
@ -194,7 +194,7 @@ fn test_transfer() {
let nonce_hash = nonce_utils::get_account_with_commitment( let nonce_hash = nonce_utils::get_account_with_commitment(
&rpc_client, &rpc_client,
&nonce_account.pubkey(), &nonce_account.pubkey(),
CommitmentConfig::recent(), CommitmentConfig::processed(),
) )
.and_then(|ref a| nonce_utils::data_from_account(a)) .and_then(|ref a| nonce_utils::data_from_account(a))
.unwrap() .unwrap()
@ -255,7 +255,7 @@ fn test_transfer_multisession_signing() {
// Setup accounts // Setup accounts
let rpc_client = let rpc_client =
RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::recent()); RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::processed());
request_and_confirm_airdrop( request_and_confirm_airdrop(
&rpc_client, &rpc_client,
&faucet_addr, &faucet_addr,
@ -365,7 +365,7 @@ fn test_transfer_all() {
let faucet_addr = receiver.recv().unwrap(); let faucet_addr = receiver.recv().unwrap();
let rpc_client = let rpc_client =
RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::recent()); RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::processed());
let default_signer = Keypair::new(); let default_signer = Keypair::new();

View File

@ -26,7 +26,7 @@ fn test_vote_authorize_and_withdraw() {
let faucet_addr = receiver.recv().unwrap(); let faucet_addr = receiver.recv().unwrap();
let rpc_client = let rpc_client =
RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::recent()); RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::processed());
let default_signer = Keypair::new(); let default_signer = Keypair::new();
let mut config = CliConfig::recent_for_tests(); let mut config = CliConfig::recent_for_tests();

View File

@ -33,7 +33,7 @@ pub fn sample_txs<T>(
let mut now = Instant::now(); let mut now = Instant::now();
let start_time = now; let start_time = now;
let initial_txs = client let initial_txs = client
.get_transaction_count_with_commitment(CommitmentConfig::recent()) .get_transaction_count_with_commitment(CommitmentConfig::processed())
.expect("transaction count"); .expect("transaction count");
let mut last_txs = initial_txs; let mut last_txs = initial_txs;
@ -42,7 +42,7 @@ pub fn sample_txs<T>(
let elapsed = now.elapsed(); let elapsed = now.elapsed();
now = Instant::now(); now = Instant::now();
let mut txs; let mut txs;
match client.get_transaction_count_with_commitment(CommitmentConfig::recent()) { match client.get_transaction_count_with_commitment(CommitmentConfig::processed()) {
Err(e) => { Err(e) => {
// ThinClient with multiple options should pick a better one now. // ThinClient with multiple options should pick a better one now.
info!("Couldn't get transaction count {:?}", e); info!("Couldn't get transaction count {:?}", e);

View File

@ -47,7 +47,7 @@ use std::{
pub struct RpcClient { pub struct RpcClient {
sender: Box<dyn RpcSender + Send + Sync + 'static>, sender: Box<dyn RpcSender + Send + Sync + 'static>,
commitment_config: CommitmentConfig, commitment_config: CommitmentConfig,
default_cluster_transaction_encoding: RwLock<Option<UiTransactionEncoding>>, node_version: RwLock<Option<semver::Version>>,
} }
fn serialize_encode_transaction( fn serialize_encode_transaction(
@ -77,7 +77,7 @@ impl RpcClient {
) -> Self { ) -> Self {
Self { Self {
sender: Box::new(sender), sender: Box::new(sender),
default_cluster_transaction_encoding: RwLock::new(None), node_version: RwLock::new(None),
commitment_config, commitment_config,
} }
} }
@ -128,16 +128,54 @@ impl RpcClient {
Self::new_with_timeout(url, timeout) Self::new_with_timeout(url, timeout)
} }
pub fn confirm_transaction(&self, signature: &Signature) -> ClientResult<bool> { fn get_node_version(&self) -> Result<semver::Version, RpcError> {
Ok(self let r_node_version = self.node_version.read().unwrap();
.confirm_transaction_with_commitment(signature, self.commitment_config)? if let Some(version) = &*r_node_version {
.value) Ok(version.clone())
} else {
drop(r_node_version);
let mut w_node_version = self.node_version.write().unwrap();
let node_version = self.get_version().map_err(|e| {
RpcError::RpcRequestError(format!("cluster version query failed: {}", e))
})?;
let node_version = semver::Version::parse(&node_version.solana_core).map_err(|e| {
RpcError::RpcRequestError(format!("failed to parse cluster version: {}", e))
})?;
*w_node_version = Some(node_version.clone());
Ok(node_version)
}
} }
pub fn commitment(&self) -> CommitmentConfig { pub fn commitment(&self) -> CommitmentConfig {
self.commitment_config self.commitment_config
} }
fn use_deprecated_commitment(&self) -> Result<bool, RpcError> {
Ok(self.get_node_version()? < semver::Version::new(1, 5, 5))
}
fn maybe_map_commitment(
&self,
requested_commitment: CommitmentConfig,
) -> Result<CommitmentConfig, RpcError> {
if matches!(
requested_commitment.commitment,
CommitmentLevel::Finalized | CommitmentLevel::Confirmed | CommitmentLevel::Processed
) && self.use_deprecated_commitment()?
{
return Ok(CommitmentConfig::use_deprecated_commitment(
requested_commitment,
));
}
Ok(requested_commitment)
}
pub fn confirm_transaction(&self, signature: &Signature) -> ClientResult<bool> {
Ok(self
.confirm_transaction_with_commitment(signature, self.commitment_config)?
.value)
}
pub fn confirm_transaction_with_commitment( pub fn confirm_transaction_with_commitment(
&self, &self,
signature: &Signature, signature: &Signature,
@ -159,34 +197,20 @@ impl RpcClient {
self.send_transaction_with_config( self.send_transaction_with_config(
transaction, transaction,
RpcSendTransactionConfig { RpcSendTransactionConfig {
preflight_commitment: Some(self.commitment_config.commitment), preflight_commitment: Some(
self.maybe_map_commitment(self.commitment_config)?
.commitment,
),
..RpcSendTransactionConfig::default() ..RpcSendTransactionConfig::default()
}, },
) )
} }
fn default_cluster_transaction_encoding(&self) -> Result<UiTransactionEncoding, RpcError> { fn default_cluster_transaction_encoding(&self) -> Result<UiTransactionEncoding, RpcError> {
let default_cluster_transaction_encoding = if self.get_node_version()? < semver::Version::new(1, 3, 16) {
self.default_cluster_transaction_encoding.read().unwrap(); Ok(UiTransactionEncoding::Base58)
if let Some(encoding) = *default_cluster_transaction_encoding {
Ok(encoding)
} else { } else {
drop(default_cluster_transaction_encoding); Ok(UiTransactionEncoding::Base64)
let cluster_version = self.get_version().map_err(|e| {
RpcError::RpcRequestError(format!("cluster version query failed: {}", e))
})?;
let cluster_version =
semver::Version::parse(&cluster_version.solana_core).map_err(|e| {
RpcError::RpcRequestError(format!("failed to parse cluster version: {}", e))
})?;
// Prefer base64 since 1.3.16
let encoding = if cluster_version < semver::Version::new(1, 3, 16) {
UiTransactionEncoding::Base58
} else {
UiTransactionEncoding::Base64
};
*self.default_cluster_transaction_encoding.write().unwrap() = Some(encoding);
Ok(encoding)
} }
} }
@ -200,8 +224,13 @@ impl RpcClient {
} else { } else {
self.default_cluster_transaction_encoding()? self.default_cluster_transaction_encoding()?
}; };
let preflight_commitment = CommitmentConfig {
commitment: config.preflight_commitment.unwrap_or_default(),
};
let preflight_commitment = self.maybe_map_commitment(preflight_commitment)?;
let config = RpcSendTransactionConfig { let config = RpcSendTransactionConfig {
encoding: Some(encoding), encoding: Some(encoding),
preflight_commitment: Some(preflight_commitment.commitment),
..config ..config
}; };
let serialized_encoded = serialize_encode_transaction(transaction, encoding)?; let serialized_encoded = serialize_encode_transaction(transaction, encoding)?;
@ -274,8 +303,11 @@ impl RpcClient {
} else { } else {
self.default_cluster_transaction_encoding()? self.default_cluster_transaction_encoding()?
}; };
let commitment = config.commitment.unwrap_or_default();
let commitment = self.maybe_map_commitment(commitment)?;
let config = RpcSimulateTransactionConfig { let config = RpcSimulateTransactionConfig {
encoding: Some(encoding), encoding: Some(encoding),
commitment: Some(commitment),
..config ..config
}; };
let serialized_encoded = serialize_encode_transaction(transaction, encoding)?; let serialized_encoded = serialize_encode_transaction(transaction, encoding)?;
@ -358,7 +390,10 @@ impl RpcClient {
&self, &self,
commitment_config: CommitmentConfig, commitment_config: CommitmentConfig,
) -> ClientResult<Slot> { ) -> ClientResult<Slot> {
self.send(RpcRequest::GetSlot, json!([commitment_config])) self.send(
RpcRequest::GetSlot,
json!([self.maybe_map_commitment(commitment_config)?]),
)
} }
pub fn supply(&self) -> RpcResult<RpcSupply> { pub fn supply(&self) -> RpcResult<RpcSupply> {
@ -369,7 +404,10 @@ impl RpcClient {
&self, &self,
commitment_config: CommitmentConfig, commitment_config: CommitmentConfig,
) -> RpcResult<RpcSupply> { ) -> RpcResult<RpcSupply> {
self.send(RpcRequest::GetSupply, json!([commitment_config])) self.send(
RpcRequest::GetSupply,
json!([self.maybe_map_commitment(commitment_config)?]),
)
} }
pub fn total_supply(&self) -> ClientResult<u64> { pub fn total_supply(&self) -> ClientResult<u64> {
@ -380,13 +418,22 @@ impl RpcClient {
&self, &self,
commitment_config: CommitmentConfig, commitment_config: CommitmentConfig,
) -> ClientResult<u64> { ) -> ClientResult<u64> {
self.send(RpcRequest::GetTotalSupply, json!([commitment_config])) self.send(
RpcRequest::GetTotalSupply,
json!([self.maybe_map_commitment(commitment_config)?]),
)
} }
pub fn get_largest_accounts_with_config( pub fn get_largest_accounts_with_config(
&self, &self,
config: RpcLargestAccountsConfig, config: RpcLargestAccountsConfig,
) -> RpcResult<Vec<RpcAccountBalance>> { ) -> RpcResult<Vec<RpcAccountBalance>> {
let commitment = config.commitment.unwrap_or_default();
let commitment = self.maybe_map_commitment(commitment)?;
let config = RpcLargestAccountsConfig {
commitment: Some(commitment),
..config
};
self.send(RpcRequest::GetLargestAccounts, json!([config])) self.send(RpcRequest::GetLargestAccounts, json!([config]))
} }
@ -398,7 +445,10 @@ impl RpcClient {
&self, &self,
commitment_config: CommitmentConfig, commitment_config: CommitmentConfig,
) -> ClientResult<RpcVoteAccountStatus> { ) -> ClientResult<RpcVoteAccountStatus> {
self.send(RpcRequest::GetVoteAccounts, json!([commitment_config])) self.send(
RpcRequest::GetVoteAccounts,
json!([self.maybe_map_commitment(commitment_config)?]),
)
} }
pub fn wait_for_max_stake( pub fn wait_for_max_stake(
@ -558,7 +608,10 @@ impl RpcClient {
&self, &self,
commitment_config: CommitmentConfig, commitment_config: CommitmentConfig,
) -> ClientResult<EpochInfo> { ) -> ClientResult<EpochInfo> {
self.send(RpcRequest::GetEpochInfo, json!([commitment_config])) self.send(
RpcRequest::GetEpochInfo,
json!([self.maybe_map_commitment(commitment_config)?]),
)
} }
pub fn get_leader_schedule( pub fn get_leader_schedule(
@ -575,7 +628,7 @@ impl RpcClient {
) -> ClientResult<Option<RpcLeaderSchedule>> { ) -> ClientResult<Option<RpcLeaderSchedule>> {
self.send( self.send(
RpcRequest::GetLeaderSchedule, RpcRequest::GetLeaderSchedule,
json!([slot, commitment_config]), json!([slot, self.maybe_map_commitment(commitment_config)?]),
) )
} }
@ -616,7 +669,7 @@ impl RpcClient {
) -> ClientResult<Signature> { ) -> ClientResult<Signature> {
let signature = self.send_transaction(transaction)?; let signature = self.send_transaction(transaction)?;
let recent_blockhash = if uses_durable_nonce(transaction).is_some() { let recent_blockhash = if uses_durable_nonce(transaction).is_some() {
self.get_recent_blockhash_with_commitment(CommitmentConfig::recent())? self.get_recent_blockhash_with_commitment(CommitmentConfig::processed())?
.value .value
.0 .0
} else { } else {
@ -628,7 +681,7 @@ impl RpcClient {
if self if self
.get_fee_calculator_for_blockhash_with_commitment( .get_fee_calculator_for_blockhash_with_commitment(
&recent_blockhash, &recent_blockhash,
CommitmentConfig::recent(), CommitmentConfig::processed(),
)? )?
.value .value
.is_none() .is_none()
@ -674,7 +727,7 @@ impl RpcClient {
) -> RpcResult<Option<Account>> { ) -> RpcResult<Option<Account>> {
let config = RpcAccountInfoConfig { let config = RpcAccountInfoConfig {
encoding: Some(UiAccountEncoding::Base64), encoding: Some(UiAccountEncoding::Base64),
commitment: Some(commitment_config), commitment: Some(self.maybe_map_commitment(commitment_config)?),
data_slice: None, data_slice: None,
}; };
let response = self.sender.send( let response = self.sender.send(
@ -721,7 +774,7 @@ impl RpcClient {
) -> RpcResult<Vec<Option<Account>>> { ) -> RpcResult<Vec<Option<Account>>> {
let config = RpcAccountInfoConfig { let config = RpcAccountInfoConfig {
encoding: Some(UiAccountEncoding::Base64), encoding: Some(UiAccountEncoding::Base64),
commitment: Some(commitment_config), commitment: Some(self.maybe_map_commitment(commitment_config)?),
data_slice: None, data_slice: None,
}; };
let pubkeys: Vec<_> = pubkeys.iter().map(|pubkey| pubkey.to_string()).collect(); let pubkeys: Vec<_> = pubkeys.iter().map(|pubkey| pubkey.to_string()).collect();
@ -775,7 +828,10 @@ impl RpcClient {
) -> RpcResult<u64> { ) -> RpcResult<u64> {
self.send( self.send(
RpcRequest::GetBalance, RpcRequest::GetBalance,
json!([pubkey.to_string(), commitment_config]), json!([
pubkey.to_string(),
self.maybe_map_commitment(commitment_config)?
]),
) )
} }
@ -798,6 +854,16 @@ impl RpcClient {
pubkey: &Pubkey, pubkey: &Pubkey,
config: RpcProgramAccountsConfig, config: RpcProgramAccountsConfig,
) -> ClientResult<Vec<(Pubkey, Account)>> { ) -> ClientResult<Vec<(Pubkey, Account)>> {
let commitment = config.account_config.commitment.unwrap_or_default();
let commitment = self.maybe_map_commitment(commitment)?;
let account_config = RpcAccountInfoConfig {
commitment: Some(commitment),
..config.account_config
};
let config = RpcProgramAccountsConfig {
account_config,
..config
};
let accounts: Vec<RpcKeyedAccount> = self.send( let accounts: Vec<RpcKeyedAccount> = self.send(
RpcRequest::GetProgramAccounts, RpcRequest::GetProgramAccounts,
json!([pubkey.to_string(), config]), json!([pubkey.to_string(), config]),
@ -814,7 +880,10 @@ impl RpcClient {
&self, &self,
commitment_config: CommitmentConfig, commitment_config: CommitmentConfig,
) -> ClientResult<u64> { ) -> ClientResult<u64> {
self.send(RpcRequest::GetTransactionCount, json!([commitment_config])) self.send(
RpcRequest::GetTransactionCount,
json!([self.maybe_map_commitment(commitment_config)?]),
)
} }
pub fn get_recent_blockhash(&self) -> ClientResult<(Hash, FeeCalculator)> { pub fn get_recent_blockhash(&self) -> ClientResult<(Hash, FeeCalculator)> {
@ -836,9 +905,11 @@ impl RpcClient {
fee_calculator, fee_calculator,
last_valid_slot, last_valid_slot,
}, },
}) = }) = self
self.send::<Response<RpcFees>>(RpcRequest::GetFees, json!([commitment_config])) .send::<Response<RpcFees>>(
{ RpcRequest::GetFees,
json!([self.maybe_map_commitment(commitment_config)?]),
) {
(context, blockhash, fee_calculator, last_valid_slot) (context, blockhash, fee_calculator, last_valid_slot)
} else if let Ok(Response { } else if let Ok(Response {
context, context,
@ -849,7 +920,7 @@ impl RpcClient {
}, },
}) = self.send::<Response<RpcBlockhashFeeCalculator>>( }) = self.send::<Response<RpcBlockhashFeeCalculator>>(
RpcRequest::GetRecentBlockhash, RpcRequest::GetRecentBlockhash,
json!([commitment_config]), json!([self.maybe_map_commitment(commitment_config)?]),
) { ) {
(context, blockhash, fee_calculator, 0) (context, blockhash, fee_calculator, 0)
} else { } else {
@ -887,7 +958,10 @@ impl RpcClient {
) -> RpcResult<Option<FeeCalculator>> { ) -> RpcResult<Option<FeeCalculator>> {
let Response { context, value } = self.send::<Response<Option<RpcFeeCalculator>>>( let Response { context, value } = self.send::<Response<Option<RpcFeeCalculator>>>(
RpcRequest::GetFeeCalculatorForBlockhash, RpcRequest::GetFeeCalculatorForBlockhash,
json!([blockhash.to_string(), commitment_config]), json!([
blockhash.to_string(),
self.maybe_map_commitment(commitment_config)?
]),
)?; )?;
Ok(Response { Ok(Response {
@ -966,7 +1040,7 @@ impl RpcClient {
) -> RpcResult<Option<UiTokenAccount>> { ) -> RpcResult<Option<UiTokenAccount>> {
let config = RpcAccountInfoConfig { let config = RpcAccountInfoConfig {
encoding: Some(UiAccountEncoding::JsonParsed), encoding: Some(UiAccountEncoding::JsonParsed),
commitment: Some(commitment_config), commitment: Some(self.maybe_map_commitment(commitment_config)?),
data_slice: None, data_slice: None,
}; };
let response = self.sender.send( let response = self.sender.send(
@ -1027,7 +1101,10 @@ impl RpcClient {
) -> RpcResult<UiTokenAmount> { ) -> RpcResult<UiTokenAmount> {
self.send( self.send(
RpcRequest::GetTokenAccountBalance, RpcRequest::GetTokenAccountBalance,
json!([pubkey.to_string(), commitment_config]), json!([
pubkey.to_string(),
self.maybe_map_commitment(commitment_config)?
]),
) )
} }
@ -1060,7 +1137,7 @@ impl RpcClient {
let config = RpcAccountInfoConfig { let config = RpcAccountInfoConfig {
encoding: Some(UiAccountEncoding::JsonParsed), encoding: Some(UiAccountEncoding::JsonParsed),
commitment: Some(commitment_config), commitment: Some(self.maybe_map_commitment(commitment_config)?),
data_slice: None, data_slice: None,
}; };
@ -1099,7 +1176,7 @@ impl RpcClient {
let config = RpcAccountInfoConfig { let config = RpcAccountInfoConfig {
encoding: Some(UiAccountEncoding::JsonParsed), encoding: Some(UiAccountEncoding::JsonParsed),
commitment: Some(commitment_config), commitment: Some(self.maybe_map_commitment(commitment_config)?),
data_slice: None, data_slice: None,
}; };
@ -1122,7 +1199,10 @@ impl RpcClient {
) -> RpcResult<UiTokenAmount> { ) -> RpcResult<UiTokenAmount> {
self.send( self.send(
RpcRequest::GetTokenSupply, RpcRequest::GetTokenSupply,
json!([mint.to_string(), commitment_config]), json!([
mint.to_string(),
self.maybe_map_commitment(commitment_config)?
]),
) )
} }
@ -1327,9 +1407,10 @@ impl RpcClient {
commitment: CommitmentConfig, commitment: CommitmentConfig,
config: RpcSendTransactionConfig, config: RpcSendTransactionConfig,
) -> ClientResult<Signature> { ) -> ClientResult<Signature> {
let desired_confirmations = match commitment.commitment { let desired_confirmations = if commitment.is_finalized() {
CommitmentLevel::Max | CommitmentLevel::Root => MAX_LOCKOUT_HISTORY + 1, MAX_LOCKOUT_HISTORY + 1
_ => 1, } else {
1
}; };
let mut confirmations = 0; let mut confirmations = 0;
@ -1340,7 +1421,7 @@ impl RpcClient {
confirmations, desired_confirmations, transaction.signatures[0], confirmations, desired_confirmations, transaction.signatures[0],
)); ));
let recent_blockhash = if uses_durable_nonce(transaction).is_some() { let recent_blockhash = if uses_durable_nonce(transaction).is_some() {
self.get_recent_blockhash_with_commitment(CommitmentConfig::recent())? self.get_recent_blockhash_with_commitment(CommitmentConfig::processed())?
.value .value
.0 .0
} else { } else {
@ -1349,13 +1430,13 @@ impl RpcClient {
let signature = self.send_transaction_with_config(transaction, config)?; let signature = self.send_transaction_with_config(transaction, config)?;
let (signature, status) = loop { let (signature, status) = loop {
// Get recent commitment in order to count confirmations for successful transactions // Get recent commitment in order to count confirmations for successful transactions
let status = let status = self
self.get_signature_status_with_commitment(&signature, CommitmentConfig::recent())?; .get_signature_status_with_commitment(&signature, CommitmentConfig::processed())?;
if status.is_none() { if status.is_none() {
if self if self
.get_fee_calculator_for_blockhash_with_commitment( .get_fee_calculator_for_blockhash_with_commitment(
&recent_blockhash, &recent_blockhash,
CommitmentConfig::recent(), CommitmentConfig::processed(),
)? )?
.value .value
.is_none() .is_none()

View File

@ -248,7 +248,7 @@ mod tests {
#[test] #[test]
fn test_build_request_json_config_options() { fn test_build_request_json_config_options() {
let commitment_config = CommitmentConfig { let commitment_config = CommitmentConfig {
commitment: CommitmentLevel::Max, commitment: CommitmentLevel::Finalized,
}; };
let addr = json!("deadbeefXjn8o3yroDHxUtKsZZgoy4GPkPPXfouKNHhx"); let addr = json!("deadbeefXjn8o3yroDHxUtKsZZgoy4GPkPPXfouKNHhx");

View File

@ -139,16 +139,14 @@ pub struct JsonRpcRequestProcessor {
impl Metadata for JsonRpcRequestProcessor {} impl Metadata for JsonRpcRequestProcessor {}
impl JsonRpcRequestProcessor { impl JsonRpcRequestProcessor {
#[allow(deprecated)]
fn bank(&self, commitment: Option<CommitmentConfig>) -> Arc<Bank> { fn bank(&self, commitment: Option<CommitmentConfig>) -> Arc<Bank> {
debug!("RPC commitment_config: {:?}", commitment); debug!("RPC commitment_config: {:?}", commitment);
let r_bank_forks = self.bank_forks.read().unwrap(); let r_bank_forks = self.bank_forks.read().unwrap();
let commitment_level = match commitment { let commitment = commitment.unwrap_or_default();
None => CommitmentLevel::Max,
Some(config) => config.commitment,
};
if commitment_level == CommitmentLevel::SingleGossip { if commitment.is_confirmed() {
let bank = self let bank = self
.optimistically_confirmed_bank .optimistically_confirmed_bank
.read() .read()
@ -163,22 +161,26 @@ impl JsonRpcRequestProcessor {
.block_commitment_cache .block_commitment_cache
.read() .read()
.unwrap() .unwrap()
.slot_with_commitment(commitment_level); .slot_with_commitment(commitment.commitment);
match commitment_level { match commitment.commitment {
CommitmentLevel::Recent => { // Recent variant is deprecated
CommitmentLevel::Recent | CommitmentLevel::Processed => {
debug!("RPC using the heaviest slot: {:?}", slot); debug!("RPC using the heaviest slot: {:?}", slot);
} }
// Root variant is deprecated
CommitmentLevel::Root => { CommitmentLevel::Root => {
debug!("RPC using node root: {:?}", slot); debug!("RPC using node root: {:?}", slot);
} }
// Single variant is deprecated
CommitmentLevel::Single => { CommitmentLevel::Single => {
debug!("RPC using confirmed slot: {:?}", slot); debug!("RPC using confirmed slot: {:?}", slot);
} }
CommitmentLevel::Max => { // Max variant is deprecated
CommitmentLevel::Max | CommitmentLevel::Finalized => {
debug!("RPC using block: {:?}", slot); debug!("RPC using block: {:?}", slot);
} }
CommitmentLevel::SingleGossip => unreachable!(), CommitmentLevel::SingleGossip | CommitmentLevel::Confirmed => unreachable!(), // SingleGossip variant is deprecated
}; };
r_bank_forks.get(slot).cloned().unwrap_or_else(|| { r_bank_forks.get(slot).cloned().unwrap_or_else(|| {
@ -195,7 +197,7 @@ impl JsonRpcRequestProcessor {
// For more information, see https://github.com/solana-labs/solana/issues/11078 // For more information, see https://github.com/solana-labs/solana/issues/11078
warn!( warn!(
"Bank with {:?} not found at slot: {:?}", "Bank with {:?} not found at slot: {:?}",
commitment_level, slot commitment.commitment, slot
); );
r_bank_forks.root_bank() r_bank_forks.root_bank()
}) })
@ -380,7 +382,7 @@ impl JsonRpcRequestProcessor {
pub fn get_epoch_schedule(&self) -> EpochSchedule { pub fn get_epoch_schedule(&self) -> EpochSchedule {
// Since epoch schedule data comes from the genesis config, any commitment level should be // Since epoch schedule data comes from the genesis config, any commitment level should be
// fine // fine
let bank = self.bank(Some(CommitmentConfig::root())); let bank = self.bank(Some(CommitmentConfig::finalized()));
*bank.epoch_schedule() *bank.epoch_schedule()
} }
@ -873,7 +875,7 @@ impl JsonRpcRequestProcessor {
let search_transaction_history = config let search_transaction_history = config
.map(|x| x.search_transaction_history) .map(|x| x.search_transaction_history)
.unwrap_or(false); .unwrap_or(false);
let bank = self.bank(Some(CommitmentConfig::recent())); let bank = self.bank(Some(CommitmentConfig::processed()));
for signature in signatures { for signature in signatures {
let status = if let Some(status) = self.get_transaction_status(signature, &bank) { let status = if let Some(status) = self.get_transaction_status(signature, &bank) {
@ -925,7 +927,7 @@ impl JsonRpcRequestProcessor {
let (slot, status) = bank.get_signature_status_slot(&signature)?; let (slot, status) = bank.get_signature_status_slot(&signature)?;
let r_block_commitment_cache = self.block_commitment_cache.read().unwrap(); let r_block_commitment_cache = self.block_commitment_cache.read().unwrap();
let optimistically_confirmed_bank = self.bank(Some(CommitmentConfig::single_gossip())); let optimistically_confirmed_bank = self.bank(Some(CommitmentConfig::confirmed()));
let optimistically_confirmed = let optimistically_confirmed =
optimistically_confirmed_bank.get_signature_status_slot(&signature); optimistically_confirmed_bank.get_signature_status_slot(&signature);
@ -5376,7 +5378,7 @@ pub mod tests {
let req = format!( let req = format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"getVoteAccounts","params":{}}}"#, r#"{{"jsonrpc":"2.0","id":1,"method":"getVoteAccounts","params":{}}}"#,
json!([CommitmentConfig::recent()]) json!([CommitmentConfig::processed()])
); );
let res = io.handle_request_sync(&req, meta.clone()); let res = io.handle_request_sync(&req, meta.clone());
@ -5422,7 +5424,7 @@ pub mod tests {
{ {
let req = format!( let req = format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"getVoteAccounts","params":{}}}"#, r#"{{"jsonrpc":"2.0","id":1,"method":"getVoteAccounts","params":{}}}"#,
json!([CommitmentConfig::recent()]) json!([CommitmentConfig::processed()])
); );
let res = io.handle_request_sync(&req, meta); let res = io.handle_request_sync(&req, meta);
@ -6110,7 +6112,8 @@ pub mod tests {
let mut io = MetaIoHandler::default(); let mut io = MetaIoHandler::default();
io.extend_with(RpcSolImpl.to_delegate()); io.extend_with(RpcSolImpl.to_delegate());
let req = r#"{"jsonrpc":"2.0","id":1,"method":"getSlot","params":[{"commitment":"singleGossip"}]}"#; let req =
r#"{"jsonrpc":"2.0","id":1,"method":"getSlot","params":[{"commitment":"confirmed"}]}"#;
let res = io.handle_request_sync(req, meta.clone()); let res = io.handle_request_sync(req, meta.clone());
let json: Value = serde_json::from_str(&res.unwrap()).unwrap(); let json: Value = serde_json::from_str(&res.unwrap()).unwrap();
let slot: Slot = serde_json::from_value(json["result"].clone()).unwrap(); let slot: Slot = serde_json::from_value(json["result"].clone()).unwrap();
@ -6123,7 +6126,8 @@ pub mod tests {
&subscriptions, &subscriptions,
&mut pending_optimistically_confirmed_banks, &mut pending_optimistically_confirmed_banks,
); );
let req = r#"{"jsonrpc":"2.0","id":1,"method":"getSlot","params":[{"commitment": "singleGossip"}]}"#; let req =
r#"{"jsonrpc":"2.0","id":1,"method":"getSlot","params":[{"commitment": "confirmed"}]}"#;
let res = io.handle_request_sync(&req, meta.clone()); let res = io.handle_request_sync(&req, meta.clone());
let json: Value = serde_json::from_str(&res.unwrap()).unwrap(); let json: Value = serde_json::from_str(&res.unwrap()).unwrap();
let slot: Slot = serde_json::from_value(json["result"].clone()).unwrap(); let slot: Slot = serde_json::from_value(json["result"].clone()).unwrap();
@ -6137,7 +6141,8 @@ pub mod tests {
&subscriptions, &subscriptions,
&mut pending_optimistically_confirmed_banks, &mut pending_optimistically_confirmed_banks,
); );
let req = r#"{"jsonrpc":"2.0","id":1,"method":"getSlot","params":[{"commitment": "singleGossip"}]}"#; let req =
r#"{"jsonrpc":"2.0","id":1,"method":"getSlot","params":[{"commitment": "confirmed"}]}"#;
let res = io.handle_request_sync(&req, meta.clone()); let res = io.handle_request_sync(&req, meta.clone());
let json: Value = serde_json::from_str(&res.unwrap()).unwrap(); let json: Value = serde_json::from_str(&res.unwrap()).unwrap();
let slot: Slot = serde_json::from_value(json["result"].clone()).unwrap(); let slot: Slot = serde_json::from_value(json["result"].clone()).unwrap();
@ -6151,7 +6156,8 @@ pub mod tests {
&subscriptions, &subscriptions,
&mut pending_optimistically_confirmed_banks, &mut pending_optimistically_confirmed_banks,
); );
let req = r#"{"jsonrpc":"2.0","id":1,"method":"getSlot","params":[{"commitment": "singleGossip"}]}"#; let req =
r#"{"jsonrpc":"2.0","id":1,"method":"getSlot","params":[{"commitment": "confirmed"}]}"#;
let res = io.handle_request_sync(&req, meta.clone()); let res = io.handle_request_sync(&req, meta.clone());
let json: Value = serde_json::from_str(&res.unwrap()).unwrap(); let json: Value = serde_json::from_str(&res.unwrap()).unwrap();
let slot: Slot = serde_json::from_value(json["result"].clone()).unwrap(); let slot: Slot = serde_json::from_value(json["result"].clone()).unwrap();
@ -6166,7 +6172,8 @@ pub mod tests {
&subscriptions, &subscriptions,
&mut pending_optimistically_confirmed_banks, &mut pending_optimistically_confirmed_banks,
); );
let req = r#"{"jsonrpc":"2.0","id":1,"method":"getSlot","params":[{"commitment": "singleGossip"}]}"#; let req =
r#"{"jsonrpc":"2.0","id":1,"method":"getSlot","params":[{"commitment": "confirmed"}]}"#;
let res = io.handle_request_sync(&req, meta); let res = io.handle_request_sync(&req, meta);
let json: Value = serde_json::from_str(&res.unwrap()).unwrap(); let json: Value = serde_json::from_str(&res.unwrap()).unwrap();
let slot: Slot = serde_json::from_value(json["result"].clone()).unwrap(); let slot: Slot = serde_json::from_value(json["result"].clone()).unwrap();

View File

@ -579,7 +579,7 @@ mod tests {
subscriber, subscriber,
tx.signatures[0].to_string(), tx.signatures[0].to_string(),
Some(RpcSignatureSubscribeConfig { Some(RpcSignatureSubscribeConfig {
commitment: Some(CommitmentConfig::single()), commitment: Some(CommitmentConfig::finalized()),
..RpcSignatureSubscribeConfig::default() ..RpcSignatureSubscribeConfig::default()
}), }),
); );
@ -612,7 +612,7 @@ mod tests {
subscriber, subscriber,
tx.signatures[0].to_string(), tx.signatures[0].to_string(),
Some(RpcSignatureSubscribeConfig { Some(RpcSignatureSubscribeConfig {
commitment: Some(CommitmentConfig::single()), commitment: Some(CommitmentConfig::finalized()),
enable_received_notification: Some(true), enable_received_notification: Some(true),
}), }),
); );
@ -721,7 +721,7 @@ mod tests {
subscriber, subscriber,
stake_account.pubkey().to_string(), stake_account.pubkey().to_string(),
Some(RpcAccountInfoConfig { Some(RpcAccountInfoConfig {
commitment: Some(CommitmentConfig::recent()), commitment: Some(CommitmentConfig::processed()),
encoding: None, encoding: None,
data_slice: None, data_slice: None,
}), }),
@ -830,7 +830,7 @@ mod tests {
subscriber, subscriber,
nonce_account.pubkey().to_string(), nonce_account.pubkey().to_string(),
Some(RpcAccountInfoConfig { Some(RpcAccountInfoConfig {
commitment: Some(CommitmentConfig::recent()), commitment: Some(CommitmentConfig::processed()),
encoding: Some(UiAccountEncoding::JsonParsed), encoding: Some(UiAccountEncoding::JsonParsed),
data_slice: None, data_slice: None,
}), }),
@ -952,7 +952,7 @@ mod tests {
subscriber, subscriber,
bob.pubkey().to_string(), bob.pubkey().to_string(),
Some(RpcAccountInfoConfig { Some(RpcAccountInfoConfig {
commitment: Some(CommitmentConfig::root()), commitment: Some(CommitmentConfig::finalized()),
encoding: None, encoding: None,
data_slice: None, data_slice: None,
}), }),
@ -1006,7 +1006,7 @@ mod tests {
subscriber, subscriber,
bob.pubkey().to_string(), bob.pubkey().to_string(),
Some(RpcAccountInfoConfig { Some(RpcAccountInfoConfig {
commitment: Some(CommitmentConfig::root()), commitment: Some(CommitmentConfig::finalized()),
encoding: None, encoding: None,
data_slice: None, data_slice: None,
}), }),

View File

@ -31,7 +31,7 @@ use solana_runtime::{
use solana_sdk::{ use solana_sdk::{
account::Account, account::Account,
clock::{Slot, UnixTimestamp}, clock::{Slot, UnixTimestamp},
commitment_config::{CommitmentConfig, CommitmentLevel}, commitment_config::CommitmentConfig,
pubkey::Pubkey, pubkey::Pubkey,
signature::Signature, signature::Signature,
transaction, transaction,
@ -227,14 +227,14 @@ where
}, },
) in hashmap.iter() ) in hashmap.iter()
{ {
let slot = match commitment.commitment { let slot = if commitment.is_finalized() {
CommitmentLevel::Max => commitment_slots.highest_confirmed_root, commitment_slots.highest_confirmed_root
CommitmentLevel::Recent => commitment_slots.slot, } else if commitment.is_confirmed() {
CommitmentLevel::Root => commitment_slots.root, commitment_slots.highest_confirmed_slot
CommitmentLevel::Single | CommitmentLevel::SingleGossip => { } else {
commitment_slots.highest_confirmed_slot commitment_slots.slot
}
}; };
if let Some(bank) = bank_forks.read().unwrap().get(slot).cloned() { if let Some(bank) = bank_forks.read().unwrap().get(slot).cloned() {
let results = bank_method(&bank, hashmap_key); let results = bank_method(&bank, hashmap_key);
let mut w_last_notified_slot = last_notified_slot.write().unwrap(); let mut w_last_notified_slot = last_notified_slot.write().unwrap();
@ -636,28 +636,23 @@ impl RpcSubscriptions {
let config = config.unwrap_or_default(); let config = config.unwrap_or_default();
let commitment = config let commitment = config
.commitment .commitment
.unwrap_or_else(CommitmentConfig::single_gossip); .unwrap_or_else(CommitmentConfig::confirmed);
let slot = match commitment.commitment { let slot = if commitment.is_finalized() {
CommitmentLevel::Max => self self.block_commitment_cache
.block_commitment_cache
.read() .read()
.unwrap() .unwrap()
.highest_confirmed_root(), .highest_confirmed_root()
CommitmentLevel::Recent => self.block_commitment_cache.read().unwrap().slot(), } else if commitment.is_confirmed() {
CommitmentLevel::Root => self.block_commitment_cache.read().unwrap().root(), self.optimistically_confirmed_bank
CommitmentLevel::Single => self
.block_commitment_cache
.read()
.unwrap()
.highest_confirmed_slot(),
CommitmentLevel::SingleGossip => self
.optimistically_confirmed_bank
.read() .read()
.unwrap() .unwrap()
.bank .bank
.slot(), .slot()
} else {
self.block_commitment_cache.read().unwrap().slot()
}; };
let last_notified_slot = if let Some((_account, slot)) = self let last_notified_slot = if let Some((_account, slot)) = self
.bank_forks .bank_forks
.read() .read()
@ -670,7 +665,7 @@ impl RpcSubscriptions {
0 0
}; };
let mut subscriptions = if commitment.commitment == CommitmentLevel::SingleGossip { let mut subscriptions = if commitment.is_confirmed() {
self.subscriptions self.subscriptions
.gossip_account_subscriptions .gossip_account_subscriptions
.write() .write()
@ -715,9 +710,9 @@ impl RpcSubscriptions {
let commitment = config let commitment = config
.account_config .account_config
.commitment .commitment
.unwrap_or_else(CommitmentConfig::single_gossip); .unwrap_or_else(CommitmentConfig::confirmed);
let mut subscriptions = if commitment.commitment == CommitmentLevel::SingleGossip { let mut subscriptions = if commitment.is_confirmed() {
self.subscriptions self.subscriptions
.gossip_program_subscriptions .gossip_program_subscriptions
.write() .write()
@ -762,10 +757,10 @@ impl RpcSubscriptions {
sub_id: SubscriptionId, sub_id: SubscriptionId,
subscriber: Subscriber<Response<RpcLogsResponse>>, subscriber: Subscriber<Response<RpcLogsResponse>>,
) { ) {
let commitment = commitment.unwrap_or_else(CommitmentConfig::single_gossip); let commitment = commitment.unwrap_or_else(CommitmentConfig::confirmed);
{ {
let mut subscriptions = if commitment.commitment == CommitmentLevel::SingleGossip { let mut subscriptions = if commitment.is_confirmed() {
self.subscriptions self.subscriptions
.gossip_logs_subscriptions .gossip_logs_subscriptions
.write() .write()
@ -873,9 +868,9 @@ impl RpcSubscriptions {
.map(|config| (config.commitment, config.enable_received_notification)) .map(|config| (config.commitment, config.enable_received_notification))
.unwrap_or_default(); .unwrap_or_default();
let commitment = commitment.unwrap_or_else(CommitmentConfig::single_gossip); let commitment = commitment.unwrap_or_else(CommitmentConfig::confirmed);
let mut subscriptions = if commitment.commitment == CommitmentLevel::SingleGossip { let mut subscriptions = if commitment.is_confirmed() {
self.subscriptions self.subscriptions
.gossip_signature_subscriptions .gossip_signature_subscriptions
.write() .write()
@ -915,7 +910,7 @@ impl RpcSubscriptions {
self.enqueue_notification(NotificationEntry::Bank(commitment_slots)); self.enqueue_notification(NotificationEntry::Bank(commitment_slots));
} }
/// Notify SingleGossip commitment-level subscribers of changes to any accounts or new /// Notify Confirmed commitment-level subscribers of changes to any accounts or new
/// signatures. /// signatures.
pub fn notify_gossip_subscribers(&self, slot: Slot) { pub fn notify_gossip_subscribers(&self, slot: Slot) {
self.enqueue_notification(NotificationEntry::Gossip(slot)); self.enqueue_notification(NotificationEntry::Gossip(slot));
@ -1374,7 +1369,7 @@ pub(crate) mod tests {
subscriptions.add_account_subscription( subscriptions.add_account_subscription(
alice.pubkey(), alice.pubkey(),
Some(RpcAccountInfoConfig { Some(RpcAccountInfoConfig {
commitment: Some(CommitmentConfig::recent()), commitment: Some(CommitmentConfig::processed()),
encoding: None, encoding: None,
data_slice: None, data_slice: None,
}), }),
@ -1433,7 +1428,7 @@ pub(crate) mod tests {
subscriptions.add_account_subscription( subscriptions.add_account_subscription(
alice.pubkey(), alice.pubkey(),
Some(RpcAccountInfoConfig { Some(RpcAccountInfoConfig {
commitment: Some(CommitmentConfig::recent()), commitment: Some(CommitmentConfig::processed()),
encoding: None, encoding: None,
data_slice: None, data_slice: None,
}), }),
@ -1529,7 +1524,7 @@ pub(crate) mod tests {
solana_stake_program::id(), solana_stake_program::id(),
Some(RpcProgramAccountsConfig { Some(RpcProgramAccountsConfig {
account_config: RpcAccountInfoConfig { account_config: RpcAccountInfoConfig {
commitment: Some(CommitmentConfig::recent()), commitment: Some(CommitmentConfig::processed()),
..RpcAccountInfoConfig::default() ..RpcAccountInfoConfig::default()
}, },
..RpcProgramAccountsConfig::default() ..RpcProgramAccountsConfig::default()
@ -1658,7 +1653,7 @@ pub(crate) mod tests {
subscriptions.add_signature_subscription( subscriptions.add_signature_subscription(
past_bank_tx.signatures[0], past_bank_tx.signatures[0],
Some(RpcSignatureSubscribeConfig { Some(RpcSignatureSubscribeConfig {
commitment: Some(CommitmentConfig::recent()), commitment: Some(CommitmentConfig::processed()),
enable_received_notification: Some(false), enable_received_notification: Some(false),
}), }),
SubscriptionId::Number(1), SubscriptionId::Number(1),
@ -1667,7 +1662,7 @@ pub(crate) mod tests {
subscriptions.add_signature_subscription( subscriptions.add_signature_subscription(
past_bank_tx.signatures[0], past_bank_tx.signatures[0],
Some(RpcSignatureSubscribeConfig { Some(RpcSignatureSubscribeConfig {
commitment: Some(CommitmentConfig::root()), commitment: Some(CommitmentConfig::finalized()),
enable_received_notification: Some(false), enable_received_notification: Some(false),
}), }),
SubscriptionId::Number(2), SubscriptionId::Number(2),
@ -1676,7 +1671,7 @@ pub(crate) mod tests {
subscriptions.add_signature_subscription( subscriptions.add_signature_subscription(
processed_tx.signatures[0], processed_tx.signatures[0],
Some(RpcSignatureSubscribeConfig { Some(RpcSignatureSubscribeConfig {
commitment: Some(CommitmentConfig::recent()), commitment: Some(CommitmentConfig::processed()),
enable_received_notification: Some(false), enable_received_notification: Some(false),
}), }),
SubscriptionId::Number(3), SubscriptionId::Number(3),
@ -1685,7 +1680,7 @@ pub(crate) mod tests {
subscriptions.add_signature_subscription( subscriptions.add_signature_subscription(
unprocessed_tx.signatures[0], unprocessed_tx.signatures[0],
Some(RpcSignatureSubscribeConfig { Some(RpcSignatureSubscribeConfig {
commitment: Some(CommitmentConfig::recent()), commitment: Some(CommitmentConfig::processed()),
enable_received_notification: Some(false), enable_received_notification: Some(false),
}), }),
SubscriptionId::Number(4), SubscriptionId::Number(4),
@ -1695,7 +1690,7 @@ pub(crate) mod tests {
subscriptions.add_signature_subscription( subscriptions.add_signature_subscription(
unprocessed_tx.signatures[0], unprocessed_tx.signatures[0],
Some(RpcSignatureSubscribeConfig { Some(RpcSignatureSubscribeConfig {
commitment: Some(CommitmentConfig::recent()), commitment: Some(CommitmentConfig::processed()),
enable_received_notification: Some(true), enable_received_notification: Some(true),
}), }),
SubscriptionId::Number(5), SubscriptionId::Number(5),
@ -1892,7 +1887,7 @@ pub(crate) mod tests {
fn test_add_and_remove_subscription() { fn test_add_and_remove_subscription() {
let mut subscriptions: HashMap<u64, HashMap<SubscriptionId, SubscriptionData<(), ()>>> = let mut subscriptions: HashMap<u64, HashMap<SubscriptionId, SubscriptionData<(), ()>>> =
HashMap::new(); HashMap::new();
let commitment = CommitmentConfig::single_gossip(); let commitment = CommitmentConfig::confirmed();
let num_keys = 5; let num_keys = 5;
for key in 0..num_keys { for key in 0..num_keys {
@ -1982,7 +1977,7 @@ pub(crate) mod tests {
subscriptions.add_account_subscription( subscriptions.add_account_subscription(
alice.pubkey(), alice.pubkey(),
Some(RpcAccountInfoConfig { Some(RpcAccountInfoConfig {
commitment: Some(CommitmentConfig::single_gossip()), commitment: Some(CommitmentConfig::confirmed()),
encoding: None, encoding: None,
data_slice: None, data_slice: None,
}), }),
@ -2063,7 +2058,7 @@ pub(crate) mod tests {
subscriptions.add_account_subscription( subscriptions.add_account_subscription(
alice.pubkey(), alice.pubkey(),
Some(RpcAccountInfoConfig { Some(RpcAccountInfoConfig {
commitment: Some(CommitmentConfig::single_gossip()), commitment: Some(CommitmentConfig::confirmed()),
encoding: None, encoding: None,
data_slice: None, data_slice: None,
}), }),

View File

@ -416,7 +416,7 @@ impl TestValidator {
// due to a bug in the Bank) // due to a bug in the Bank)
{ {
let rpc_client = let rpc_client =
RpcClient::new_with_commitment(rpc_url.clone(), CommitmentConfig::recent()); RpcClient::new_with_commitment(rpc_url.clone(), CommitmentConfig::processed());
let fee_rate_governor = rpc_client let fee_rate_governor = rpc_client
.get_fee_rate_governor() .get_fee_rate_governor()
.expect("get_fee_rate_governor") .expect("get_fee_rate_governor")
@ -475,7 +475,7 @@ impl TestValidator {
/// associated fee calculator /// associated fee calculator
pub fn rpc_client(&self) -> (RpcClient, Hash, FeeCalculator) { pub fn rpc_client(&self) -> (RpcClient, Hash, FeeCalculator) {
let rpc_client = let rpc_client =
RpcClient::new_with_commitment(self.rpc_url.clone(), CommitmentConfig::recent()); RpcClient::new_with_commitment(self.rpc_url.clone(), CommitmentConfig::processed());
let (recent_blockhash, fee_calculator) = rpc_client let (recent_blockhash, fee_calculator) = rpc_client
.get_recent_blockhash() .get_recent_blockhash()
.expect("get_recent_blockhash"); .expect("get_recent_blockhash");

View File

@ -498,7 +498,7 @@ impl Validator {
}; };
if config.dev_halt_at_slot.is_some() { if config.dev_halt_at_slot.is_some() {
// Simulate a confirmed root to avoid RPC errors with CommitmentConfig::max() and // Simulate a confirmed root to avoid RPC errors with CommitmentConfig::finalized() and
// to ensure RPC endpoints like getConfirmedBlock, which require a confirmed root, work // to ensure RPC endpoints like getConfirmedBlock, which require a confirmed root, work
block_commitment_cache block_commitment_cache
.write() .write()

View File

@ -247,7 +247,7 @@ fn test_rpc_subscriptions() {
let rpc_client = RpcClient::new(test_validator.rpc_url()); let rpc_client = RpcClient::new(test_validator.rpc_url());
let mut mint_balance = rpc_client let mut mint_balance = rpc_client
.get_balance_with_commitment(&alice.pubkey(), CommitmentConfig::recent()) .get_balance_with_commitment(&alice.pubkey(), CommitmentConfig::processed())
.unwrap() .unwrap()
.value; .value;
assert!(mint_balance >= transactions.len() as u64); assert!(mint_balance >= transactions.len() as u64);
@ -264,7 +264,7 @@ fn test_rpc_subscriptions() {
let expected_mint_balance = mint_balance - transactions.len() as u64; let expected_mint_balance = mint_balance - transactions.len() as u64;
while mint_balance != expected_mint_balance && now.elapsed() < Duration::from_secs(5) { while mint_balance != expected_mint_balance && now.elapsed() < Duration::from_secs(5) {
mint_balance = rpc_client mint_balance = rpc_client
.get_balance_with_commitment(&alice.pubkey(), CommitmentConfig::recent()) .get_balance_with_commitment(&alice.pubkey(), CommitmentConfig::processed())
.unwrap() .unwrap()
.value; .value;
sleep(Duration::from_millis(100)); sleep(Duration::from_millis(100));

View File

@ -134,22 +134,20 @@ to report progress and higher levels to ensure the state will not be rolled back
In descending order of commitment (most finalized to least finalized), clients In descending order of commitment (most finalized to least finalized), clients
may specify: may specify:
- `"max"` - the node will query the most recent block confirmed by supermajority - `"finalized"` - the node will query the most recent block confirmed by supermajority
of the cluster as having reached maximum lockout, meaning the cluster has of the cluster as having reached maximum lockout, meaning the cluster has
recognized this block as finalized recognized this block as finalized
- `"root"` - the node will query the most recent block having reached maximum - `"confirmed"` - the node will query the most recent block that has been voted on by supermajority of the cluster.
lockout on this node, meaning the node has recognized this block as finalized
- `"singleGossip"` - the node will query the most recent block that has been voted on by supermajority of the cluster.
- It incorporates votes from gossip and replay. - It incorporates votes from gossip and replay.
- It does not count votes on descendants of a block, only direct votes on that block. - It does not count votes on descendants of a block, only direct votes on that block.
- This confirmation level also upholds "optimistic confirmation" guarantees in - This confirmation level also upholds "optimistic confirmation" guarantees in
release 1.3 and onwards. release 1.3 and onwards.
- `"recent"` - the node will query its most recent block. Note that the block - `"processed"` - the node will query its most recent block. Note that the block
may not be complete. may not be complete.
For processing many dependent transactions in series, it's recommended to use For processing many dependent transactions in series, it's recommended to use
`"singleGossip"` commitment, which balances speed with rollback safety. `"confirmed"` commitment, which balances speed with rollback safety.
For total safety, it's recommended to use`"max"` commitment. For total safety, it's recommended to use`"finalized"` commitment.
#### Example #### Example
@ -2966,7 +2964,7 @@ After connecting to the RPC PubSub websocket at `ws://<ADDRESS>/`:
- Submit subscription requests to the websocket using the methods below - Submit subscription requests to the websocket using the methods below
- Multiple subscriptions may be active at once - Multiple subscriptions may be active at once
- Many subscriptions take the optional [`commitment` parameter](jsonrpc-api.md#configuring-state-commitment), defining how finalized a change should be to trigger a notification. For subscriptions, if commitment is unspecified, the default value is `"singleGossip"`. - Many subscriptions take the optional [`commitment` parameter](jsonrpc-api.md#configuring-state-commitment), defining how finalized a change should be to trigger a notification. For subscriptions, if commitment is unspecified, the default value is `"confirmed"`.
### accountSubscribe ### accountSubscribe

View File

@ -149,7 +149,7 @@ vote, and vote account pubkey responsible for the vote.
Together, the transaction merkle and optimistic confirmation proofs can be Together, the transaction merkle and optimistic confirmation proofs can be
provided over RPC to subscribers by extending the existing signature provided over RPC to subscribers by extending the existing signature
subscrption logic. Clients who subscribe to the "SingleGossip" confirmation subscrption logic. Clients who subscribe to the "Confirmed" confirmation
level are already notified when optimistic confirmation is detected, a flag level are already notified when optimistic confirmation is detected, a flag
can be provided to signal the two proofs above should also be returned. can be provided to signal the two proofs above should also be returned.

View File

@ -49,11 +49,14 @@ pub fn spend_and_verify_all_nodes<S: ::std::hash::BuildHasher>(
let random_keypair = Keypair::new(); let random_keypair = Keypair::new();
let client = create_client(ingress_node.client_facing_addr(), VALIDATOR_PORT_RANGE); let client = create_client(ingress_node.client_facing_addr(), VALIDATOR_PORT_RANGE);
let bal = client let bal = client
.poll_get_balance_with_commitment(&funding_keypair.pubkey(), CommitmentConfig::recent()) .poll_get_balance_with_commitment(
&funding_keypair.pubkey(),
CommitmentConfig::processed(),
)
.expect("balance in source"); .expect("balance in source");
assert!(bal > 0); assert!(bal > 0);
let (blockhash, _fee_calculator, _last_valid_slot) = client let (blockhash, _fee_calculator, _last_valid_slot) = client
.get_recent_blockhash_with_commitment(CommitmentConfig::recent()) .get_recent_blockhash_with_commitment(CommitmentConfig::processed())
.unwrap(); .unwrap();
let mut transaction = let mut transaction =
system_transaction::transfer(&funding_keypair, &random_keypair.pubkey(), 1, blockhash); system_transaction::transfer(&funding_keypair, &random_keypair.pubkey(), 1, blockhash);
@ -78,7 +81,7 @@ pub fn verify_balances<S: ::std::hash::BuildHasher>(
let client = create_client(node.client_facing_addr(), VALIDATOR_PORT_RANGE); let client = create_client(node.client_facing_addr(), VALIDATOR_PORT_RANGE);
for (pk, b) in expected_balances { for (pk, b) in expected_balances {
let bal = client let bal = client
.poll_get_balance_with_commitment(&pk, CommitmentConfig::recent()) .poll_get_balance_with_commitment(&pk, CommitmentConfig::processed())
.expect("balance in source"); .expect("balance in source");
assert_eq!(bal, b); assert_eq!(bal, b);
} }
@ -95,11 +98,14 @@ pub fn send_many_transactions(
for _ in 0..num_txs { for _ in 0..num_txs {
let random_keypair = Keypair::new(); let random_keypair = Keypair::new();
let bal = client let bal = client
.poll_get_balance_with_commitment(&funding_keypair.pubkey(), CommitmentConfig::recent()) .poll_get_balance_with_commitment(
&funding_keypair.pubkey(),
CommitmentConfig::processed(),
)
.expect("balance in source"); .expect("balance in source");
assert!(bal > 0); assert!(bal > 0);
let (blockhash, _fee_calculator, _last_valid_slot) = client let (blockhash, _fee_calculator, _last_valid_slot) = client
.get_recent_blockhash_with_commitment(CommitmentConfig::recent()) .get_recent_blockhash_with_commitment(CommitmentConfig::processed())
.unwrap(); .unwrap();
let transfer_amount = thread_rng().gen_range(1, max_tokens_per_transfer); let transfer_amount = thread_rng().gen_range(1, max_tokens_per_transfer);
@ -195,7 +201,7 @@ pub fn kill_entry_and_spend_and_verify_rest(
for ingress_node in &cluster_nodes { for ingress_node in &cluster_nodes {
client client
.poll_get_balance_with_commitment(&ingress_node.id, CommitmentConfig::recent()) .poll_get_balance_with_commitment(&ingress_node.id, CommitmentConfig::processed())
.unwrap_or_else(|err| panic!("Node {} has no balance: {}", ingress_node.id, err)); .unwrap_or_else(|err| panic!("Node {} has no balance: {}", ingress_node.id, err));
} }
@ -219,7 +225,10 @@ pub fn kill_entry_and_spend_and_verify_rest(
let client = create_client(ingress_node.client_facing_addr(), VALIDATOR_PORT_RANGE); let client = create_client(ingress_node.client_facing_addr(), VALIDATOR_PORT_RANGE);
let balance = client let balance = client
.poll_get_balance_with_commitment(&funding_keypair.pubkey(), CommitmentConfig::recent()) .poll_get_balance_with_commitment(
&funding_keypair.pubkey(),
CommitmentConfig::processed(),
)
.expect("balance in source"); .expect("balance in source");
assert_ne!(balance, 0); assert_ne!(balance, 0);
@ -233,7 +242,7 @@ pub fn kill_entry_and_spend_and_verify_rest(
let random_keypair = Keypair::new(); let random_keypair = Keypair::new();
let (blockhash, _fee_calculator, _last_valid_slot) = client let (blockhash, _fee_calculator, _last_valid_slot) = client
.get_recent_blockhash_with_commitment(CommitmentConfig::recent()) .get_recent_blockhash_with_commitment(CommitmentConfig::processed())
.unwrap(); .unwrap();
let mut transaction = system_transaction::transfer( let mut transaction = system_transaction::transfer(
&funding_keypair, &funding_keypair,
@ -311,7 +320,7 @@ pub fn check_no_new_roots(
.unwrap_or_else(|_| panic!("get_slot for {} failed", ingress_node.id)); .unwrap_or_else(|_| panic!("get_slot for {} failed", ingress_node.id));
roots[i] = initial_root; roots[i] = initial_root;
client client
.get_slot_with_commitment(CommitmentConfig::recent()) .get_slot_with_commitment(CommitmentConfig::processed())
.unwrap_or_else(|_| panic!("get_slot for {} failed", ingress_node.id)) .unwrap_or_else(|_| panic!("get_slot for {} failed", ingress_node.id))
}) })
.max() .max()
@ -325,7 +334,7 @@ pub fn check_no_new_roots(
for contact_info in contact_infos { for contact_info in contact_infos {
let client = create_client(contact_info.client_facing_addr(), VALIDATOR_PORT_RANGE); let client = create_client(contact_info.client_facing_addr(), VALIDATOR_PORT_RANGE);
current_slot = client current_slot = client
.get_slot_with_commitment(CommitmentConfig::recent()) .get_slot_with_commitment(CommitmentConfig::processed())
.unwrap_or_else(|_| panic!("get_slot for {} failed", contact_infos[0].id)); .unwrap_or_else(|_| panic!("get_slot for {} failed", contact_infos[0].id));
if current_slot > end_slot { if current_slot > end_slot {
reached_end_slot = true; reached_end_slot = true;

View File

@ -435,7 +435,7 @@ impl LocalCluster {
) -> u64 { ) -> u64 {
trace!("getting leader blockhash"); trace!("getting leader blockhash");
let (blockhash, _fee_calculator, _last_valid_slot) = client let (blockhash, _fee_calculator, _last_valid_slot) = client
.get_recent_blockhash_with_commitment(CommitmentConfig::recent()) .get_recent_blockhash_with_commitment(CommitmentConfig::processed())
.unwrap(); .unwrap();
let mut tx = let mut tx =
system_transaction::transfer(&source_keypair, dest_pubkey, lamports, blockhash); system_transaction::transfer(&source_keypair, dest_pubkey, lamports, blockhash);
@ -452,7 +452,7 @@ impl LocalCluster {
.wait_for_balance_with_commitment( .wait_for_balance_with_commitment(
dest_pubkey, dest_pubkey,
Some(lamports), Some(lamports),
CommitmentConfig::recent(), CommitmentConfig::processed(),
) )
.expect("get balance") .expect("get balance")
} }
@ -474,7 +474,7 @@ impl LocalCluster {
// Create the vote account if necessary // Create the vote account if necessary
if client if client
.poll_get_balance_with_commitment(&vote_account_pubkey, CommitmentConfig::recent()) .poll_get_balance_with_commitment(&vote_account_pubkey, CommitmentConfig::processed())
.unwrap_or(0) .unwrap_or(0)
== 0 == 0
{ {
@ -496,7 +496,7 @@ impl LocalCluster {
&[from_account.as_ref(), vote_account], &[from_account.as_ref(), vote_account],
message, message,
client client
.get_recent_blockhash_with_commitment(CommitmentConfig::recent()) .get_recent_blockhash_with_commitment(CommitmentConfig::processed())
.unwrap() .unwrap()
.0, .0,
); );
@ -507,7 +507,7 @@ impl LocalCluster {
.wait_for_balance_with_commitment( .wait_for_balance_with_commitment(
&vote_account_pubkey, &vote_account_pubkey,
Some(amount), Some(amount),
CommitmentConfig::recent(), CommitmentConfig::processed(),
) )
.expect("get balance"); .expect("get balance");
@ -524,7 +524,7 @@ impl LocalCluster {
&[from_account.as_ref(), &stake_account_keypair], &[from_account.as_ref(), &stake_account_keypair],
message, message,
client client
.get_recent_blockhash_with_commitment(CommitmentConfig::recent()) .get_recent_blockhash_with_commitment(CommitmentConfig::processed())
.unwrap() .unwrap()
.0, .0,
); );
@ -541,7 +541,7 @@ impl LocalCluster {
.wait_for_balance_with_commitment( .wait_for_balance_with_commitment(
&stake_account_pubkey, &stake_account_pubkey,
Some(amount), Some(amount),
CommitmentConfig::recent(), CommitmentConfig::processed(),
) )
.expect("get balance"); .expect("get balance");
} else { } else {
@ -552,8 +552,9 @@ impl LocalCluster {
} }
info!("Checking for vote account registration of {}", node_pubkey); info!("Checking for vote account registration of {}", node_pubkey);
match ( match (
client.get_account_with_commitment(&stake_account_pubkey, CommitmentConfig::recent()), client
client.get_account_with_commitment(&vote_account_pubkey, CommitmentConfig::recent()), .get_account_with_commitment(&stake_account_pubkey, CommitmentConfig::processed()),
client.get_account_with_commitment(&vote_account_pubkey, CommitmentConfig::processed()),
) { ) {
(Ok(Some(stake_account)), Ok(Some(vote_account))) => { (Ok(Some(stake_account)), Ok(Some(vote_account))) => {
match ( match (

View File

@ -168,7 +168,7 @@ fn test_local_cluster_signature_subscribe() {
VALIDATOR_PORT_RANGE, VALIDATOR_PORT_RANGE,
); );
let (blockhash, _fee_calculator, _last_valid_slot) = tx_client let (blockhash, _fee_calculator, _last_valid_slot) = tx_client
.get_recent_blockhash_with_commitment(CommitmentConfig::recent()) .get_recent_blockhash_with_commitment(CommitmentConfig::processed())
.unwrap(); .unwrap();
let mut transaction = system_transaction::transfer( let mut transaction = system_transaction::transfer(
@ -182,7 +182,7 @@ fn test_local_cluster_signature_subscribe() {
&format!("ws://{}", &non_bootstrap_info.rpc_pubsub.to_string()), &format!("ws://{}", &non_bootstrap_info.rpc_pubsub.to_string()),
&transaction.signatures[0], &transaction.signatures[0],
Some(RpcSignatureSubscribeConfig { Some(RpcSignatureSubscribeConfig {
commitment: Some(CommitmentConfig::recent()), commitment: Some(CommitmentConfig::processed()),
enable_received_notification: Some(true), enable_received_notification: Some(true),
}), }),
) )
@ -791,7 +791,7 @@ fn test_mainnet_beta_cluster_type() {
( (
program_id, program_id,
client client
.get_account_with_commitment(program_id, CommitmentConfig::recent()) .get_account_with_commitment(program_id, CommitmentConfig::processed())
.unwrap() .unwrap()
), ),
(_program_id, Some(_)) (_program_id, Some(_))
@ -809,7 +809,7 @@ fn test_mainnet_beta_cluster_type() {
( (
program_id, program_id,
client client
.get_account_with_commitment(program_id, CommitmentConfig::recent()) .get_account_with_commitment(program_id, CommitmentConfig::processed())
.unwrap() .unwrap()
), ),
(program_id, None) (program_id, None)
@ -826,7 +826,7 @@ fn generate_frozen_account_panic(mut cluster: LocalCluster, frozen_account: Arc<
trace!( trace!(
"validator slot: {}", "validator slot: {}",
client client
.get_slot_with_commitment(CommitmentConfig::recent()) .get_slot_with_commitment(CommitmentConfig::processed())
.expect("get slot") .expect("get slot")
); );
@ -838,7 +838,7 @@ fn generate_frozen_account_panic(mut cluster: LocalCluster, frozen_account: Arc<
while !solana_runtime::accounts_db::FROZEN_ACCOUNT_PANIC.load(Ordering::Relaxed) { while !solana_runtime::accounts_db::FROZEN_ACCOUNT_PANIC.load(Ordering::Relaxed) {
// Transfer from frozen account // Transfer from frozen account
let (blockhash, _fee_calculator, _last_valid_slot) = client let (blockhash, _fee_calculator, _last_valid_slot) = client
.get_recent_blockhash_with_commitment(CommitmentConfig::recent()) .get_recent_blockhash_with_commitment(CommitmentConfig::processed())
.unwrap(); .unwrap();
client client
.async_transfer( .async_transfer(
@ -1222,7 +1222,7 @@ fn test_snapshots_blockstore_floor() {
let target_slot = slot_floor + 40; let target_slot = slot_floor + 40;
while current_slot <= target_slot { while current_slot <= target_slot {
trace!("current_slot: {}", current_slot); trace!("current_slot: {}", current_slot);
if let Ok(slot) = validator_client.get_slot_with_commitment(CommitmentConfig::recent()) { if let Ok(slot) = validator_client.get_slot_with_commitment(CommitmentConfig::processed()) {
current_slot = slot; current_slot = slot;
} else { } else {
continue; continue;
@ -1402,7 +1402,7 @@ fn test_no_voting() {
.unwrap(); .unwrap();
loop { loop {
let last_slot = client let last_slot = client
.get_slot_with_commitment(CommitmentConfig::recent()) .get_slot_with_commitment(CommitmentConfig::processed())
.expect("Couldn't get slot"); .expect("Couldn't get slot");
if last_slot > 4 * VOTE_THRESHOLD_DEPTH as u64 { if last_slot > 4 * VOTE_THRESHOLD_DEPTH as u64 {
break; break;
@ -1460,7 +1460,7 @@ fn test_optimistic_confirmation_violation_detection() {
let mut prev_voted_slot = 0; let mut prev_voted_slot = 0;
loop { loop {
let last_voted_slot = client let last_voted_slot = client
.get_slot_with_commitment(CommitmentConfig::recent()) .get_slot_with_commitment(CommitmentConfig::processed())
.unwrap(); .unwrap();
if last_voted_slot > 50 { if last_voted_slot > 50 {
if prev_voted_slot == 0 { if prev_voted_slot == 0 {
@ -1498,7 +1498,7 @@ fn test_optimistic_confirmation_violation_detection() {
let client = cluster.get_validator_client(&entry_point_id).unwrap(); let client = cluster.get_validator_client(&entry_point_id).unwrap();
loop { loop {
let last_root = client let last_root = client
.get_slot_with_commitment(CommitmentConfig::max()) .get_slot_with_commitment(CommitmentConfig::finalized())
.unwrap(); .unwrap();
if last_root > prev_voted_slot { if last_root > prev_voted_slot {
break; break;
@ -1561,7 +1561,7 @@ fn test_validator_saves_tower() {
// Wait for some votes to be generated // Wait for some votes to be generated
let mut last_replayed_root; let mut last_replayed_root;
loop { loop {
if let Ok(slot) = validator_client.get_slot_with_commitment(CommitmentConfig::recent()) { if let Ok(slot) = validator_client.get_slot_with_commitment(CommitmentConfig::processed()) {
trace!("current slot: {}", slot); trace!("current slot: {}", slot);
if slot > 2 { if slot > 2 {
// this will be the root next time a validator starts // this will be the root next time a validator starts
@ -1584,6 +1584,9 @@ fn test_validator_saves_tower() {
// Wait for the first root // Wait for the first root
loop { loop {
#[allow(deprecated)]
// This test depends on knowing the immediate root, without any delay from the commitment
// service, so the deprecated CommitmentConfig::root() is retained
if let Ok(root) = validator_client.get_slot_with_commitment(CommitmentConfig::root()) { if let Ok(root) = validator_client.get_slot_with_commitment(CommitmentConfig::root()) {
trace!("current root: {}", root); trace!("current root: {}", root);
if root > last_replayed_root + 1 { if root > last_replayed_root + 1 {
@ -1596,7 +1599,7 @@ fn test_validator_saves_tower() {
// Stop validator, and check saved tower // Stop validator, and check saved tower
let recent_slot = validator_client let recent_slot = validator_client
.get_slot_with_commitment(CommitmentConfig::recent()) .get_slot_with_commitment(CommitmentConfig::processed())
.unwrap(); .unwrap();
let validator_info = cluster.exit_node(&validator_id); let validator_info = cluster.exit_node(&validator_id);
let tower2 = Tower::restore(&ledger_path, &validator_id).unwrap(); let tower2 = Tower::restore(&ledger_path, &validator_id).unwrap();
@ -1613,6 +1616,9 @@ fn test_validator_saves_tower() {
// Wait for a new root, demonstrating the validator was able to make progress from the older `tower1` // Wait for a new root, demonstrating the validator was able to make progress from the older `tower1`
loop { loop {
#[allow(deprecated)]
// This test depends on knowing the immediate root, without any delay from the commitment
// service, so the deprecated CommitmentConfig::root() is retained
if let Ok(root) = validator_client.get_slot_with_commitment(CommitmentConfig::root()) { if let Ok(root) = validator_client.get_slot_with_commitment(CommitmentConfig::root()) {
trace!( trace!(
"current root: {}, last_replayed_root: {}", "current root: {}, last_replayed_root: {}",
@ -1642,10 +1648,10 @@ fn test_validator_saves_tower() {
// Wait for a couple more slots to pass so another vote occurs // Wait for a couple more slots to pass so another vote occurs
let current_slot = validator_client let current_slot = validator_client
.get_slot_with_commitment(CommitmentConfig::recent()) .get_slot_with_commitment(CommitmentConfig::processed())
.unwrap(); .unwrap();
loop { loop {
if let Ok(slot) = validator_client.get_slot_with_commitment(CommitmentConfig::recent()) { if let Ok(slot) = validator_client.get_slot_with_commitment(CommitmentConfig::processed()) {
trace!("current_slot: {}, slot: {}", current_slot, slot); trace!("current_slot: {}, slot: {}", current_slot, slot);
if slot > current_slot + 1 { if slot > current_slot + 1 {
break; break;
@ -2157,13 +2163,13 @@ fn test_optimistic_confirmation_violation_without_tower() {
#[test] #[test]
#[serial] #[serial]
fn test_run_test_load_program_accounts_root() { fn test_run_test_load_program_accounts_root() {
run_test_load_program_accounts(CommitmentConfig::root()); run_test_load_program_accounts(CommitmentConfig::finalized());
} }
#[test] #[test]
#[serial] #[serial]
fn test_run_test_load_program_accounts_partition_root() { fn test_run_test_load_program_accounts_partition_root() {
run_test_load_program_accounts_partition(CommitmentConfig::root()); run_test_load_program_accounts_partition(CommitmentConfig::finalized());
} }
fn run_test_load_program_accounts_partition(scan_commitment: CommitmentConfig) { fn run_test_load_program_accounts_partition(scan_commitment: CommitmentConfig) {
@ -2245,7 +2251,7 @@ fn setup_transfer_scan_threads(
return; return;
} }
let (blockhash, _fee_calculator, _last_valid_slot) = client let (blockhash, _fee_calculator, _last_valid_slot) = client
.get_recent_blockhash_with_commitment(CommitmentConfig::recent()) .get_recent_blockhash_with_commitment(CommitmentConfig::processed())
.unwrap(); .unwrap();
for i in 0..starting_keypairs_.len() { for i in 0..starting_keypairs_.len() {
client client
@ -2388,7 +2394,7 @@ fn wait_for_next_snapshot(
.get_validator_client(&cluster.entry_point_info.id) .get_validator_client(&cluster.entry_point_info.id)
.unwrap(); .unwrap();
let last_slot = client let last_slot = client
.get_slot_with_commitment(CommitmentConfig::recent()) .get_slot_with_commitment(CommitmentConfig::processed())
.expect("Couldn't get slot"); .expect("Couldn't get slot");
// Wait for a snapshot for a bank >= last_slot to be made so we know that the snapshot // Wait for a snapshot for a bank >= last_slot to be made so we know that the snapshot

View File

@ -109,13 +109,16 @@ impl BlockCommitmentCache {
self.highest_confirmed_slot() self.highest_confirmed_slot()
} }
#[allow(deprecated)]
pub fn slot_with_commitment(&self, commitment_level: CommitmentLevel) -> Slot { pub fn slot_with_commitment(&self, commitment_level: CommitmentLevel) -> Slot {
match commitment_level { match commitment_level {
CommitmentLevel::Recent => self.slot(), CommitmentLevel::Recent | CommitmentLevel::Processed => self.slot(),
CommitmentLevel::Root => self.root(), CommitmentLevel::Root => self.root(),
CommitmentLevel::Single => self.highest_confirmed_slot(), CommitmentLevel::Single => self.highest_confirmed_slot(),
CommitmentLevel::SingleGossip => self.highest_gossip_confirmed_slot(), CommitmentLevel::SingleGossip | CommitmentLevel::Confirmed => {
CommitmentLevel::Max => self.highest_confirmed_root(), self.highest_gossip_confirmed_slot()
}
CommitmentLevel::Max | CommitmentLevel::Finalized => self.highest_confirmed_root(),
} }
} }

View File

@ -1,3 +1,6 @@
#![allow(deprecated)]
#![cfg(feature = "full")]
use std::str::FromStr; use std::str::FromStr;
use thiserror::Error; use thiserror::Error;
@ -8,36 +11,74 @@ pub struct CommitmentConfig {
} }
impl CommitmentConfig { impl CommitmentConfig {
#[deprecated(
since = "1.5.5",
note = "Please use CommitmentConfig::processed() instead"
)]
pub fn recent() -> Self { pub fn recent() -> Self {
Self { Self {
commitment: CommitmentLevel::Recent, commitment: CommitmentLevel::Recent,
} }
} }
#[deprecated(
since = "1.5.5",
note = "Please use CommitmentConfig::finalized() instead"
)]
pub fn max() -> Self { pub fn max() -> Self {
Self { Self {
commitment: CommitmentLevel::Max, commitment: CommitmentLevel::Max,
} }
} }
#[deprecated(
since = "1.5.5",
note = "Please use CommitmentConfig::finalized() instead"
)]
pub fn root() -> Self { pub fn root() -> Self {
Self { Self {
commitment: CommitmentLevel::Root, commitment: CommitmentLevel::Root,
} }
} }
#[deprecated(
since = "1.5.5",
note = "Please use CommitmentConfig::confirmed() instead"
)]
pub fn single() -> Self { pub fn single() -> Self {
Self { Self {
commitment: CommitmentLevel::Single, commitment: CommitmentLevel::Single,
} }
} }
#[deprecated(
since = "1.5.5",
note = "Please use CommitmentConfig::confirmed() instead"
)]
pub fn single_gossip() -> Self { pub fn single_gossip() -> Self {
Self { Self {
commitment: CommitmentLevel::SingleGossip, commitment: CommitmentLevel::SingleGossip,
} }
} }
pub fn finalized() -> Self {
Self {
commitment: CommitmentLevel::Finalized,
}
}
pub fn confirmed() -> Self {
Self {
commitment: CommitmentLevel::Confirmed,
}
}
pub fn processed() -> Self {
Self {
commitment: CommitmentLevel::Processed,
}
}
pub fn ok(self) -> Option<Self> { pub fn ok(self) -> Option<Self> {
if self == Self::default() { if self == Self::default() {
None None
@ -45,6 +86,36 @@ impl CommitmentConfig {
Some(self) Some(self)
} }
} }
pub fn is_finalized(&self) -> bool {
matches!(
&self.commitment,
CommitmentLevel::Finalized | CommitmentLevel::Max | CommitmentLevel::Root
)
}
pub fn is_confirmed(&self) -> bool {
matches!(
&self.commitment,
CommitmentLevel::Confirmed | CommitmentLevel::SingleGossip | CommitmentLevel::Single
)
}
pub fn is_processed(&self) -> bool {
matches!(
&self.commitment,
CommitmentLevel::Processed | CommitmentLevel::Recent
)
}
pub fn use_deprecated_commitment(commitment: CommitmentConfig) -> Self {
match commitment.commitment {
CommitmentLevel::Finalized => CommitmentConfig::max(),
CommitmentLevel::Confirmed => CommitmentConfig::single_gossip(),
CommitmentLevel::Processed => CommitmentConfig::recent(),
_ => commitment,
}
}
} }
impl FromStr for CommitmentConfig { impl FromStr for CommitmentConfig {
@ -62,32 +133,67 @@ impl FromStr for CommitmentConfig {
/// finalized. When querying the ledger state, use lower levels of commitment to report progress and higher /// finalized. When querying the ledger state, use lower levels of commitment to report progress and higher
/// levels to ensure state changes will not be rolled back. /// levels to ensure state changes will not be rolled back.
pub enum CommitmentLevel { pub enum CommitmentLevel {
/// The highest slot having reached max vote lockout, as recognized by a supermajority of the cluster. /// (DEPRECATED) The highest slot having reached max vote lockout, as recognized by a supermajority of the cluster.
#[deprecated(
since = "1.5.5",
note = "Please use CommitmentLevel::Finalized instead"
)]
Max, Max,
/// The highest slot of the heaviest fork. Ledger state at this slot is not derived from a finalized /// (DEPRECATED) The highest slot of the heaviest fork. Ledger state at this slot is not derived from a finalized
/// block, but if multiple forks are present, is from the fork the validator believes is most likely /// block, but if multiple forks are present, is from the fork the validator believes is most likely
/// to finalize. /// to finalize.
#[deprecated(
since = "1.5.5",
note = "Please use CommitmentLevel::Processed instead"
)]
Recent, Recent,
/// The highest slot having reached max vote lockout. /// (DEPRECATED) The highest slot having reached max vote lockout.
#[deprecated(
since = "1.5.5",
note = "Please use CommitmentLevel::Finalized instead"
)]
Root, Root,
/// (DEPRECATED) The highest slot having reached 1 confirmation by supermajority of the cluster. /// (DEPRECATED) The highest slot having reached 1 confirmation by supermajority of the cluster.
#[deprecated(
since = "1.5.5",
note = "Please use CommitmentLevel::Confirmed instead"
)]
Single, Single,
/// The highest slot that has been voted on by supermajority of the cluster /// (DEPRECATED) The highest slot that has been voted on by supermajority of the cluster
/// This differs from `single` in that: /// This differs from `single` in that:
/// 1) It incorporates votes from gossip and replay. /// 1) It incorporates votes from gossip and replay.
/// 2) It does not count votes on descendants of a block, only direct votes on that block. /// 2) It does not count votes on descendants of a block, only direct votes on that block.
/// 3) This confirmation level also upholds "optimistic confirmation" guarantees in /// 3) This confirmation level also upholds "optimistic confirmation" guarantees in
/// release 1.3 and onwards. /// release 1.3 and onwards.
#[deprecated(
since = "1.5.5",
note = "Please use CommitmentLevel::Confirmed instead"
)]
SingleGossip, SingleGossip,
/// The highest slot of the heaviest fork processed by the node. Ledger state at this slot is
/// not derived from a confirmed or finalized block, but if multiple forks are present, is from
/// the fork the validator believes is most likely to finalize.
Processed,
/// The highest slot that has been voted on by supermajority of the cluster, ie. is confirmed.
/// Confirmation incorporates votes from gossip and replay. It does not count votes on
/// descendants of a block, only direct votes on that block, and upholds "optimistic
/// confirmation" guarantees in release 1.3 and onwards.
Confirmed,
/// The highest slot having reached max vote lockout, as recognized by a supermajority of the
/// cluster.
Finalized,
} }
impl Default for CommitmentLevel { impl Default for CommitmentLevel {
fn default() -> Self { fn default() -> Self {
Self::Max Self::Finalized
} }
} }
@ -101,6 +207,9 @@ impl FromStr for CommitmentLevel {
"root" => Ok(CommitmentLevel::Root), "root" => Ok(CommitmentLevel::Root),
"single" => Ok(CommitmentLevel::Single), "single" => Ok(CommitmentLevel::Single),
"singleGossip" => Ok(CommitmentLevel::SingleGossip), "singleGossip" => Ok(CommitmentLevel::SingleGossip),
"processed" => Ok(CommitmentLevel::Processed),
"confirmed" => Ok(CommitmentLevel::Confirmed),
"finalized" => Ok(CommitmentLevel::Finalized),
_ => Err(ParseCommitmentLevelError::Invalid), _ => Err(ParseCommitmentLevelError::Invalid),
} }
} }
@ -114,6 +223,9 @@ impl std::fmt::Display for CommitmentLevel {
CommitmentLevel::Root => "root", CommitmentLevel::Root => "root",
CommitmentLevel::Single => "single", CommitmentLevel::Single => "single",
CommitmentLevel::SingleGossip => "singleGossip", CommitmentLevel::SingleGossip => "singleGossip",
CommitmentLevel::Processed => "processed",
CommitmentLevel::Confirmed => "confirmed",
CommitmentLevel::Finalized => "finalized",
}; };
write!(f, "{}", s) write!(f, "{}", s)
} }

View File

@ -418,7 +418,7 @@ mod test {
.unwrap(); .unwrap();
rpc_client rpc_client
.poll_for_signature_with_commitment(&stake1_signature, CommitmentConfig::recent()) .poll_for_signature_with_commitment(&stake1_signature, CommitmentConfig::processed())
.unwrap(); .unwrap();
// A balance increase by system transfer is ignored // A balance increase by system transfer is ignored
@ -473,7 +473,7 @@ mod test {
rpc_client rpc_client
.poll_for_signature_with_commitment( .poll_for_signature_with_commitment(
&stake3_initialize_signature, &stake3_initialize_signature,
CommitmentConfig::recent(), CommitmentConfig::processed(),
) )
.unwrap(); .unwrap();
@ -504,7 +504,7 @@ mod test {
rpc_client rpc_client
.poll_for_signature_with_commitment( .poll_for_signature_with_commitment(
&stake3_withdraw_signature, &stake3_withdraw_signature,
CommitmentConfig::recent(), CommitmentConfig::processed(),
) )
.unwrap(); .unwrap();
@ -529,7 +529,7 @@ mod test {
rpc_client rpc_client
.poll_for_signature_with_commitment( .poll_for_signature_with_commitment(
&stake4_initialize_signature, &stake4_initialize_signature,
CommitmentConfig::recent(), CommitmentConfig::processed(),
) )
.unwrap(); .unwrap();
@ -560,7 +560,7 @@ mod test {
rpc_client rpc_client
.poll_for_signature_with_commitment( .poll_for_signature_with_commitment(
&stake45_split_signature, &stake45_split_signature,
CommitmentConfig::recent(), CommitmentConfig::processed(),
) )
.unwrap(); .unwrap();
@ -577,12 +577,15 @@ mod test {
)) ))
.unwrap(); .unwrap();
rpc_client rpc_client
.poll_for_signature_with_commitment(&fund_system1_signature, CommitmentConfig::recent()) .poll_for_signature_with_commitment(
&fund_system1_signature,
CommitmentConfig::processed(),
)
.unwrap(); .unwrap();
accounts_info.enroll_system_account( accounts_info.enroll_system_account(
&system1_keypair.pubkey(), &system1_keypair.pubkey(),
rpc_client rpc_client
.get_slot_with_commitment(CommitmentConfig::recent()) .get_slot_with_commitment(CommitmentConfig::processed())
.unwrap(), .unwrap(),
2 * one_sol, 2 * one_sol,
); );
@ -616,12 +619,15 @@ mod test {
)) ))
.unwrap(); .unwrap();
rpc_client rpc_client
.poll_for_signature_with_commitment(&fund_system2_signature, CommitmentConfig::recent()) .poll_for_signature_with_commitment(
&fund_system2_signature,
CommitmentConfig::processed(),
)
.unwrap(); .unwrap();
accounts_info.enroll_system_account( accounts_info.enroll_system_account(
&system2_keypair.pubkey(), &system2_keypair.pubkey(),
rpc_client rpc_client
.get_slot_with_commitment(CommitmentConfig::recent()) .get_slot_with_commitment(CommitmentConfig::processed())
.unwrap(), .unwrap(),
2 * one_sol, 2 * one_sol,
); );
@ -644,7 +650,7 @@ mod test {
// Process all the transactions // Process all the transactions
let current_slot = rpc_client let current_slot = rpc_client
.get_slot_with_commitment(CommitmentConfig::recent()) .get_slot_with_commitment(CommitmentConfig::processed())
.unwrap(); .unwrap();
process_slots(&rpc_client, &mut accounts_info, current_slot + 1); process_slots(&rpc_client, &mut accounts_info, current_slot + 1);

View File

@ -534,7 +534,7 @@ fn transact(
break; break;
} }
let slot = rpc_client.get_slot_with_commitment(CommitmentConfig::max())?; let slot = rpc_client.get_slot_with_commitment(CommitmentConfig::finalized())?;
info!( info!(
"Current slot={}, last_valid_slot={} (slots remaining: {}) ", "Current slot={}, last_valid_slot={} (slots remaining: {}) ",
slot, slot,

View File

@ -1046,7 +1046,7 @@ mod tests {
let test_validator = TestValidator::with_no_fees(alice.pubkey()); let test_validator = TestValidator::with_no_fees(alice.pubkey());
let url = test_validator.rpc_url(); let url = test_validator.rpc_url();
let client = RpcClient::new_with_commitment(url, CommitmentConfig::recent()); let client = RpcClient::new_with_commitment(url, CommitmentConfig::processed());
test_process_distribute_tokens_with_client(&client, alice, None); test_process_distribute_tokens_with_client(&client, alice, None);
} }
@ -1056,7 +1056,7 @@ mod tests {
let test_validator = TestValidator::with_no_fees(alice.pubkey()); let test_validator = TestValidator::with_no_fees(alice.pubkey());
let url = test_validator.rpc_url(); let url = test_validator.rpc_url();
let client = RpcClient::new_with_commitment(url, CommitmentConfig::recent()); let client = RpcClient::new_with_commitment(url, CommitmentConfig::processed());
test_process_distribute_tokens_with_client(&client, alice, Some(sol_to_lamports(1.5))); test_process_distribute_tokens_with_client(&client, alice, Some(sol_to_lamports(1.5)));
} }
@ -1066,7 +1066,7 @@ mod tests {
let test_validator = TestValidator::with_no_fees(alice.pubkey()); let test_validator = TestValidator::with_no_fees(alice.pubkey());
let url = test_validator.rpc_url(); let url = test_validator.rpc_url();
let client = RpcClient::new_with_commitment(url, CommitmentConfig::recent()); let client = RpcClient::new_with_commitment(url, CommitmentConfig::processed());
test_process_distribute_stake_with_client(&client, alice); test_process_distribute_stake_with_client(&client, alice);
} }
@ -1381,7 +1381,7 @@ mod tests {
let test_validator = TestValidator::with_custom_fees(alice.pubkey(), fees); let test_validator = TestValidator::with_custom_fees(alice.pubkey(), fees);
let url = test_validator.rpc_url(); let url = test_validator.rpc_url();
let client = RpcClient::new_with_commitment(url, CommitmentConfig::recent()); let client = RpcClient::new_with_commitment(url, CommitmentConfig::processed());
let sender_keypair_file = tmp_file_path("keypair_file", &alice.pubkey()); let sender_keypair_file = tmp_file_path("keypair_file", &alice.pubkey());
write_keypair_file(&alice, &sender_keypair_file).unwrap(); write_keypair_file(&alice, &sender_keypair_file).unwrap();
@ -1464,7 +1464,7 @@ mod tests {
let test_validator = TestValidator::with_custom_fees(alice.pubkey(), fees); let test_validator = TestValidator::with_custom_fees(alice.pubkey(), fees);
let url = test_validator.rpc_url(); let url = test_validator.rpc_url();
let client = RpcClient::new_with_commitment(url, CommitmentConfig::recent()); let client = RpcClient::new_with_commitment(url, CommitmentConfig::processed());
let sender_keypair_file = tmp_file_path("keypair_file", &alice.pubkey()); let sender_keypair_file = tmp_file_path("keypair_file", &alice.pubkey());
write_keypair_file(&alice, &sender_keypair_file).unwrap(); write_keypair_file(&alice, &sender_keypair_file).unwrap();
@ -1573,7 +1573,7 @@ mod tests {
let alice = Keypair::new(); let alice = Keypair::new();
let test_validator = TestValidator::with_custom_fees(alice.pubkey(), fees); let test_validator = TestValidator::with_custom_fees(alice.pubkey(), fees);
let url = test_validator.rpc_url(); let url = test_validator.rpc_url();
let client = RpcClient::new_with_commitment(url, CommitmentConfig::recent()); let client = RpcClient::new_with_commitment(url, CommitmentConfig::processed());
let sender_keypair_file = tmp_file_path("keypair_file", &alice.pubkey()); let sender_keypair_file = tmp_file_path("keypair_file", &alice.pubkey());
write_keypair_file(&alice, &sender_keypair_file).unwrap(); write_keypair_file(&alice, &sender_keypair_file).unwrap();
@ -1680,7 +1680,7 @@ mod tests {
let test_validator = TestValidator::with_custom_fees(alice.pubkey(), fees); let test_validator = TestValidator::with_custom_fees(alice.pubkey(), fees);
let url = test_validator.rpc_url(); let url = test_validator.rpc_url();
let client = RpcClient::new_with_commitment(url, CommitmentConfig::recent()); let client = RpcClient::new_with_commitment(url, CommitmentConfig::processed());
let sender_keypair_file = tmp_file_path("keypair_file", &alice.pubkey()); let sender_keypair_file = tmp_file_path("keypair_file", &alice.pubkey());
write_keypair_file(&alice, &sender_keypair_file).unwrap(); write_keypair_file(&alice, &sender_keypair_file).unwrap();
@ -1994,7 +1994,7 @@ mod tests {
let sender_keypair = Keypair::new(); let sender_keypair = Keypair::new();
let test_validator = TestValidator::with_no_fees(sender_keypair.pubkey()); let test_validator = TestValidator::with_no_fees(sender_keypair.pubkey());
let url = test_validator.rpc_url(); let url = test_validator.rpc_url();
let client = RpcClient::new_with_commitment(url, CommitmentConfig::recent()); let client = RpcClient::new_with_commitment(url, CommitmentConfig::processed());
let fee_payer = Keypair::new(); let fee_payer = Keypair::new();
let transaction = transfer( let transaction = transfer(

View File

@ -20,7 +20,7 @@ use solana_account_decoder::parse_token::UiTokenAmount;
pub use solana_runtime::bank::RewardType; pub use solana_runtime::bank::RewardType;
use solana_sdk::{ use solana_sdk::{
clock::{Slot, UnixTimestamp}, clock::{Slot, UnixTimestamp},
commitment_config::{CommitmentConfig, CommitmentLevel}, commitment_config::CommitmentConfig,
deserialize_utils::default_on_eof, deserialize_utils::default_on_eof,
instruction::CompiledInstruction, instruction::CompiledInstruction,
message::{Message, MessageHeader}, message::{Message, MessageHeader},
@ -281,22 +281,18 @@ pub struct TransactionStatus {
impl TransactionStatus { impl TransactionStatus {
pub fn satisfies_commitment(&self, commitment_config: CommitmentConfig) -> bool { pub fn satisfies_commitment(&self, commitment_config: CommitmentConfig) -> bool {
match commitment_config.commitment { if commitment_config.is_finalized() {
CommitmentLevel::Max | CommitmentLevel::Root => self.confirmations.is_none(), self.confirmations.is_none()
CommitmentLevel::SingleGossip => { } else if commitment_config.is_confirmed() {
if let Some(status) = &self.confirmation_status { if let Some(status) = &self.confirmation_status {
*status != TransactionConfirmationStatus::Processed *status != TransactionConfirmationStatus::Processed
} else { } else {
// These fallback cases handle TransactionStatus RPC responses from older software // These fallback cases handle TransactionStatus RPC responses from older software
self.confirmations.is_some() && self.confirmations.unwrap() > 1 self.confirmations.is_some() && self.confirmations.unwrap() > 1
|| self.confirmations.is_none() || self.confirmations.is_none()
}
} }
CommitmentLevel::Single => match self.confirmations { } else {
Some(confirmations) => confirmations >= 1, true
None => true,
},
CommitmentLevel::Recent => true,
} }
} }
@ -620,11 +616,9 @@ mod test {
confirmation_status: Some(TransactionConfirmationStatus::Finalized), confirmation_status: Some(TransactionConfirmationStatus::Finalized),
}; };
assert!(status.satisfies_commitment(CommitmentConfig::default())); assert!(status.satisfies_commitment(CommitmentConfig::finalized()));
assert!(status.satisfies_commitment(CommitmentConfig::root())); assert!(status.satisfies_commitment(CommitmentConfig::confirmed()));
assert!(status.satisfies_commitment(CommitmentConfig::single())); assert!(status.satisfies_commitment(CommitmentConfig::processed()));
assert!(status.satisfies_commitment(CommitmentConfig::single_gossip()));
assert!(status.satisfies_commitment(CommitmentConfig::recent()));
let status = TransactionStatus { let status = TransactionStatus {
slot: 0, slot: 0,
@ -634,11 +628,9 @@ mod test {
confirmation_status: Some(TransactionConfirmationStatus::Confirmed), confirmation_status: Some(TransactionConfirmationStatus::Confirmed),
}; };
assert!(!status.satisfies_commitment(CommitmentConfig::default())); assert!(!status.satisfies_commitment(CommitmentConfig::finalized()));
assert!(!status.satisfies_commitment(CommitmentConfig::root())); assert!(status.satisfies_commitment(CommitmentConfig::confirmed()));
assert!(status.satisfies_commitment(CommitmentConfig::single())); assert!(status.satisfies_commitment(CommitmentConfig::processed()));
assert!(status.satisfies_commitment(CommitmentConfig::single_gossip()));
assert!(status.satisfies_commitment(CommitmentConfig::recent()));
let status = TransactionStatus { let status = TransactionStatus {
slot: 0, slot: 0,
@ -648,11 +640,9 @@ mod test {
confirmation_status: Some(TransactionConfirmationStatus::Processed), confirmation_status: Some(TransactionConfirmationStatus::Processed),
}; };
assert!(!status.satisfies_commitment(CommitmentConfig::default())); assert!(!status.satisfies_commitment(CommitmentConfig::finalized()));
assert!(!status.satisfies_commitment(CommitmentConfig::root())); assert!(!status.satisfies_commitment(CommitmentConfig::confirmed()));
assert!(status.satisfies_commitment(CommitmentConfig::single())); assert!(status.satisfies_commitment(CommitmentConfig::processed()));
assert!(!status.satisfies_commitment(CommitmentConfig::single_gossip()));
assert!(status.satisfies_commitment(CommitmentConfig::recent()));
let status = TransactionStatus { let status = TransactionStatus {
slot: 0, slot: 0,
@ -662,11 +652,9 @@ mod test {
confirmation_status: None, confirmation_status: None,
}; };
assert!(!status.satisfies_commitment(CommitmentConfig::default())); assert!(!status.satisfies_commitment(CommitmentConfig::finalized()));
assert!(!status.satisfies_commitment(CommitmentConfig::root())); assert!(!status.satisfies_commitment(CommitmentConfig::confirmed()));
assert!(!status.satisfies_commitment(CommitmentConfig::single())); assert!(status.satisfies_commitment(CommitmentConfig::processed()));
assert!(!status.satisfies_commitment(CommitmentConfig::single_gossip()));
assert!(status.satisfies_commitment(CommitmentConfig::recent()));
// Test single_gossip fallback cases // Test single_gossip fallback cases
let status = TransactionStatus { let status = TransactionStatus {
@ -676,7 +664,7 @@ mod test {
err: None, err: None,
confirmation_status: None, confirmation_status: None,
}; };
assert!(!status.satisfies_commitment(CommitmentConfig::single_gossip())); assert!(!status.satisfies_commitment(CommitmentConfig::confirmed()));
let status = TransactionStatus { let status = TransactionStatus {
slot: 0, slot: 0,
@ -685,7 +673,7 @@ mod test {
err: None, err: None,
confirmation_status: None, confirmation_status: None,
}; };
assert!(status.satisfies_commitment(CommitmentConfig::single_gossip())); assert!(status.satisfies_commitment(CommitmentConfig::confirmed()));
let status = TransactionStatus { let status = TransactionStatus {
slot: 0, slot: 0,
@ -694,6 +682,6 @@ mod test {
err: None, err: None,
confirmation_status: None, confirmation_status: None,
}; };
assert!(status.satisfies_commitment(CommitmentConfig::single_gossip())); assert!(status.satisfies_commitment(CommitmentConfig::confirmed()));
} }
} }

View File

@ -435,14 +435,16 @@ fn main() {
rpc_client: &RpcClient, rpc_client: &RpcClient,
identity: &Pubkey, identity: &Pubkey,
) -> client_error::Result<(Slot, Slot, Slot, u64, Sol, String)> { ) -> client_error::Result<(Slot, Slot, Slot, u64, Sol, String)> {
let processed_slot = rpc_client.get_slot_with_commitment(CommitmentConfig::recent())?; let processed_slot =
rpc_client.get_slot_with_commitment(CommitmentConfig::processed())?;
let confirmed_slot = let confirmed_slot =
rpc_client.get_slot_with_commitment(CommitmentConfig::single_gossip())?; rpc_client.get_slot_with_commitment(CommitmentConfig::confirmed())?;
let finalized_slot = rpc_client.get_slot_with_commitment(CommitmentConfig::max())?; let finalized_slot =
rpc_client.get_slot_with_commitment(CommitmentConfig::finalized())?;
let transaction_count = let transaction_count =
rpc_client.get_transaction_count_with_commitment(CommitmentConfig::recent())?; rpc_client.get_transaction_count_with_commitment(CommitmentConfig::processed())?;
let identity_balance = rpc_client let identity_balance = rpc_client
.get_balance_with_commitment(identity, CommitmentConfig::single_gossip())? .get_balance_with_commitment(identity, CommitmentConfig::confirmed())?
.value; .value;
let health = match rpc_client.get_health() { let health = match rpc_client.get_health() {

View File

@ -323,7 +323,7 @@ fn check_vote_account(
authorized_voter_pubkeys: &[Pubkey], authorized_voter_pubkeys: &[Pubkey],
) -> Result<(), String> { ) -> Result<(), String> {
let vote_account = rpc_client let vote_account = rpc_client
.get_account_with_commitment(vote_account_address, CommitmentConfig::single_gossip()) .get_account_with_commitment(vote_account_address, CommitmentConfig::confirmed())
.map_err(|err| format!("failed to fetch vote account: {}", err.to_string()))? .map_err(|err| format!("failed to fetch vote account: {}", err.to_string()))?
.value .value
.ok_or_else(|| format!("vote account does not exist: {}", vote_account_address))?; .ok_or_else(|| format!("vote account does not exist: {}", vote_account_address))?;
@ -336,7 +336,7 @@ fn check_vote_account(
} }
let identity_account = rpc_client let identity_account = rpc_client
.get_account_with_commitment(identity_pubkey, CommitmentConfig::single_gossip()) .get_account_with_commitment(identity_pubkey, CommitmentConfig::confirmed())
.map_err(|err| format!("failed to fetch identity account: {}", err.to_string()))? .map_err(|err| format!("failed to fetch identity account: {}", err.to_string()))?
.value .value
.ok_or_else(|| format!("identity account does not exist: {}", identity_pubkey))?; .ok_or_else(|| format!("identity account does not exist: {}", identity_pubkey))?;
@ -690,7 +690,7 @@ fn rpc_bootstrap(
Ok(()) Ok(())
} else { } else {
rpc_client rpc_client
.get_slot_with_commitment(CommitmentConfig::root()) .get_slot_with_commitment(CommitmentConfig::finalized())
.map_err(|err| format!("Failed to get RPC node slot: {}", err)) .map_err(|err| format!("Failed to get RPC node slot: {}", err))
.and_then(|slot| { .and_then(|slot| {
info!("RPC node root slot: {}", slot); info!("RPC node root slot: {}", slot);