Nonce fees 1.0 (#8664)

automerge
This commit is contained in:
Grimes
2020-03-05 09:41:45 -08:00
committed by GitHub
parent 4d9aee4794
commit d94f5c94a3
19 changed files with 664 additions and 439 deletions

View File

@ -2486,7 +2486,7 @@ mod tests {
};
use solana_sdk::{
account::Account,
nonce_state::{Meta as NonceMeta, NonceState},
nonce,
pubkey::Pubkey,
signature::{keypair_from_seed, read_keypair_file, write_keypair_file, Presigner},
system_program,
@ -3265,18 +3265,16 @@ mod tests {
// Nonced pay
let blockhash = Hash::default();
let data =
nonce::state::Versions::new_current(nonce::State::Initialized(nonce::state::Data {
authority: config.signers[0].pubkey(),
blockhash,
fee_calculator: FeeCalculator::default(),
}));
let nonce_response = json!(Response {
context: RpcResponseContext { slot: 1 },
value: json!(RpcAccount::encode(
Account::new_data(
1,
&NonceState::Initialized(
NonceMeta::new(&config.signers[0].pubkey()),
blockhash
),
&system_program::ID,
)
.unwrap()
Account::new_data(1, &data, &system_program::ID,).unwrap()
)),
});
let mut mocks = HashMap::new();
@ -3296,15 +3294,16 @@ mod tests {
let bob_keypair = Keypair::new();
let bob_pubkey = bob_keypair.pubkey();
let blockhash = Hash::default();
let data =
nonce::state::Versions::new_current(nonce::State::Initialized(nonce::state::Data {
authority: bob_pubkey,
blockhash,
fee_calculator: FeeCalculator::default(),
}));
let nonce_authority_response = json!(Response {
context: RpcResponseContext { slot: 1 },
value: json!(RpcAccount::encode(
Account::new_data(
1,
&NonceState::Initialized(NonceMeta::new(&bob_pubkey), blockhash),
&system_program::ID,
)
.unwrap()
Account::new_data(1, &data, &system_program::ID,).unwrap()
)),
});
let mut mocks = HashMap::new();

View File

@ -14,7 +14,7 @@ use solana_sdk::{
account_utils::StateMut,
hash::Hash,
message::Message,
nonce_state::{Meta, NonceState},
nonce::{self, state::Versions, State},
pubkey::Pubkey,
system_instruction::{
advance_nonce_account, authorize_nonce_account, create_address_with_seed,
@ -363,22 +363,20 @@ pub fn check_nonce_account(
if nonce_account.owner != system_program::ID {
return Err(CliError::InvalidNonce(CliNonceError::InvalidAccountOwner).into());
}
let nonce_state: NonceState = nonce_account
.state()
let nonce_state = StateMut::<Versions>::state(nonce_account)
.map(|v| v.convert_to_current())
.map_err(|_| Box::new(CliError::InvalidNonce(CliNonceError::InvalidAccountData)))?;
match nonce_state {
NonceState::Initialized(meta, hash) => {
if &hash != nonce_hash {
State::Initialized(ref data) => {
if &data.blockhash != nonce_hash {
Err(CliError::InvalidNonce(CliNonceError::InvalidHash).into())
} else if nonce_authority != &meta.nonce_authority {
} else if nonce_authority != &data.authority {
Err(CliError::InvalidNonce(CliNonceError::InvalidAuthority).into())
} else {
Ok(())
}
}
NonceState::Uninitialized => {
Err(CliError::InvalidNonce(CliNonceError::InvalidState).into())
}
State::Uninitialized => Err(CliError::InvalidNonce(CliNonceError::InvalidState).into()),
}
}
@ -429,7 +427,7 @@ pub fn process_create_nonce_account(
if let Ok(nonce_account) = rpc_client.get_account(&nonce_account_address) {
let err_msg = if nonce_account.owner == system_program::id()
&& StateMut::<NonceState>::state(&nonce_account).is_ok()
&& StateMut::<Versions>::state(&nonce_account).is_ok()
{
format!("Nonce account {} already exists", nonce_account_address)
} else {
@ -441,7 +439,7 @@ pub fn process_create_nonce_account(
return Err(CliError::BadParameter(err_msg).into());
}
let minimum_balance = rpc_client.get_minimum_balance_for_rent_exemption(NonceState::size())?;
let minimum_balance = rpc_client.get_minimum_balance_for_rent_exemption(State::size())?;
if lamports < minimum_balance {
return Err(CliError::BadParameter(format!(
"need at least {} lamports for nonce account to be rent exempt, provided lamports: {}",
@ -495,9 +493,10 @@ pub fn process_get_nonce(rpc_client: &RpcClient, nonce_account_pubkey: &Pubkey)
))
.into());
}
match nonce_account.state() {
Ok(NonceState::Uninitialized) => Ok("Nonce account is uninitialized".to_string()),
Ok(NonceState::Initialized(_, hash)) => Ok(format!("{:?}", hash)),
let nonce_state = StateMut::<Versions>::state(&nonce_account).map(|v| v.convert_to_current());
match nonce_state {
Ok(State::Uninitialized) => Ok("Nonce account is uninitialized".to_string()),
Ok(State::Initialized(ref data)) => Ok(format!("{:?}", data.blockhash)),
Err(err) => Err(CliError::RpcRequestError(format!(
"Account data could not be deserialized to nonce state: {:?}",
err
@ -554,7 +553,7 @@ pub fn process_show_nonce_account(
))
.into());
}
let print_account = |data: Option<(Meta, Hash)>| {
let print_account = |data: Option<&nonce::state::Data>| {
println!(
"Balance: {}",
build_balance_message(nonce_account.lamports, use_lamports_unit, true)
@ -562,26 +561,32 @@ pub fn process_show_nonce_account(
println!(
"Minimum Balance Required: {}",
build_balance_message(
rpc_client.get_minimum_balance_for_rent_exemption(NonceState::size())?,
rpc_client.get_minimum_balance_for_rent_exemption(State::size())?,
use_lamports_unit,
true
)
);
match data {
Some((meta, hash)) => {
println!("Nonce: {}", hash);
println!("Authority: {}", meta.nonce_authority);
Some(ref data) => {
println!("Nonce: {}", data.blockhash);
println!(
"Fee: {} lamports per signature",
data.fee_calculator.lamports_per_signature
);
println!("Authority: {}", data.authority);
}
None => {
println!("Nonce: uninitialized");
println!("Fees: uninitialized");
println!("Authority: uninitialized");
}
}
Ok("".to_string())
};
match nonce_account.state() {
Ok(NonceState::Uninitialized) => print_account(None),
Ok(NonceState::Initialized(meta, hash)) => print_account(Some((meta, hash))),
let nonce_state = StateMut::<Versions>::state(&nonce_account).map(|v| v.convert_to_current());
match nonce_state {
Ok(State::Uninitialized) => print_account(None),
Ok(State::Initialized(ref data)) => print_account(Some(data)),
Err(err) => Err(CliError::RpcRequestError(format!(
"Account data could not be deserialized to nonce state: {:?}",
err
@ -626,8 +631,9 @@ mod tests {
use crate::cli::{app, parse_command};
use solana_sdk::{
account::Account,
fee_calculator::FeeCalculator,
hash::hash,
nonce_state::{Meta as NonceMeta, NonceState},
nonce::{self, State},
signature::{read_keypair_file, write_keypair, Keypair, Signer},
system_program,
};
@ -903,18 +909,15 @@ mod tests {
fn test_check_nonce_account() {
let blockhash = Hash::default();
let nonce_pubkey = Pubkey::new_rand();
let valid = Account::new_data(
1,
&NonceState::Initialized(NonceMeta::new(&nonce_pubkey), blockhash),
&system_program::ID,
);
let data = Versions::new_current(State::Initialized(nonce::state::Data {
authority: nonce_pubkey,
blockhash,
fee_calculator: FeeCalculator::default(),
}));
let valid = Account::new_data(1, &data, &system_program::ID);
assert!(check_nonce_account(&valid.unwrap(), &nonce_pubkey, &blockhash).is_ok());
let invalid_owner = Account::new_data(
1,
&NonceState::Initialized(NonceMeta::new(&nonce_pubkey), blockhash),
&Pubkey::new(&[1u8; 32]),
);
let invalid_owner = Account::new_data(1, &data, &Pubkey::new(&[1u8; 32]));
assert_eq!(
check_nonce_account(&invalid_owner.unwrap(), &nonce_pubkey, &blockhash),
Err(Box::new(CliError::InvalidNonce(
@ -930,21 +933,23 @@ mod tests {
))),
);
let invalid_hash = Account::new_data(
1,
&NonceState::Initialized(NonceMeta::new(&nonce_pubkey), hash(b"invalid")),
&system_program::ID,
);
let data = Versions::new_current(State::Initialized(nonce::state::Data {
authority: nonce_pubkey,
blockhash: hash(b"invalid"),
fee_calculator: FeeCalculator::default(),
}));
let invalid_hash = Account::new_data(1, &data, &system_program::ID);
assert_eq!(
check_nonce_account(&invalid_hash.unwrap(), &nonce_pubkey, &blockhash),
Err(Box::new(CliError::InvalidNonce(CliNonceError::InvalidHash))),
);
let invalid_authority = Account::new_data(
1,
&NonceState::Initialized(NonceMeta::new(&Pubkey::new_rand()), blockhash),
&system_program::ID,
);
let data = Versions::new_current(State::Initialized(nonce::state::Data {
authority: Pubkey::new_rand(),
blockhash,
fee_calculator: FeeCalculator::default(),
}));
let invalid_authority = Account::new_data(1, &data, &system_program::ID);
assert_eq!(
check_nonce_account(&invalid_authority.unwrap(), &nonce_pubkey, &blockhash),
Err(Box::new(CliError::InvalidNonce(
@ -952,7 +957,8 @@ mod tests {
))),
);
let invalid_state = Account::new_data(1, &NonceState::Uninitialized, &system_program::ID);
let data = Versions::new_current(State::Uninitialized);
let invalid_state = Account::new_data(1, &data, &system_program::ID);
assert_eq!(
check_nonce_account(&invalid_state.unwrap(), &nonce_pubkey, &blockhash),
Err(Box::new(CliError::InvalidNonce(

View File

@ -11,7 +11,7 @@ use solana_faucet::faucet::run_local_faucet;
use solana_sdk::{
account_utils::StateMut,
fee_calculator::FeeCalculator,
nonce_state::NonceState,
nonce,
pubkey::Pubkey,
signature::{Keypair, Signer},
};
@ -377,7 +377,7 @@ fn test_nonced_pay_tx() {
config.signers = vec![&default_signer];
let minimum_nonce_balance = rpc_client
.get_minimum_balance_for_rent_exemption(NonceState::size())
.get_minimum_balance_for_rent_exemption(nonce::State::size())
.unwrap();
request_and_confirm_airdrop(
@ -409,9 +409,11 @@ fn test_nonced_pay_tx() {
// Fetch nonce hash
let account = rpc_client.get_account(&nonce_account.pubkey()).unwrap();
let nonce_state: NonceState = account.state().unwrap();
let nonce_state = StateMut::<nonce::state::Versions>::state(&account)
.unwrap()
.convert_to_current();
let nonce_hash = match nonce_state {
NonceState::Initialized(_meta, hash) => hash,
nonce::State::Initialized(ref data) => data.blockhash,
_ => panic!("Nonce is not initialized"),
};
@ -431,9 +433,11 @@ fn test_nonced_pay_tx() {
// Verify that nonce has been used
let account = rpc_client.get_account(&nonce_account.pubkey()).unwrap();
let nonce_state: NonceState = account.state().unwrap();
let nonce_state = StateMut::<nonce::state::Versions>::state(&account)
.unwrap()
.convert_to_current();
match nonce_state {
NonceState::Initialized(_meta, hash) => assert_ne!(hash, nonce_hash),
nonce::State::Initialized(ref data) => assert_ne!(data.blockhash, nonce_hash),
_ => assert!(false, "Nonce is not initialized"),
}

View File

@ -9,7 +9,7 @@ use solana_faucet::faucet::run_local_faucet;
use solana_sdk::{
account_utils::StateMut,
fee_calculator::FeeCalculator,
nonce_state::NonceState,
nonce,
pubkey::Pubkey,
signature::{keypair_from_seed, Keypair, Signer},
system_instruction::create_address_with_seed,
@ -457,7 +457,7 @@ fn test_nonced_stake_delegation_and_deactivation() {
config.json_rpc_url = format!("http://{}:{}", leader_data.rpc.ip(), leader_data.rpc.port());
let minimum_nonce_balance = rpc_client
.get_minimum_balance_for_rent_exemption(NonceState::size())
.get_minimum_balance_for_rent_exemption(nonce::State::size())
.unwrap();
request_and_confirm_airdrop(
@ -500,9 +500,11 @@ fn test_nonced_stake_delegation_and_deactivation() {
// Fetch nonce hash
let account = rpc_client.get_account(&nonce_account.pubkey()).unwrap();
let nonce_state: NonceState = account.state().unwrap();
let nonce_state = StateMut::<nonce::state::Versions>::state(&account)
.unwrap()
.convert_to_current();
let nonce_hash = match nonce_state {
NonceState::Initialized(_meta, hash) => hash,
nonce::State::Initialized(ref data) => data.blockhash,
_ => panic!("Nonce is not initialized"),
};
@ -523,9 +525,11 @@ fn test_nonced_stake_delegation_and_deactivation() {
// Fetch nonce hash
let account = rpc_client.get_account(&nonce_account.pubkey()).unwrap();
let nonce_state: NonceState = account.state().unwrap();
let nonce_state = StateMut::<nonce::state::Versions>::state(&account)
.unwrap()
.convert_to_current();
let nonce_hash = match nonce_state {
NonceState::Initialized(_meta, hash) => hash,
nonce::State::Initialized(ref data) => data.blockhash,
_ => panic!("Nonce is not initialized"),
};
@ -700,7 +704,7 @@ fn test_stake_authorize() {
// Create nonce account
let minimum_nonce_balance = rpc_client
.get_minimum_balance_for_rent_exemption(NonceState::size())
.get_minimum_balance_for_rent_exemption(nonce::State::size())
.unwrap();
let nonce_account = Keypair::new();
config.signers = vec![&default_signer, &nonce_account];
@ -714,9 +718,11 @@ fn test_stake_authorize() {
// Fetch nonce hash
let account = rpc_client.get_account(&nonce_account.pubkey()).unwrap();
let nonce_state: NonceState = account.state().unwrap();
let nonce_state = StateMut::<nonce::state::Versions>::state(&account)
.unwrap()
.convert_to_current();
let nonce_hash = match nonce_state {
NonceState::Initialized(_meta, hash) => hash,
nonce::State::Initialized(ref data) => data.blockhash,
_ => panic!("Nonce is not initialized"),
};
@ -763,9 +769,11 @@ fn test_stake_authorize() {
};
assert_eq!(current_authority, online_authority_pubkey);
let account = rpc_client.get_account(&nonce_account.pubkey()).unwrap();
let nonce_state: NonceState = account.state().unwrap();
let nonce_state = StateMut::<nonce::state::Versions>::state(&account)
.unwrap()
.convert_to_current();
let new_nonce_hash = match nonce_state {
NonceState::Initialized(_meta, hash) => hash,
nonce::State::Initialized(ref data) => data.blockhash,
_ => panic!("Nonce is not initialized"),
};
assert_ne!(nonce_hash, new_nonce_hash);
@ -982,7 +990,7 @@ fn test_stake_split() {
// Create nonce account
let minimum_nonce_balance = rpc_client
.get_minimum_balance_for_rent_exemption(NonceState::size())
.get_minimum_balance_for_rent_exemption(nonce::State::size())
.unwrap();
let nonce_account = keypair_from_seed(&[1u8; 32]).unwrap();
config.signers = vec![&default_signer, &nonce_account];
@ -997,9 +1005,11 @@ fn test_stake_split() {
// Fetch nonce hash
let account = rpc_client.get_account(&nonce_account.pubkey()).unwrap();
let nonce_state: NonceState = account.state().unwrap();
let nonce_state = StateMut::<nonce::state::Versions>::state(&account)
.unwrap()
.convert_to_current();
let nonce_hash = match nonce_state {
NonceState::Initialized(_meta, hash) => hash,
nonce::State::Initialized(ref data) => data.blockhash,
_ => panic!("Nonce is not initialized"),
};
@ -1232,7 +1242,7 @@ fn test_stake_set_lockup() {
// Create nonce account
let minimum_nonce_balance = rpc_client
.get_minimum_balance_for_rent_exemption(NonceState::size())
.get_minimum_balance_for_rent_exemption(nonce::State::size())
.unwrap();
let nonce_account = keypair_from_seed(&[1u8; 32]).unwrap();
let nonce_account_pubkey = nonce_account.pubkey();
@ -1248,9 +1258,11 @@ fn test_stake_set_lockup() {
// Fetch nonce hash
let account = rpc_client.get_account(&nonce_account_pubkey).unwrap();
let nonce_state: NonceState = account.state().unwrap();
let nonce_state = StateMut::<nonce::state::Versions>::state(&account)
.unwrap()
.convert_to_current();
let nonce_hash = match nonce_state {
NonceState::Initialized(_meta, hash) => hash,
nonce::State::Initialized(ref data) => data.blockhash,
_ => panic!("Nonce is not initialized"),
};
@ -1347,7 +1359,7 @@ fn test_offline_nonced_create_stake_account_and_withdraw() {
// Create nonce account
let minimum_nonce_balance = rpc_client
.get_minimum_balance_for_rent_exemption(NonceState::size())
.get_minimum_balance_for_rent_exemption(nonce::State::size())
.unwrap();
let nonce_account = keypair_from_seed(&[3u8; 32]).unwrap();
let nonce_pubkey = nonce_account.pubkey();
@ -1362,9 +1374,11 @@ fn test_offline_nonced_create_stake_account_and_withdraw() {
// Fetch nonce hash
let account = rpc_client.get_account(&nonce_account.pubkey()).unwrap();
let nonce_state: NonceState = account.state().unwrap();
let nonce_state = StateMut::<nonce::state::Versions>::state(&account)
.unwrap()
.convert_to_current();
let nonce_hash = match nonce_state {
NonceState::Initialized(_meta, hash) => hash,
nonce::State::Initialized(ref data) => data.blockhash,
_ => panic!("Nonce is not initialized"),
};
@ -1410,9 +1424,11 @@ fn test_offline_nonced_create_stake_account_and_withdraw() {
// Fetch nonce hash
let account = rpc_client.get_account(&nonce_account.pubkey()).unwrap();
let nonce_state: NonceState = account.state().unwrap();
let nonce_state = StateMut::<nonce::state::Versions>::state(&account)
.unwrap()
.convert_to_current();
let nonce_hash = match nonce_state {
NonceState::Initialized(_meta, hash) => hash,
nonce::State::Initialized(ref data) => data.blockhash,
_ => panic!("Nonce is not initialized"),
};
@ -1451,9 +1467,11 @@ fn test_offline_nonced_create_stake_account_and_withdraw() {
// Fetch nonce hash
let account = rpc_client.get_account(&nonce_account.pubkey()).unwrap();
let nonce_state: NonceState = account.state().unwrap();
let nonce_state = StateMut::<nonce::state::Versions>::state(&account)
.unwrap()
.convert_to_current();
let nonce_hash = match nonce_state {
NonceState::Initialized(_meta, hash) => hash,
nonce::State::Initialized(ref data) => data.blockhash,
_ => panic!("Nonce is not initialized"),
};

View File

@ -9,7 +9,7 @@ use solana_faucet::faucet::run_local_faucet;
use solana_sdk::{
account_utils::StateMut,
fee_calculator::FeeCalculator,
nonce_state::NonceState,
nonce,
pubkey::Pubkey,
signature::{keypair_from_seed, Keypair, Signer},
};
@ -120,7 +120,7 @@ fn test_transfer() {
// Create nonce account
let nonce_account = keypair_from_seed(&[3u8; 32]).unwrap();
let minimum_nonce_balance = rpc_client
.get_minimum_balance_for_rent_exemption(NonceState::size())
.get_minimum_balance_for_rent_exemption(nonce::State::size())
.unwrap();
config.signers = vec![&default_signer, &nonce_account];
config.command = CliCommand::CreateNonceAccount {
@ -134,9 +134,11 @@ fn test_transfer() {
// Fetch nonce hash
let account = rpc_client.get_account(&nonce_account.pubkey()).unwrap();
let nonce_state: NonceState = account.state().unwrap();
let nonce_state = StateMut::<nonce::state::Versions>::state(&account)
.unwrap()
.convert_to_current();
let nonce_hash = match nonce_state {
NonceState::Initialized(_meta, hash) => hash,
nonce::State::Initialized(ref data) => data.blockhash,
_ => panic!("Nonce is not initialized"),
};
@ -156,9 +158,11 @@ fn test_transfer() {
check_balance(49_976 - minimum_nonce_balance, &rpc_client, &sender_pubkey);
check_balance(30, &rpc_client, &recipient_pubkey);
let account = rpc_client.get_account(&nonce_account.pubkey()).unwrap();
let nonce_state: NonceState = account.state().unwrap();
let nonce_state = StateMut::<nonce::state::Versions>::state(&account)
.unwrap()
.convert_to_current();
let new_nonce_hash = match nonce_state {
NonceState::Initialized(_meta, hash) => hash,
nonce::State::Initialized(ref data) => data.blockhash,
_ => panic!("Nonce is not initialized"),
};
assert_ne!(nonce_hash, new_nonce_hash);
@ -175,9 +179,11 @@ fn test_transfer() {
// Fetch nonce hash
let account = rpc_client.get_account(&nonce_account.pubkey()).unwrap();
let nonce_state: NonceState = account.state().unwrap();
let nonce_state = StateMut::<nonce::state::Versions>::state(&account)
.unwrap()
.convert_to_current();
let nonce_hash = match nonce_state {
NonceState::Initialized(_meta, hash) => hash,
nonce::State::Initialized(ref data) => data.blockhash,
_ => panic!("Nonce is not initialized"),
};

View File

@ -1,7 +1,10 @@
use crossbeam_channel::{Receiver, RecvTimeoutError};
use solana_client::rpc_response::RpcTransactionStatus;
use solana_ledger::{blockstore::Blockstore, blockstore_processor::TransactionStatusBatch};
use solana_runtime::bank::{Bank, HashAgeKind};
use solana_runtime::{
bank::{Bank, HashAgeKind},
nonce_utils,
};
use std::{
sync::{
atomic::{AtomicBool, Ordering},
@ -59,14 +62,13 @@ impl TransactionStatusService {
.zip(balances.post_balances)
{
if Bank::can_commit(&status) && !transaction.signatures.is_empty() {
let fee_hash = if let Some(HashAgeKind::DurableNonce(_, _)) = hash_age_kind {
bank.last_blockhash()
} else {
transaction.message().recent_blockhash
};
let fee_calculator = bank
.get_fee_calculator(&fee_hash)
.expect("FeeCalculator must exist");
let fee_calculator = match hash_age_kind {
Some(HashAgeKind::DurableNonce(_, account)) => {
nonce_utils::fee_calculator_of(&account)
}
_ => bank.get_fee_calculator(&transaction.message().recent_blockhash),
}
.expect("FeeCalculator must exist");
let fee = fee_calculator.calculate_fee(transaction.message());
blockstore
.write_transaction_status(

View File

@ -6,7 +6,7 @@ use crate::{
append_vec::StoredAccount,
bank::{HashAgeKind, TransactionProcessResult},
blockhash_queue::BlockhashQueue,
nonce_utils::prepare_if_nonce_account,
nonce_utils,
rent_collector::RentCollector,
system_instruction_processor::{get_system_account_kind, SystemAccountKind},
transaction_utils::OrderedIterator,
@ -17,8 +17,7 @@ use solana_sdk::{
account::Account,
clock::Slot,
hash::Hash,
native_loader,
nonce_state::NonceState,
native_loader, nonce,
pubkey::Pubkey,
transaction::Result,
transaction::{Transaction, TransactionError},
@ -160,7 +159,7 @@ impl Accounts {
})? {
SystemAccountKind::System => 0,
SystemAccountKind::Nonce => {
rent_collector.rent.minimum_balance(NonceState::size())
rent_collector.rent.minimum_balance(nonce::State::size())
}
};
@ -266,13 +265,15 @@ impl Accounts {
.zip(lock_results.into_iter())
.map(|etx| match etx {
(tx, (Ok(()), hash_age_kind)) => {
let fee_hash = if let Some(HashAgeKind::DurableNonce(_, _)) = hash_age_kind {
hash_queue.last_hash()
} else {
tx.message().recent_blockhash
let fee_calculator = match hash_age_kind.as_ref() {
Some(HashAgeKind::DurableNonce(_, account)) => {
nonce_utils::fee_calculator_of(account)
}
_ => hash_queue
.get_fee_calculator(&tx.message().recent_blockhash)
.cloned(),
};
let fee = if let Some(fee_calculator) = hash_queue.get_fee_calculator(&fee_hash)
{
let fee = if let Some(fee_calculator) = fee_calculator {
fee_calculator.calculate_fee(tx.message())
} else {
return (Err(TransactionError::BlockhashNotFound), hash_age_kind);
@ -631,7 +632,13 @@ impl Accounts {
.enumerate()
.zip(acc.0.iter_mut())
{
prepare_if_nonce_account(account, key, res, maybe_nonce, last_blockhash);
nonce_utils::prepare_if_nonce_account(
account,
key,
res,
maybe_nonce,
last_blockhash,
);
if message.is_writable(i) {
if account.rent_epoch == 0 {
account.rent_epoch = rent_collector.epoch;
@ -681,7 +688,7 @@ mod tests {
hash::Hash,
instruction::CompiledInstruction,
message::Message,
nonce_state,
nonce,
rent::Rent,
signature::{Keypair, Signer},
system_program,
@ -915,19 +922,16 @@ mod tests {
..Rent::default()
},
);
let min_balance = rent_collector
.rent
.minimum_balance(nonce_state::NonceState::size());
let min_balance = rent_collector.rent.minimum_balance(nonce::State::size());
let fee_calculator = FeeCalculator::new(min_balance);
let nonce = Keypair::new();
let mut accounts = vec![(
nonce.pubkey(),
Account::new_data(
min_balance * 2,
&nonce_state::NonceState::Initialized(
nonce_state::Meta::new(&Pubkey::default()),
Hash::default(),
),
&nonce::state::Versions::new_current(nonce::State::Initialized(
nonce::state::Data::default(),
)),
&system_program::id(),
)
.unwrap(),

View File

@ -40,8 +40,7 @@ use solana_sdk::{
hard_forks::HardForks,
hash::{extend_and_hash, hashv, Hash},
inflation::Inflation,
native_loader,
nonce_state::NonceState,
native_loader, nonce,
pubkey::Pubkey,
signature::{Keypair, Signature},
slot_hashes::SlotHashes,
@ -1410,19 +1409,20 @@ impl Bank {
let results = OrderedIterator::new(txs, iteration_order)
.zip(executed.iter())
.map(|(tx, (res, hash_age_kind))| {
let is_durable_nonce = hash_age_kind
.as_ref()
.map(|hash_age_kind| hash_age_kind.is_durable_nonce())
.unwrap_or(false);
let fee_hash = if is_durable_nonce {
self.last_blockhash()
} else {
tx.message().recent_blockhash
let (fee_calculator, is_durable_nonce) = match hash_age_kind {
Some(HashAgeKind::DurableNonce(_, account)) => {
(nonce_utils::fee_calculator_of(account), true)
}
_ => (
hash_queue
.get_fee_calculator(&tx.message().recent_blockhash)
.cloned(),
false,
),
};
let fee = hash_queue
.get_fee_calculator(&fee_hash)
.ok_or(TransactionError::BlockhashNotFound)?
.calculate_fee(tx.message());
let fee_calculator = fee_calculator.ok_or(TransactionError::BlockhashNotFound)?;
let fee = fee_calculator.calculate_fee(tx.message());
let message = tx.message();
match *res {
@ -1691,9 +1691,10 @@ impl Bank {
match self.get_account(pubkey) {
Some(mut account) => {
let min_balance = match get_system_account_kind(&account) {
Some(SystemAccountKind::Nonce) => {
self.rent_collector.rent.minimum_balance(NonceState::size())
}
Some(SystemAccountKind::Nonce) => self
.rent_collector
.rent
.minimum_balance(nonce::State::size()),
_ => 0,
};
if lamports + min_balance > account.lamports {
@ -2165,7 +2166,7 @@ mod tests {
genesis_config::create_genesis_config,
instruction::{AccountMeta, CompiledInstruction, Instruction, InstructionError},
message::{Message, MessageHeader},
nonce_state,
nonce,
poh_config::PohConfig,
rent::Rent,
signature::{Keypair, Signer},
@ -3413,15 +3414,13 @@ mod tests {
genesis_config.rent.lamports_per_byte_year = 42;
let bank = Bank::new(&genesis_config);
let min_balance =
bank.get_minimum_balance_for_rent_exemption(nonce_state::NonceState::size());
let min_balance = bank.get_minimum_balance_for_rent_exemption(nonce::State::size());
let nonce = Keypair::new();
let nonce_account = Account::new_data(
min_balance + 42,
&nonce_state::NonceState::Initialized(
nonce_state::Meta::new(&Pubkey::default()),
Hash::default(),
),
&nonce::state::Versions::new_current(nonce::State::Initialized(
nonce::state::Data::default(),
)),
&system_program::id(),
)
.unwrap();
@ -4992,9 +4991,9 @@ mod tests {
sysvar::recent_blockhashes::RecentBlockhashes::from_account(&bhq_account).unwrap();
// Check length
assert_eq!(recent_blockhashes.len(), i);
let most_recent_hash = recent_blockhashes.iter().nth(0).unwrap();
let most_recent_hash = recent_blockhashes.iter().nth(0).unwrap().blockhash;
// Check order
assert_eq!(Some(true), bank.check_hash_age(most_recent_hash, 0));
assert_eq!(Some(true), bank.check_hash_age(&most_recent_hash, 0));
goto_end_of_slot(Arc::get_mut(&mut bank).unwrap());
bank = Arc::new(new_from_parent(&bank));
}
@ -5098,11 +5097,14 @@ mod tests {
}
fn get_nonce_account(bank: &Bank, nonce_pubkey: &Pubkey) -> Option<Hash> {
bank.get_account(&nonce_pubkey)
.and_then(|acc| match acc.state() {
Ok(nonce_state::NonceState::Initialized(_meta, hash)) => Some(hash),
bank.get_account(&nonce_pubkey).and_then(|acc| {
let state =
StateMut::<nonce::state::Versions>::state(&acc).map(|v| v.convert_to_current());
match state {
Ok(nonce::State::Initialized(ref data)) => Some(data.blockhash),
_ => None,
})
}
})
}
fn nonce_setup(
@ -5151,6 +5153,13 @@ mod tests {
genesis_cfg_fn(&mut genesis_config);
let mut bank = Arc::new(Bank::new(&genesis_config));
// Banks 0 and 1 have no fees, wait two blocks before
// initializing our nonce accounts
for _ in 0..2 {
goto_end_of_slot(Arc::get_mut(&mut bank).unwrap());
bank = Arc::new(new_from_parent(&bank));
}
let (custodian_keypair, nonce_keypair) = nonce_setup(
&mut bank,
&mint_keypair,
@ -5274,10 +5283,9 @@ mod tests {
let nonce = Keypair::new();
let nonce_account = Account::new_data(
42424242,
&nonce_state::NonceState::Initialized(
nonce_state::Meta::new(&Pubkey::default()),
Hash::default(),
),
&nonce::state::Versions::new_current(nonce::State::Initialized(
nonce::state::Data::default(),
)),
&system_program::id(),
)
.unwrap();

View File

@ -1,5 +1,7 @@
use serde::{Deserialize, Serialize};
use solana_sdk::{fee_calculator::FeeCalculator, hash::Hash, timing::timestamp};
use solana_sdk::{
fee_calculator::FeeCalculator, hash::Hash, sysvar::recent_blockhashes, timing::timestamp,
};
use std::collections::HashMap;
#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
@ -112,15 +114,19 @@ impl BlockhashQueue {
None
}
pub fn get_recent_blockhashes(&self) -> impl Iterator<Item = (u64, &Hash)> {
(&self.ages).iter().map(|(k, v)| (v.hash_height, k))
pub fn get_recent_blockhashes(&self) -> impl Iterator<Item = recent_blockhashes::IterItem> {
(&self.ages)
.iter()
.map(|(k, v)| recent_blockhashes::IterItem(v.hash_height, k, &v.fee_calculator))
}
}
#[cfg(test)]
mod tests {
use super::*;
use bincode::serialize;
use solana_sdk::{clock::MAX_RECENT_BLOCKHASHES, hash::hash};
use solana_sdk::{
clock::MAX_RECENT_BLOCKHASHES, hash::hash, sysvar::recent_blockhashes::IterItem,
};
#[test]
fn test_register_hash() {
@ -172,7 +178,7 @@ mod tests {
}
let recent_blockhashes = blockhash_queue.get_recent_blockhashes();
// Verify that the returned hashes are most recent
for (_slot, hash) in recent_blockhashes {
for IterItem(_slot, hash, _fee_calc) in recent_blockhashes {
assert_eq!(
Some(true),
blockhash_queue.check_hash_age(hash, MAX_RECENT_BLOCKHASHES)

View File

@ -10,7 +10,7 @@ pub mod genesis_utils;
pub mod loader_utils;
pub mod message_processor;
mod native_loader;
mod nonce_utils;
pub mod nonce_utils;
pub mod rent_collector;
mod serde_utils;
pub mod stakes;

View File

@ -1,9 +1,10 @@
use solana_sdk::{
account::Account,
account_utils::StateMut,
fee_calculator::FeeCalculator,
hash::Hash,
instruction::CompiledInstruction,
nonce_state::NonceState,
nonce::{self, state::Versions, State},
program_utils::limited_deserialize,
pubkey::Pubkey,
system_instruction::SystemInstruction,
@ -39,8 +40,8 @@ pub fn get_nonce_pubkey_from_instruction<'a>(
}
pub fn verify_nonce_account(acc: &Account, hash: &Hash) -> bool {
match acc.state() {
Ok(NonceState::Initialized(_meta, ref nonce)) => hash == nonce,
match StateMut::<Versions>::state(acc).map(|v| v.convert_to_current()) {
Ok(State::Initialized(ref data)) => *hash == data.blockhash,
_ => false,
}
}
@ -60,24 +61,39 @@ pub fn prepare_if_nonce_account(
*account = nonce_acc.clone()
}
// Since hash_age_kind is DurableNonce, unwrap is safe here
if let NonceState::Initialized(meta, _) = account.state().unwrap() {
account
.set_state(&NonceState::Initialized(meta, *last_blockhash))
.unwrap();
let state = StateMut::<Versions>::state(nonce_acc)
.unwrap()
.convert_to_current();
if let State::Initialized(ref data) = state {
let new_data = Versions::new_current(State::Initialized(nonce::state::Data {
blockhash: *last_blockhash,
..data.clone()
}));
account.set_state(&new_data).unwrap();
}
}
}
}
pub fn fee_calculator_of(account: &Account) -> Option<FeeCalculator> {
let state = StateMut::<Versions>::state(account)
.ok()?
.convert_to_current();
match state {
State::Initialized(data) => Some(data.fee_calculator),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
use solana_sdk::{
account::Account,
account_utils::State,
account_utils::State as AccountUtilsState,
hash::Hash,
instruction::InstructionError,
nonce_state::{with_test_keyed_account, Meta, NonceAccount},
nonce::{self, account::with_test_keyed_account, Account as NonceAccount, State},
pubkey::Pubkey,
signature::{Keypair, Signer},
system_instruction,
@ -193,9 +209,9 @@ mod tests {
with_test_keyed_account(42, true, |nonce_account| {
let mut signers = HashSet::new();
signers.insert(nonce_account.signer_key().unwrap().clone());
let state: NonceState = nonce_account.state().unwrap();
let state: State = nonce_account.state().unwrap();
// New is in Uninitialzed state
assert_eq!(state, NonceState::Uninitialized);
assert_eq!(state, State::Uninitialized);
let recent_blockhashes = create_test_recent_blockhashes(0);
let authorized = nonce_account.unsigned_key().clone();
nonce_account
@ -203,7 +219,7 @@ mod tests {
.unwrap();
assert!(verify_nonce_account(
&nonce_account.account.borrow(),
&recent_blockhashes[0]
&recent_blockhashes[0].blockhash,
));
});
}
@ -223,9 +239,9 @@ mod tests {
with_test_keyed_account(42, true, |nonce_account| {
let mut signers = HashSet::new();
signers.insert(nonce_account.signer_key().unwrap().clone());
let state: NonceState = nonce_account.state().unwrap();
let state: State = nonce_account.state().unwrap();
// New is in Uninitialzed state
assert_eq!(state, NonceState::Uninitialized);
assert_eq!(state, State::Uninitialized);
let recent_blockhashes = create_test_recent_blockhashes(0);
let authorized = nonce_account.unsigned_key().clone();
nonce_account
@ -233,19 +249,14 @@ mod tests {
.unwrap();
assert!(!verify_nonce_account(
&nonce_account.account.borrow(),
&recent_blockhashes[1]
&recent_blockhashes[1].blockhash,
));
});
}
fn create_accounts_prepare_if_nonce_account() -> (Pubkey, Account, Account, Hash) {
let stored_nonce = Hash::default();
let account = Account::new_data(
42,
&NonceState::Initialized(Meta::new(&Pubkey::default()), stored_nonce),
&system_program::id(),
)
.unwrap();
let data = Versions::new_current(State::Initialized(nonce::state::Data::default()));
let account = Account::new_data(42, &data, &system_program::id()).unwrap();
let pre_account = Account {
lamports: 43,
..account.clone()
@ -296,12 +307,11 @@ mod tests {
let post_account_pubkey = pre_account_pubkey;
let mut expect_account = post_account.clone();
expect_account
.set_state(&NonceState::Initialized(
Meta::new(&Pubkey::default()),
last_blockhash,
))
.unwrap();
let data = Versions::new_current(State::Initialized(nonce::state::Data {
blockhash: last_blockhash,
..nonce::state::Data::default()
}));
expect_account.set_state(&data).unwrap();
assert!(run_prepare_if_nonce_account_test(
&mut post_account,
@ -356,10 +366,12 @@ mod tests {
let mut expect_account = pre_account.clone();
expect_account
.set_state(&NonceState::Initialized(
Meta::new(&Pubkey::default()),
last_blockhash,
))
.set_state(&Versions::new_current(State::Initialized(
nonce::state::Data {
blockhash: last_blockhash,
..nonce::state::Data::default()
},
)))
.unwrap();
assert!(run_prepare_if_nonce_account_test(

View File

@ -3,7 +3,7 @@ use solana_sdk::{
account::{get_signers, Account, KeyedAccount},
account_utils::StateMut,
instruction::InstructionError,
nonce_state::{NonceAccount, NonceState},
nonce::{self, Account as NonceAccount},
program_utils::{limited_deserialize, next_keyed_account},
pubkey::Pubkey,
system_instruction::{
@ -306,8 +306,13 @@ pub fn get_system_account_kind(account: &Account) -> Option<SystemAccountKind> {
if system_program::check_id(&account.owner) {
if account.data.is_empty() {
Some(SystemAccountKind::System)
} else if let Ok(NonceState::Initialized(_, _)) = account.state() {
Some(SystemAccountKind::Nonce)
} else if account.data.len() == nonce::State::size() {
match account.state().ok()? {
nonce::state::Versions::Current(state) => match *state {
nonce::State::Initialized(_) => Some(SystemAccountKind::Nonce),
_ => None,
},
}
} else {
None
}
@ -324,13 +329,15 @@ mod tests {
use solana_sdk::{
account::Account,
client::SyncClient,
fee_calculator::FeeCalculator,
genesis_config::create_genesis_config,
hash::{hash, Hash},
instruction::{AccountMeta, Instruction, InstructionError},
message::Message,
nonce_state,
nonce,
signature::{Keypair, Signer},
system_instruction, system_program, sysvar,
sysvar::recent_blockhashes::IterItem,
transaction::TransactionError,
};
use std::cell::RefCell;
@ -351,14 +358,11 @@ mod tests {
fn create_default_recent_blockhashes_account() -> RefCell<Account> {
RefCell::new(sysvar::recent_blockhashes::create_account_with_data(
1,
vec![(0u64, &Hash::default()); 32].into_iter(),
vec![IterItem(0u64, &Hash::default(), &FeeCalculator::default()); 32].into_iter(),
))
}
fn create_default_rent_account() -> RefCell<Account> {
RefCell::new(sysvar::recent_blockhashes::create_account_with_data(
1,
vec![(0u64, &Hash::default()); 32].into_iter(),
))
RefCell::new(sysvar::rent::create_account(1, &Rent::free()))
}
#[test]
@ -737,10 +741,9 @@ mod tests {
let nonce = Pubkey::new_rand();
let nonce_account = Account::new_ref_data(
42,
&nonce_state::NonceState::Initialized(
nonce_state::Meta::new(&Pubkey::default()),
Hash::default(),
),
&nonce::state::Versions::new_current(nonce::State::Initialized(
nonce::state::Data::default(),
)),
&system_program::id(),
)
.unwrap();
@ -879,7 +882,10 @@ mod tests {
let from = Pubkey::new_rand();
let from_account = Account::new_ref_data(
100,
&nonce_state::NonceState::Initialized(nonce_state::Meta::new(&from), Hash::default()),
&nonce::state::Versions::new_current(nonce::State::Initialized(nonce::state::Data {
authority: from,
..nonce::state::Data::default()
})),
&system_program::id(),
)
.unwrap();
@ -1084,7 +1090,8 @@ mod tests {
RefCell::new(if sysvar::recent_blockhashes::check_id(&meta.pubkey) {
sysvar::recent_blockhashes::create_account_with_data(
1,
vec![(0u64, &Hash::default()); 32].into_iter(),
vec![IterItem(0u64, &Hash::default(), &FeeCalculator::default()); 32]
.into_iter(),
)
} else if sysvar::rent::check_id(&meta.pubkey) {
sysvar::rent::create_account(1, &Rent::free())
@ -1165,7 +1172,7 @@ mod tests {
#[test]
fn test_process_nonce_ix_ok() {
let nonce_acc = nonce_state::create_account(1_000_000);
let nonce_acc = nonce::create_account(1_000_000);
super::process_instruction(
&Pubkey::default(),
&[
@ -1183,7 +1190,15 @@ mod tests {
let new_recent_blockhashes_account =
RefCell::new(sysvar::recent_blockhashes::create_account_with_data(
1,
vec![(0u64, &hash(&serialize(&0).unwrap())); 32].into_iter(),
vec![
IterItem(
0u64,
&hash(&serialize(&0).unwrap()),
&FeeCalculator::default()
);
32
]
.into_iter(),
));
assert_eq!(
super::process_instruction(
@ -1269,11 +1284,7 @@ mod tests {
super::process_instruction(
&Pubkey::default(),
&[
KeyedAccount::new(
&Pubkey::default(),
true,
&nonce_state::create_account(1_000_000),
),
KeyedAccount::new(&Pubkey::default(), true, &nonce::create_account(1_000_000),),
KeyedAccount::new(&Pubkey::default(), true, &create_default_account()),
KeyedAccount::new(
&sysvar::recent_blockhashes::id(),
@ -1294,11 +1305,7 @@ mod tests {
super::process_instruction(
&Pubkey::default(),
&[
KeyedAccount::new(
&Pubkey::default(),
true,
&nonce_state::create_account(1_000_000),
),
KeyedAccount::new(&Pubkey::default(), true, &nonce::create_account(1_000_000),),
KeyedAccount::new(&Pubkey::default(), true, &create_default_account()),
KeyedAccount::new(
&sysvar::recent_blockhashes::id(),
@ -1333,7 +1340,7 @@ mod tests {
&[KeyedAccount::new(
&Pubkey::default(),
true,
&nonce_state::create_account(1_000_000),
&nonce::create_account(1_000_000),
),],
&serialize(&SystemInstruction::InitializeNonceAccount(Pubkey::default())).unwrap(),
),
@ -1347,11 +1354,7 @@ mod tests {
super::process_instruction(
&Pubkey::default(),
&[
KeyedAccount::new(
&Pubkey::default(),
true,
&nonce_state::create_account(1_000_000),
),
KeyedAccount::new(&Pubkey::default(), true, &nonce::create_account(1_000_000),),
KeyedAccount::new(
&sysvar::recent_blockhashes::id(),
false,
@ -1370,11 +1373,7 @@ mod tests {
super::process_instruction(
&Pubkey::default(),
&[
KeyedAccount::new(
&Pubkey::default(),
true,
&nonce_state::create_account(1_000_000),
),
KeyedAccount::new(&Pubkey::default(), true, &nonce::create_account(1_000_000),),
KeyedAccount::new(
&sysvar::recent_blockhashes::id(),
false,
@ -1394,11 +1393,7 @@ mod tests {
super::process_instruction(
&Pubkey::default(),
&[
KeyedAccount::new(
&Pubkey::default(),
true,
&nonce_state::create_account(1_000_000),
),
KeyedAccount::new(&Pubkey::default(), true, &nonce::create_account(1_000_000),),
KeyedAccount::new(
&sysvar::recent_blockhashes::id(),
false,
@ -1414,7 +1409,7 @@ mod tests {
#[test]
fn test_process_authorize_ix_ok() {
let nonce_acc = nonce_state::create_account(1_000_000);
let nonce_acc = nonce::create_account(1_000_000);
super::process_instruction(
&Pubkey::default(),
&[
@ -1464,10 +1459,9 @@ mod tests {
fn test_get_system_account_kind_nonce_ok() {
let nonce_account = Account::new_data(
42,
&nonce_state::NonceState::Initialized(
nonce_state::Meta::new(&Pubkey::default()),
Hash::default(),
),
&nonce::state::Versions::new_current(nonce::State::Initialized(
nonce::state::Data::default(),
)),
&system_program::id(),
)
.unwrap();
@ -1480,7 +1474,7 @@ mod tests {
#[test]
fn test_get_system_account_kind_uninitialized_nonce_account_fail() {
assert_eq!(
get_system_account_kind(&nonce_state::create_account(42).borrow()),
get_system_account_kind(&nonce::create_account(42).borrow()),
None
);
}
@ -1492,13 +1486,12 @@ mod tests {
}
#[test]
fn test_get_system_account_kind_nonsystem_owner_with_nonce_state_data_fail() {
fn test_get_system_account_kind_nonsystem_owner_with_nonce_data_fail() {
let nonce_account = Account::new_data(
42,
&nonce_state::NonceState::Initialized(
nonce_state::Meta::new(&Pubkey::default()),
Hash::default(),
),
&nonce::state::Versions::new_current(nonce::State::Initialized(
nonce::state::Data::default(),
)),
&Pubkey::new_rand(),
)
.unwrap();

View File

@ -17,7 +17,7 @@ pub mod message;
pub mod move_loader;
pub mod native_loader;
pub mod native_token;
pub mod nonce_state;
pub mod nonce;
pub mod packet;
pub mod poh_config;
pub mod program_utils;

View File

@ -1,49 +1,16 @@
use crate::{
account::{Account, KeyedAccount},
account_utils::State,
hash::Hash,
account::{self, KeyedAccount},
account_utils::State as AccountUtilsState,
instruction::InstructionError,
nonce::{self, state::Versions, State},
pubkey::Pubkey,
system_instruction::NonceError,
system_program,
sysvar::{recent_blockhashes::RecentBlockhashes, rent::Rent},
};
use serde_derive::{Deserialize, Serialize};
use std::{cell::RefCell, collections::HashSet};
#[derive(Debug, Default, Serialize, Deserialize, PartialEq, Clone, Copy)]
pub struct Meta {
pub nonce_authority: Pubkey,
}
impl Meta {
pub fn new(nonce_authority: &Pubkey) -> Self {
Self {
nonce_authority: *nonce_authority,
}
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Copy)]
pub enum NonceState {
Uninitialized,
Initialized(Meta, Hash),
}
impl Default for NonceState {
fn default() -> Self {
NonceState::Uninitialized
}
}
impl NonceState {
pub fn size() -> usize {
bincode::serialized_size(&NonceState::Initialized(Meta::default(), Hash::default()))
.unwrap() as usize
}
}
pub trait NonceAccount {
pub trait Account {
fn advance_nonce_account(
&self,
recent_blockhashes: &RecentBlockhashes,
@ -70,7 +37,7 @@ pub trait NonceAccount {
) -> Result<(), InstructionError>;
}
impl<'a> NonceAccount for KeyedAccount<'a> {
impl<'a> Account for KeyedAccount<'a> {
fn advance_nonce_account(
&self,
recent_blockhashes: &RecentBlockhashes,
@ -80,20 +47,26 @@ impl<'a> NonceAccount for KeyedAccount<'a> {
return Err(NonceError::NoRecentBlockhashes.into());
}
let meta = match self.state()? {
NonceState::Initialized(meta, ref hash) => {
if !signers.contains(&meta.nonce_authority) {
let state = AccountUtilsState::<Versions>::state(self)?.convert_to_current();
match state {
State::Initialized(data) => {
if !signers.contains(&data.authority) {
return Err(InstructionError::MissingRequiredSignature);
}
if *hash == recent_blockhashes[0] {
let recent_blockhash = recent_blockhashes[0].blockhash;
if data.blockhash == recent_blockhash {
return Err(NonceError::NotExpired.into());
}
meta
}
_ => return Err(NonceError::BadAccountState.into()),
};
self.set_state(&NonceState::Initialized(meta, recent_blockhashes[0]))
let new_data = nonce::state::Data {
blockhash: recent_blockhash,
fee_calculator: recent_blockhashes[0].fee_calculator.clone(),
..data
};
self.set_state(&Versions::new_current(State::Initialized(new_data)))
}
_ => Err(NonceError::BadAccountState.into()),
}
}
fn withdraw_nonce_account(
@ -104,16 +77,16 @@ impl<'a> NonceAccount for KeyedAccount<'a> {
rent: &Rent,
signers: &HashSet<Pubkey>,
) -> Result<(), InstructionError> {
let signer = match self.state()? {
NonceState::Uninitialized => {
let signer = match AccountUtilsState::<Versions>::state(self)?.convert_to_current() {
State::Uninitialized => {
if lamports > self.lamports()? {
return Err(InstructionError::InsufficientFunds);
}
*self.unsigned_key()
}
NonceState::Initialized(meta, ref hash) => {
State::Initialized(ref data) => {
if lamports == self.lamports()? {
if *hash == recent_blockhashes[0] {
if data.blockhash == recent_blockhashes[0].blockhash {
return Err(NonceError::NotExpired.into());
}
} else {
@ -122,7 +95,7 @@ impl<'a> NonceAccount for KeyedAccount<'a> {
return Err(InstructionError::InsufficientFunds);
}
}
meta.nonce_authority
data.authority
}
};
@ -146,18 +119,21 @@ impl<'a> NonceAccount for KeyedAccount<'a> {
return Err(NonceError::NoRecentBlockhashes.into());
}
let meta = match self.state()? {
NonceState::Uninitialized => {
match AccountUtilsState::<Versions>::state(self)?.convert_to_current() {
State::Uninitialized => {
let min_balance = rent.minimum_balance(self.data_len()?);
if self.lamports()? < min_balance {
return Err(InstructionError::InsufficientFunds);
}
Meta::new(nonce_authority)
let data = nonce::state::Data {
authority: *nonce_authority,
blockhash: recent_blockhashes[0].blockhash,
fee_calculator: recent_blockhashes[0].fee_calculator.clone(),
};
self.set_state(&Versions::new_current(State::Initialized(data)))
}
_ => return Err(NonceError::BadAccountState.into()),
};
self.set_state(&NonceState::Initialized(meta, recent_blockhashes[0]))
_ => Err(NonceError::BadAccountState.into()),
}
}
fn authorize_nonce_account(
@ -165,24 +141,28 @@ impl<'a> NonceAccount for KeyedAccount<'a> {
nonce_authority: &Pubkey,
signers: &HashSet<Pubkey>,
) -> Result<(), InstructionError> {
match self.state()? {
NonceState::Initialized(meta, nonce) => {
if !signers.contains(&meta.nonce_authority) {
match AccountUtilsState::<Versions>::state(self)?.convert_to_current() {
State::Initialized(data) => {
if !signers.contains(&data.authority) {
return Err(InstructionError::MissingRequiredSignature);
}
self.set_state(&NonceState::Initialized(Meta::new(nonce_authority), nonce))
let new_data = nonce::state::Data {
authority: *nonce_authority,
..data
};
self.set_state(&Versions::new_current(State::Initialized(new_data)))
}
_ => Err(NonceError::BadAccountState.into()),
}
}
}
pub fn create_account(lamports: u64) -> RefCell<Account> {
pub fn create_account(lamports: u64) -> RefCell<account::Account> {
RefCell::new(
Account::new_data_with_space(
account::Account::new_data_with_space(
lamports,
&NonceState::Uninitialized,
NonceState::size(),
&Versions::new_current(State::Uninitialized),
State::size(),
&system_program::id(),
)
.expect("nonce_account"),
@ -206,6 +186,8 @@ mod test {
use super::*;
use crate::{
account::KeyedAccount,
account_utils::State as AccountUtilsState,
nonce::{self, State},
system_instruction::NonceError,
sysvar::recent_blockhashes::{create_test_recent_blockhashes, RecentBlockhashes},
};
@ -213,13 +195,7 @@ mod test {
#[test]
fn default_is_uninitialized() {
assert_eq!(NonceState::default(), NonceState::Uninitialized)
}
#[test]
fn new_meta() {
let nonce_authority = Pubkey::default();
assert_eq!(Meta::new(&nonce_authority), Meta { nonce_authority });
assert_eq!(State::default(), State::Uninitialized)
}
#[test]
@ -228,39 +204,62 @@ mod test {
lamports_per_byte_year: 42,
..Rent::default()
};
let min_lamports = rent.minimum_balance(NonceState::size());
let min_lamports = rent.minimum_balance(State::size());
with_test_keyed_account(min_lamports + 42, true, |keyed_account| {
let meta = Meta::new(&keyed_account.unsigned_key());
let data = nonce::state::Data {
authority: *keyed_account.unsigned_key(),
..nonce::state::Data::default()
};
let mut signers = HashSet::new();
signers.insert(keyed_account.signer_key().unwrap().clone());
let state: NonceState = keyed_account.state().unwrap();
let state = AccountUtilsState::<Versions>::state(keyed_account)
.unwrap()
.convert_to_current();
// New is in Uninitialzed state
assert_eq!(state, NonceState::Uninitialized);
assert_eq!(state, State::Uninitialized);
let recent_blockhashes = create_test_recent_blockhashes(95);
let authorized = keyed_account.unsigned_key().clone();
keyed_account
.initialize_nonce_account(&authorized, &recent_blockhashes, &rent)
.unwrap();
let state: NonceState = keyed_account.state().unwrap();
let stored = recent_blockhashes[0];
let state = AccountUtilsState::<Versions>::state(keyed_account)
.unwrap()
.convert_to_current();
let data = nonce::state::Data {
blockhash: recent_blockhashes[0].blockhash,
fee_calculator: recent_blockhashes[0].fee_calculator.clone(),
..data.clone()
};
// First nonce instruction drives state from Uninitialized to Initialized
assert_eq!(state, NonceState::Initialized(meta, stored));
assert_eq!(state, State::Initialized(data.clone()));
let recent_blockhashes = create_test_recent_blockhashes(63);
keyed_account
.advance_nonce_account(&recent_blockhashes, &signers)
.unwrap();
let state: NonceState = keyed_account.state().unwrap();
let stored = recent_blockhashes[0];
let state = AccountUtilsState::<Versions>::state(keyed_account)
.unwrap()
.convert_to_current();
let data = nonce::state::Data {
blockhash: recent_blockhashes[0].blockhash,
fee_calculator: recent_blockhashes[0].fee_calculator.clone(),
..data.clone()
};
// Second nonce instruction consumes and replaces stored nonce
assert_eq!(state, NonceState::Initialized(meta, stored));
assert_eq!(state, State::Initialized(data.clone()));
let recent_blockhashes = create_test_recent_blockhashes(31);
keyed_account
.advance_nonce_account(&recent_blockhashes, &signers)
.unwrap();
let state: NonceState = keyed_account.state().unwrap();
let stored = recent_blockhashes[0];
let state = AccountUtilsState::<Versions>::state(keyed_account)
.unwrap()
.convert_to_current();
let data = nonce::state::Data {
blockhash: recent_blockhashes[0].blockhash,
fee_calculator: recent_blockhashes[0].fee_calculator.clone(),
..data.clone()
};
// Third nonce instruction for fun and profit
assert_eq!(state, NonceState::Initialized(meta, stored));
assert_eq!(state, State::Initialized(data.clone()));
with_test_keyed_account(42, false, |to_keyed| {
let recent_blockhashes = create_test_recent_blockhashes(0);
let withdraw_lamports = keyed_account.account.borrow().lamports;
@ -276,12 +275,12 @@ mod test {
&signers,
)
.unwrap();
// Empties NonceAccount balance
// Empties Account balance
assert_eq!(
keyed_account.account.borrow().lamports,
expect_nonce_lamports
);
// NonceAccount balance goes to `to`
// Account balance goes to `to`
assert_eq!(to_keyed.account.borrow().lamports, expect_to_lamports);
})
})
@ -293,19 +292,24 @@ mod test {
lamports_per_byte_year: 42,
..Rent::default()
};
let min_lamports = rent.minimum_balance(NonceState::size());
let min_lamports = rent.minimum_balance(State::size());
with_test_keyed_account(min_lamports + 42, true, |nonce_account| {
let recent_blockhashes = create_test_recent_blockhashes(31);
let stored = recent_blockhashes[0];
let authorized = nonce_account.unsigned_key().clone();
let meta = Meta::new(&authorized);
let authority = nonce_account.unsigned_key().clone();
nonce_account
.initialize_nonce_account(&authorized, &recent_blockhashes, &rent)
.initialize_nonce_account(&authority, &recent_blockhashes, &rent)
.unwrap();
let pubkey = nonce_account.account.borrow().owner.clone();
let nonce_account = KeyedAccount::new(&pubkey, false, nonce_account.account);
let state: NonceState = nonce_account.state().unwrap();
assert_eq!(state, NonceState::Initialized(meta, stored));
let state = AccountUtilsState::<Versions>::state(&nonce_account)
.unwrap()
.convert_to_current();
let data = nonce::state::Data {
authority,
blockhash: recent_blockhashes[0].blockhash,
fee_calculator: recent_blockhashes[0].fee_calculator.clone(),
};
assert_eq!(state, State::Initialized(data));
let signers = HashSet::new();
let recent_blockhashes = create_test_recent_blockhashes(0);
let result = nonce_account.advance_nonce_account(&recent_blockhashes, &signers);
@ -319,7 +323,7 @@ mod test {
lamports_per_byte_year: 42,
..Rent::default()
};
let min_lamports = rent.minimum_balance(NonceState::size());
let min_lamports = rent.minimum_balance(State::size());
with_test_keyed_account(min_lamports + 42, true, |keyed_account| {
let mut signers = HashSet::new();
signers.insert(keyed_account.signer_key().unwrap().clone());
@ -340,7 +344,7 @@ mod test {
lamports_per_byte_year: 42,
..Rent::default()
};
let min_lamports = rent.minimum_balance(NonceState::size());
let min_lamports = rent.minimum_balance(State::size());
with_test_keyed_account(min_lamports + 42, true, |keyed_account| {
let mut signers = HashSet::new();
signers.insert(keyed_account.signer_key().unwrap().clone());
@ -360,7 +364,7 @@ mod test {
lamports_per_byte_year: 42,
..Rent::default()
};
let min_lamports = rent.minimum_balance(NonceState::size());
let min_lamports = rent.minimum_balance(State::size());
with_test_keyed_account(min_lamports + 42, true, |keyed_account| {
let mut signers = HashSet::new();
signers.insert(keyed_account.signer_key().unwrap().clone());
@ -376,7 +380,7 @@ mod test {
lamports_per_byte_year: 42,
..Rent::default()
};
let min_lamports = rent.minimum_balance(NonceState::size());
let min_lamports = rent.minimum_balance(State::size());
with_test_keyed_account(min_lamports + 42, true, |nonce_account| {
with_test_keyed_account(42, true, |nonce_authority| {
let mut signers = HashSet::new();
@ -401,7 +405,7 @@ mod test {
lamports_per_byte_year: 42,
..Rent::default()
};
let min_lamports = rent.minimum_balance(NonceState::size());
let min_lamports = rent.minimum_balance(State::size());
with_test_keyed_account(min_lamports + 42, true, |nonce_account| {
with_test_keyed_account(42, false, |nonce_authority| {
let mut signers = HashSet::new();
@ -423,10 +427,12 @@ mod test {
lamports_per_byte_year: 42,
..Rent::default()
};
let min_lamports = rent.minimum_balance(NonceState::size());
let min_lamports = rent.minimum_balance(State::size());
with_test_keyed_account(min_lamports + 42, true, |nonce_keyed| {
let state: NonceState = nonce_keyed.state().unwrap();
assert_eq!(state, NonceState::Uninitialized);
let state = AccountUtilsState::<Versions>::state(nonce_keyed)
.unwrap()
.convert_to_current();
assert_eq!(state, State::Uninitialized);
with_test_keyed_account(42, false, |to_keyed| {
let mut signers = HashSet::new();
signers.insert(nonce_keyed.signer_key().unwrap().clone());
@ -444,13 +450,15 @@ mod test {
&signers,
)
.unwrap();
let state: NonceState = nonce_keyed.state().unwrap();
let state = AccountUtilsState::<Versions>::state(nonce_keyed)
.unwrap()
.convert_to_current();
// Withdraw instruction...
// Deinitializes NonceAccount state
assert_eq!(state, NonceState::Uninitialized);
// Empties NonceAccount balance
// Deinitializes Account state
assert_eq!(state, State::Uninitialized);
// Empties Account balance
assert_eq!(nonce_keyed.account.borrow().lamports, expect_nonce_lamports);
// NonceAccount balance goes to `to`
// Account balance goes to `to`
assert_eq!(to_keyed.account.borrow().lamports, expect_to_lamports);
})
})
@ -462,10 +470,12 @@ mod test {
lamports_per_byte_year: 42,
..Rent::default()
};
let min_lamports = rent.minimum_balance(NonceState::size());
let min_lamports = rent.minimum_balance(State::size());
with_test_keyed_account(min_lamports + 42, false, |nonce_keyed| {
let state: NonceState = nonce_keyed.state().unwrap();
assert_eq!(state, NonceState::Uninitialized);
let state = AccountUtilsState::<Versions>::state(nonce_keyed)
.unwrap()
.convert_to_current();
assert_eq!(state, State::Uninitialized);
with_test_keyed_account(42, false, |to_keyed| {
let signers = HashSet::new();
let recent_blockhashes = create_test_recent_blockhashes(0);
@ -488,10 +498,12 @@ mod test {
lamports_per_byte_year: 42,
..Rent::default()
};
let min_lamports = rent.minimum_balance(NonceState::size());
let min_lamports = rent.minimum_balance(State::size());
with_test_keyed_account(min_lamports + 42, true, |nonce_keyed| {
let state: NonceState = nonce_keyed.state().unwrap();
assert_eq!(state, NonceState::Uninitialized);
let state = AccountUtilsState::<Versions>::state(nonce_keyed)
.unwrap()
.convert_to_current();
assert_eq!(state, State::Uninitialized);
with_test_keyed_account(42, false, |to_keyed| {
let mut signers = HashSet::new();
signers.insert(nonce_keyed.signer_key().unwrap().clone());
@ -515,7 +527,7 @@ mod test {
lamports_per_byte_year: 42,
..Rent::default()
};
let min_lamports = rent.minimum_balance(NonceState::size());
let min_lamports = rent.minimum_balance(State::size());
with_test_keyed_account(min_lamports + 42, true, |nonce_keyed| {
with_test_keyed_account(42, false, |to_keyed| {
let mut signers = HashSet::new();
@ -534,8 +546,10 @@ mod test {
&signers,
)
.unwrap();
let state: NonceState = nonce_keyed.state().unwrap();
assert_eq!(state, NonceState::Uninitialized);
let state = AccountUtilsState::<Versions>::state(nonce_keyed)
.unwrap()
.convert_to_current();
assert_eq!(state, State::Uninitialized);
assert_eq!(nonce_keyed.account.borrow().lamports, nonce_expect_lamports);
assert_eq!(to_keyed.account.borrow().lamports, to_expect_lamports);
let withdraw_lamports = nonce_keyed.account.borrow().lamports;
@ -551,8 +565,10 @@ mod test {
&signers,
)
.unwrap();
let state: NonceState = nonce_keyed.state().unwrap();
assert_eq!(state, NonceState::Uninitialized);
let state = AccountUtilsState::<Versions>::state(nonce_keyed)
.unwrap()
.convert_to_current();
assert_eq!(state, State::Uninitialized);
assert_eq!(nonce_keyed.account.borrow().lamports, nonce_expect_lamports);
assert_eq!(to_keyed.account.borrow().lamports, to_expect_lamports);
})
@ -565,19 +581,24 @@ mod test {
lamports_per_byte_year: 42,
..Rent::default()
};
let min_lamports = rent.minimum_balance(NonceState::size());
let min_lamports = rent.minimum_balance(State::size());
with_test_keyed_account(min_lamports + 42, true, |nonce_keyed| {
let mut signers = HashSet::new();
signers.insert(nonce_keyed.signer_key().unwrap().clone());
let recent_blockhashes = create_test_recent_blockhashes(31);
let authorized = nonce_keyed.unsigned_key().clone();
let meta = Meta::new(&authorized);
let authority = nonce_keyed.unsigned_key().clone();
nonce_keyed
.initialize_nonce_account(&authorized, &recent_blockhashes, &rent)
.initialize_nonce_account(&authority, &recent_blockhashes, &rent)
.unwrap();
let state: NonceState = nonce_keyed.state().unwrap();
let stored = recent_blockhashes[0];
assert_eq!(state, NonceState::Initialized(meta, stored));
let state = AccountUtilsState::<Versions>::state(nonce_keyed)
.unwrap()
.convert_to_current();
let data = nonce::state::Data {
authority,
blockhash: recent_blockhashes[0].blockhash,
fee_calculator: recent_blockhashes[0].fee_calculator.clone(),
};
assert_eq!(state, State::Initialized(data.clone()));
with_test_keyed_account(42, false, |to_keyed| {
let withdraw_lamports = nonce_keyed.account.borrow().lamports - min_lamports;
let nonce_expect_lamports =
@ -592,9 +613,15 @@ mod test {
&signers,
)
.unwrap();
let state: NonceState = nonce_keyed.state().unwrap();
let stored = recent_blockhashes[0];
assert_eq!(state, NonceState::Initialized(meta, stored));
let state = AccountUtilsState::<Versions>::state(nonce_keyed)
.unwrap()
.convert_to_current();
let data = nonce::state::Data {
blockhash: recent_blockhashes[0].blockhash,
fee_calculator: recent_blockhashes[0].fee_calculator.clone(),
..data.clone()
};
assert_eq!(state, State::Initialized(data));
assert_eq!(nonce_keyed.account.borrow().lamports, nonce_expect_lamports);
assert_eq!(to_keyed.account.borrow().lamports, to_expect_lamports);
let recent_blockhashes = create_test_recent_blockhashes(0);
@ -623,7 +650,7 @@ mod test {
lamports_per_byte_year: 42,
..Rent::default()
};
let min_lamports = rent.minimum_balance(NonceState::size());
let min_lamports = rent.minimum_balance(State::size());
with_test_keyed_account(min_lamports + 42, true, |nonce_keyed| {
let recent_blockhashes = create_test_recent_blockhashes(0);
let authorized = nonce_keyed.unsigned_key().clone();
@ -652,7 +679,7 @@ mod test {
lamports_per_byte_year: 42,
..Rent::default()
};
let min_lamports = rent.minimum_balance(NonceState::size());
let min_lamports = rent.minimum_balance(State::size());
with_test_keyed_account(min_lamports + 42, true, |nonce_keyed| {
let recent_blockhashes = create_test_recent_blockhashes(95);
let authorized = nonce_keyed.unsigned_key().clone();
@ -682,7 +709,7 @@ mod test {
lamports_per_byte_year: 42,
..Rent::default()
};
let min_lamports = rent.minimum_balance(NonceState::size());
let min_lamports = rent.minimum_balance(State::size());
with_test_keyed_account(min_lamports + 42, true, |nonce_keyed| {
let recent_blockhashes = create_test_recent_blockhashes(95);
let authorized = nonce_keyed.unsigned_key().clone();
@ -712,21 +739,28 @@ mod test {
lamports_per_byte_year: 42,
..Rent::default()
};
let min_lamports = rent.minimum_balance(NonceState::size());
let min_lamports = rent.minimum_balance(State::size());
with_test_keyed_account(min_lamports + 42, true, |keyed_account| {
let state: NonceState = keyed_account.state().unwrap();
assert_eq!(state, NonceState::Uninitialized);
let state = AccountUtilsState::<Versions>::state(keyed_account)
.unwrap()
.convert_to_current();
assert_eq!(state, State::Uninitialized);
let mut signers = HashSet::new();
signers.insert(keyed_account.signer_key().unwrap().clone());
let recent_blockhashes = create_test_recent_blockhashes(0);
let stored = recent_blockhashes[0];
let authorized = keyed_account.unsigned_key().clone();
let meta = Meta::new(&authorized);
let authority = keyed_account.unsigned_key().clone();
let result =
keyed_account.initialize_nonce_account(&authorized, &recent_blockhashes, &rent);
keyed_account.initialize_nonce_account(&authority, &recent_blockhashes, &rent);
let data = nonce::state::Data {
authority,
blockhash: recent_blockhashes[0].blockhash,
fee_calculator: recent_blockhashes[0].fee_calculator.clone(),
};
assert_eq!(result, Ok(()));
let state: NonceState = keyed_account.state().unwrap();
assert_eq!(state, NonceState::Initialized(meta, stored));
let state = AccountUtilsState::<Versions>::state(keyed_account)
.unwrap()
.convert_to_current();
assert_eq!(state, State::Initialized(data));
})
}
@ -736,7 +770,7 @@ mod test {
lamports_per_byte_year: 42,
..Rent::default()
};
let min_lamports = rent.minimum_balance(NonceState::size());
let min_lamports = rent.minimum_balance(State::size());
with_test_keyed_account(min_lamports + 42, true, |keyed_account| {
let mut signers = HashSet::new();
signers.insert(keyed_account.signer_key().unwrap().clone());
@ -754,7 +788,7 @@ mod test {
lamports_per_byte_year: 42,
..Rent::default()
};
let min_lamports = rent.minimum_balance(NonceState::size());
let min_lamports = rent.minimum_balance(State::size());
with_test_keyed_account(min_lamports + 42, true, |keyed_account| {
let recent_blockhashes = create_test_recent_blockhashes(31);
let authorized = keyed_account.unsigned_key().clone();
@ -774,7 +808,7 @@ mod test {
lamports_per_byte_year: 42,
..Rent::default()
};
let min_lamports = rent.minimum_balance(NonceState::size());
let min_lamports = rent.minimum_balance(State::size());
with_test_keyed_account(min_lamports - 42, true, |keyed_account| {
let recent_blockhashes = create_test_recent_blockhashes(63);
let authorized = keyed_account.unsigned_key().clone();
@ -790,22 +824,27 @@ mod test {
lamports_per_byte_year: 42,
..Rent::default()
};
let min_lamports = rent.minimum_balance(NonceState::size());
let min_lamports = rent.minimum_balance(State::size());
with_test_keyed_account(min_lamports + 42, true, |nonce_account| {
let mut signers = HashSet::new();
signers.insert(nonce_account.signer_key().unwrap().clone());
let recent_blockhashes = create_test_recent_blockhashes(31);
let stored = recent_blockhashes[0];
let authorized = nonce_account.unsigned_key().clone();
nonce_account
.initialize_nonce_account(&authorized, &recent_blockhashes, &rent)
.unwrap();
let authorized = &Pubkey::default().clone();
let meta = Meta::new(&authorized);
let authority = Pubkey::default();
let data = nonce::state::Data {
authority,
blockhash: recent_blockhashes[0].blockhash,
fee_calculator: recent_blockhashes[0].fee_calculator.clone(),
};
let result = nonce_account.authorize_nonce_account(&Pubkey::default(), &signers);
assert_eq!(result, Ok(()));
let state: NonceState = nonce_account.state().unwrap();
assert_eq!(state, NonceState::Initialized(meta, stored));
let state = AccountUtilsState::<Versions>::state(nonce_account)
.unwrap()
.convert_to_current();
assert_eq!(state, State::Initialized(data));
})
}
@ -815,7 +854,7 @@ mod test {
lamports_per_byte_year: 42,
..Rent::default()
};
let min_lamports = rent.minimum_balance(NonceState::size());
let min_lamports = rent.minimum_balance(State::size());
with_test_keyed_account(min_lamports + 42, true, |nonce_account| {
let mut signers = HashSet::new();
signers.insert(nonce_account.signer_key().unwrap().clone());
@ -830,7 +869,7 @@ mod test {
lamports_per_byte_year: 42,
..Rent::default()
};
let min_lamports = rent.minimum_balance(NonceState::size());
let min_lamports = rent.minimum_balance(State::size());
with_test_keyed_account(min_lamports + 42, true, |nonce_account| {
let mut signers = HashSet::new();
signers.insert(nonce_account.signer_key().unwrap().clone());

4
sdk/src/nonce/mod.rs Normal file
View File

@ -0,0 +1,4 @@
pub mod account;
pub use account::{create_account, Account};
pub mod state;
pub use state::State;

View File

@ -0,0 +1,39 @@
use super::Versions;
use crate::{fee_calculator::FeeCalculator, hash::Hash, pubkey::Pubkey};
use serde_derive::{Deserialize, Serialize};
#[derive(Debug, Default, Serialize, Deserialize, PartialEq, Clone)]
pub struct Data {
pub authority: Pubkey,
pub blockhash: Hash,
pub fee_calculator: FeeCalculator,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
pub enum State {
Uninitialized,
Initialized(Data),
}
impl Default for State {
fn default() -> Self {
State::Uninitialized
}
}
impl State {
pub fn size() -> usize {
let data = Versions::new_current(State::Initialized(Data::default()));
bincode::serialized_size(&data).unwrap() as usize
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn default_is_uninitialized() {
assert_eq!(State::default(), State::Uninitialized)
}
}

View File

@ -0,0 +1,21 @@
mod current;
pub use current::{Data, State};
use serde_derive::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
pub enum Versions {
Current(Box<State>),
}
impl Versions {
pub fn new_current(state: State) -> Self {
Self::Current(Box::new(state))
}
pub fn convert_to_current(self) -> State {
match self {
Self::Current(state) => *state,
}
}
}

View File

@ -1,7 +1,7 @@
use crate::{
hash::hashv,
instruction::{AccountMeta, Instruction, WithSigner},
nonce_state::NonceState,
nonce,
program_utils::DecodeError,
pubkey::Pubkey,
system_program,
@ -322,7 +322,7 @@ pub fn create_nonce_account_with_seed(
base,
seed,
lamports,
NonceState::size() as u64,
nonce::State::size() as u64,
&system_program::id(),
),
Instruction::new(
@ -348,7 +348,7 @@ pub fn create_nonce_account(
from_pubkey,
nonce_pubkey,
lamports,
NonceState::size() as u64,
nonce::State::size() as u64,
&system_program::id(),
),
Instruction::new(

View File

@ -1,21 +1,61 @@
use crate::{
account::Account,
declare_sysvar_id,
fee_calculator::FeeCalculator,
hash::{hash, Hash},
sysvar::Sysvar,
};
use bincode::serialize;
use std::{collections::BinaryHeap, iter::FromIterator, ops::Deref};
use std::{cmp::Ordering, collections::BinaryHeap, iter::FromIterator, ops::Deref};
const MAX_ENTRIES: usize = 32;
crate::declare_sysvar_id!(
declare_sysvar_id!(
"SysvarRecentB1ockHashes11111111111111111111",
RecentBlockhashes
);
#[repr(C)]
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct RecentBlockhashes(Vec<Hash>);
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
pub struct Entry {
pub blockhash: Hash,
pub fee_calculator: FeeCalculator,
}
impl Entry {
pub fn new(blockhash: &Hash, fee_calculator: &FeeCalculator) -> Self {
Self {
blockhash: *blockhash,
fee_calculator: fee_calculator.clone(),
}
}
}
#[derive(Clone, Debug)]
pub struct IterItem<'a>(pub u64, pub &'a Hash, pub &'a FeeCalculator);
impl<'a> Eq for IterItem<'a> {}
impl<'a> PartialEq for IterItem<'a> {
fn eq(&self, other: &Self) -> bool {
self.0 == other.0
}
}
impl<'a> Ord for IterItem<'a> {
fn cmp(&self, other: &Self) -> Ordering {
self.0.cmp(&other.0)
}
}
impl<'a> PartialOrd for IterItem<'a> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
#[repr(C)]
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct RecentBlockhashes(Vec<Entry>);
impl Default for RecentBlockhashes {
fn default() -> Self {
@ -23,14 +63,14 @@ impl Default for RecentBlockhashes {
}
}
impl<'a> FromIterator<&'a Hash> for RecentBlockhashes {
impl<'a> FromIterator<IterItem<'a>> for RecentBlockhashes {
fn from_iter<I>(iter: I) -> Self
where
I: IntoIterator<Item = &'a Hash>,
I: IntoIterator<Item = IterItem<'a>>,
{
let mut new = Self::default();
for i in iter {
new.0.push(*i)
new.0.push(Entry::new(i.1, i.2))
}
new
}
@ -67,12 +107,12 @@ impl<T: Ord> Iterator for IntoIterSorted<T> {
impl Sysvar for RecentBlockhashes {
fn size_of() -> usize {
// hard-coded so that we don't have to construct an empty
1032 // golden, update if MAX_ENTRIES changes
1288 // golden, update if MAX_ENTRIES changes
}
}
impl Deref for RecentBlockhashes {
type Target = Vec<Hash>;
type Target = Vec<Entry>;
fn deref(&self) -> &Self::Target {
&self.0
}
@ -84,18 +124,18 @@ pub fn create_account(lamports: u64) -> Account {
pub fn update_account<'a, I>(account: &mut Account, recent_blockhash_iter: I) -> Option<()>
where
I: IntoIterator<Item = (u64, &'a Hash)>,
I: IntoIterator<Item = IterItem<'a>>,
{
let sorted = BinaryHeap::from_iter(recent_blockhash_iter);
let sorted_iter = IntoIterSorted { inner: sorted };
let recent_blockhash_iter = sorted_iter.take(MAX_ENTRIES).map(|(_, hash)| hash);
let recent_blockhash_iter = sorted_iter.take(MAX_ENTRIES);
let recent_blockhashes = RecentBlockhashes::from_iter(recent_blockhash_iter);
recent_blockhashes.to_account(account)
}
pub fn create_account_with_data<'a, I>(lamports: u64, recent_blockhash_iter: I) -> Account
where
I: IntoIterator<Item = (u64, &'a Hash)>,
I: IntoIterator<Item = IterItem<'a>>,
{
let mut account = create_account(lamports);
update_account(&mut account, recent_blockhash_iter).unwrap();
@ -103,10 +143,20 @@ where
}
pub fn create_test_recent_blockhashes(start: usize) -> RecentBlockhashes {
let bhq: Vec<_> = (start..start + (MAX_ENTRIES - 1))
.map(|i| hash(&serialize(&i).unwrap()))
let blocks: Vec<_> = (start..start + MAX_ENTRIES)
.map(|i| {
(
i as u64,
hash(&bincode::serialize(&i).unwrap()),
FeeCalculator::new(i as u64 * 100),
)
})
.collect();
RecentBlockhashes::from_iter(bhq.iter())
let bhq: Vec<_> = blocks
.iter()
.map(|(i, hash, fee_calc)| IterItem(*i, hash, fee_calc))
.collect();
RecentBlockhashes::from_iter(bhq.into_iter())
}
#[cfg(test)]
@ -118,9 +168,10 @@ mod tests {
#[test]
fn test_size_of() {
let entry = Entry::new(&Hash::default(), &FeeCalculator::default());
assert_eq!(
bincode::serialized_size(&RecentBlockhashes(vec![Hash::default(); MAX_ENTRIES]))
.unwrap() as usize,
bincode::serialized_size(&RecentBlockhashes(vec![entry; MAX_ENTRIES])).unwrap()
as usize,
RecentBlockhashes::size_of()
);
}
@ -135,8 +186,11 @@ mod tests {
#[test]
fn test_create_account_full() {
let def_hash = Hash::default();
let account =
create_account_with_data(42, vec![(0u64, &def_hash); MAX_ENTRIES].into_iter());
let def_fees = FeeCalculator::default();
let account = create_account_with_data(
42,
vec![IterItem(0u64, &def_hash, &def_fees); MAX_ENTRIES].into_iter(),
);
let recent_blockhashes = RecentBlockhashes::from_account(&account).unwrap();
assert_eq!(recent_blockhashes.len(), MAX_ENTRIES);
}
@ -144,15 +198,19 @@ mod tests {
#[test]
fn test_create_account_truncate() {
let def_hash = Hash::default();
let account =
create_account_with_data(42, vec![(0u64, &def_hash); MAX_ENTRIES + 1].into_iter());
let def_fees = FeeCalculator::default();
let account = create_account_with_data(
42,
vec![IterItem(0u64, &def_hash, &def_fees); MAX_ENTRIES + 1].into_iter(),
);
let recent_blockhashes = RecentBlockhashes::from_account(&account).unwrap();
assert_eq!(recent_blockhashes.len(), MAX_ENTRIES);
}
#[test]
fn test_create_account_unsorted() {
let mut unsorted_recent_blockhashes: Vec<_> = (0..MAX_ENTRIES)
let def_fees = FeeCalculator::default();
let mut unsorted_blocks: Vec<_> = (0..MAX_ENTRIES)
.map(|i| {
(i as u64, {
// create hash with visibly recognizable ordering
@ -162,20 +220,26 @@ mod tests {
})
})
.collect();
unsorted_recent_blockhashes.shuffle(&mut thread_rng());
unsorted_blocks.shuffle(&mut thread_rng());
let account = create_account_with_data(
42,
unsorted_recent_blockhashes
unsorted_blocks
.iter()
.map(|(i, hash)| (*i, hash)),
.map(|(i, hash)| IterItem(*i, hash, &def_fees)),
);
let recent_blockhashes = RecentBlockhashes::from_account(&account).unwrap();
let mut expected_recent_blockhashes: Vec<_> =
(unsorted_recent_blockhashes.into_iter().map(|(_, b)| b)).collect();
expected_recent_blockhashes.sort();
expected_recent_blockhashes.reverse();
let mut unsorted_recent_blockhashes: Vec<_> = unsorted_blocks
.iter()
.map(|(i, hash)| IterItem(*i, hash, &def_fees))
.collect();
unsorted_recent_blockhashes.sort();
unsorted_recent_blockhashes.reverse();
let expected_recent_blockhashes: Vec<_> = (unsorted_recent_blockhashes
.into_iter()
.map(|IterItem(_, b, f)| Entry::new(b, f)))
.collect();
assert_eq!(*recent_blockhashes, expected_recent_blockhashes);
}