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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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