Consolidate Nonce state under one struct (#8624)

automerge
This commit is contained in:
Trent Nelson 2020-03-04 09:51:48 -07:00 committed by GitHub
parent 8f60f1093a
commit 1cc7131bb7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 180 additions and 163 deletions

View File

@ -3261,10 +3261,11 @@ mod tests {
// Nonced pay // Nonced pay
let blockhash = Hash::default(); let blockhash = Hash::default();
let data = nonce::state::Versions::new_current(nonce::State::Initialized( let data =
nonce::state::Meta::new(&config.signers[0].pubkey()), nonce::state::Versions::new_current(nonce::State::Initialized(nonce::state::Data {
blockhash, authority: config.signers[0].pubkey(),
)); blockhash,
}));
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(
@ -3288,10 +3289,11 @@ 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( let data =
nonce::state::Meta::new(&bob_pubkey), nonce::state::Versions::new_current(nonce::State::Initialized(nonce::state::Data {
blockhash, authority: bob_pubkey,
)); blockhash,
}));
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(

View File

@ -367,10 +367,10 @@ pub fn check_nonce_account(
.map(|v| v.convert_to_current()) .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 {
State::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(())
@ -496,7 +496,7 @@ pub fn process_get_nonce(rpc_client: &RpcClient, nonce_account_pubkey: &Pubkey)
let nonce_state = StateMut::<Versions>::state(&nonce_account).map(|v| v.convert_to_current()); let nonce_state = StateMut::<Versions>::state(&nonce_account).map(|v| v.convert_to_current());
match nonce_state { match nonce_state {
Ok(State::Uninitialized) => Ok("Nonce account is uninitialized".to_string()), Ok(State::Uninitialized) => Ok("Nonce account is uninitialized".to_string()),
Ok(State::Initialized(_, hash)) => Ok(format!("{:?}", hash)), 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
@ -553,7 +553,7 @@ pub fn process_show_nonce_account(
)) ))
.into()); .into());
} }
let print_account = |data: Option<(nonce::state::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)
@ -567,9 +567,9 @@ pub fn process_show_nonce_account(
) )
); );
match data { match data {
Some((meta, hash)) => { Some(ref data) => {
println!("Nonce: {}", hash); println!("Nonce: {}", data.blockhash);
println!("Authority: {}", meta.nonce_authority); println!("Authority: {}", data.authority);
} }
None => { None => {
println!("Nonce: uninitialized"); println!("Nonce: uninitialized");
@ -581,7 +581,7 @@ pub fn process_show_nonce_account(
let nonce_state = StateMut::<Versions>::state(&nonce_account).map(|v| v.convert_to_current()); let nonce_state = StateMut::<Versions>::state(&nonce_account).map(|v| v.convert_to_current());
match nonce_state { match nonce_state {
Ok(State::Uninitialized) => print_account(None), Ok(State::Uninitialized) => print_account(None),
Ok(State::Initialized(meta, hash)) => print_account(Some((meta, hash))), 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
@ -903,10 +903,10 @@ 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 data = Versions::new_current(State::Initialized( let data = Versions::new_current(State::Initialized(nonce::state::Data {
nonce::state::Meta::new(&nonce_pubkey), authority: nonce_pubkey,
blockhash, blockhash,
)); }));
let valid = Account::new_data(1, &data, &system_program::ID); 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());
@ -926,20 +926,20 @@ mod tests {
))), ))),
); );
let data = Versions::new_current(State::Initialized( let data = Versions::new_current(State::Initialized(nonce::state::Data {
nonce::state::Meta::new(&nonce_pubkey), authority: nonce_pubkey,
hash(b"invalid"), blockhash: hash(b"invalid"),
)); }));
let invalid_hash = Account::new_data(1, &data, &system_program::ID); 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 data = Versions::new_current(State::Initialized( let data = Versions::new_current(State::Initialized(nonce::state::Data {
nonce::state::Meta::new(&Pubkey::new_rand()), authority: Pubkey::new_rand(),
blockhash, blockhash,
)); }));
let invalid_authority = Account::new_data(1, &data, &system_program::ID); 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),

View File

@ -413,7 +413,7 @@ fn test_nonced_pay_tx() {
.unwrap() .unwrap()
.convert_to_current(); .convert_to_current();
let nonce_hash = match nonce_state { let nonce_hash = match nonce_state {
nonce::State::Initialized(_meta, hash) => hash, nonce::State::Initialized(ref data) => data.blockhash,
_ => panic!("Nonce is not initialized"), _ => panic!("Nonce is not initialized"),
}; };
@ -437,7 +437,7 @@ fn test_nonced_pay_tx() {
.unwrap() .unwrap()
.convert_to_current(); .convert_to_current();
match nonce_state { match nonce_state {
nonce::State::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

@ -504,7 +504,7 @@ fn test_nonced_stake_delegation_and_deactivation() {
.unwrap() .unwrap()
.convert_to_current(); .convert_to_current();
let nonce_hash = match nonce_state { let nonce_hash = match nonce_state {
nonce::State::Initialized(_meta, hash) => hash, nonce::State::Initialized(ref data) => data.blockhash,
_ => panic!("Nonce is not initialized"), _ => panic!("Nonce is not initialized"),
}; };
@ -529,7 +529,7 @@ fn test_nonced_stake_delegation_and_deactivation() {
.unwrap() .unwrap()
.convert_to_current(); .convert_to_current();
let nonce_hash = match nonce_state { let nonce_hash = match nonce_state {
nonce::State::Initialized(_meta, hash) => hash, nonce::State::Initialized(ref data) => data.blockhash,
_ => panic!("Nonce is not initialized"), _ => panic!("Nonce is not initialized"),
}; };
@ -722,7 +722,7 @@ fn test_stake_authorize() {
.unwrap() .unwrap()
.convert_to_current(); .convert_to_current();
let nonce_hash = match nonce_state { let nonce_hash = match nonce_state {
nonce::State::Initialized(_meta, hash) => hash, nonce::State::Initialized(ref data) => data.blockhash,
_ => panic!("Nonce is not initialized"), _ => panic!("Nonce is not initialized"),
}; };
@ -773,7 +773,7 @@ fn test_stake_authorize() {
.unwrap() .unwrap()
.convert_to_current(); .convert_to_current();
let new_nonce_hash = match nonce_state { let new_nonce_hash = match nonce_state {
nonce::State::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);
@ -1009,7 +1009,7 @@ fn test_stake_split() {
.unwrap() .unwrap()
.convert_to_current(); .convert_to_current();
let nonce_hash = match nonce_state { let nonce_hash = match nonce_state {
nonce::State::Initialized(_meta, hash) => hash, nonce::State::Initialized(ref data) => data.blockhash,
_ => panic!("Nonce is not initialized"), _ => panic!("Nonce is not initialized"),
}; };
@ -1262,7 +1262,7 @@ fn test_stake_set_lockup() {
.unwrap() .unwrap()
.convert_to_current(); .convert_to_current();
let nonce_hash = match nonce_state { let nonce_hash = match nonce_state {
nonce::State::Initialized(_meta, hash) => hash, nonce::State::Initialized(ref data) => data.blockhash,
_ => panic!("Nonce is not initialized"), _ => panic!("Nonce is not initialized"),
}; };
@ -1378,7 +1378,7 @@ fn test_offline_nonced_create_stake_account_and_withdraw() {
.unwrap() .unwrap()
.convert_to_current(); .convert_to_current();
let nonce_hash = match nonce_state { let nonce_hash = match nonce_state {
nonce::State::Initialized(_meta, hash) => hash, nonce::State::Initialized(ref data) => data.blockhash,
_ => panic!("Nonce is not initialized"), _ => panic!("Nonce is not initialized"),
}; };
@ -1428,7 +1428,7 @@ fn test_offline_nonced_create_stake_account_and_withdraw() {
.unwrap() .unwrap()
.convert_to_current(); .convert_to_current();
let nonce_hash = match nonce_state { let nonce_hash = match nonce_state {
nonce::State::Initialized(_meta, hash) => hash, nonce::State::Initialized(ref data) => data.blockhash,
_ => panic!("Nonce is not initialized"), _ => panic!("Nonce is not initialized"),
}; };
@ -1471,7 +1471,7 @@ fn test_offline_nonced_create_stake_account_and_withdraw() {
.unwrap() .unwrap()
.convert_to_current(); .convert_to_current();
let nonce_hash = match nonce_state { let nonce_hash = match nonce_state {
nonce::State::Initialized(_meta, hash) => hash, nonce::State::Initialized(ref data) => data.blockhash,
_ => panic!("Nonce is not initialized"), _ => panic!("Nonce is not initialized"),
}; };

View File

@ -138,7 +138,7 @@ fn test_transfer() {
.unwrap() .unwrap()
.convert_to_current(); .convert_to_current();
let nonce_hash = match nonce_state { let nonce_hash = match nonce_state {
nonce::State::Initialized(_meta, hash) => hash, nonce::State::Initialized(ref data) => data.blockhash,
_ => panic!("Nonce is not initialized"), _ => panic!("Nonce is not initialized"),
}; };
@ -162,7 +162,7 @@ fn test_transfer() {
.unwrap() .unwrap()
.convert_to_current(); .convert_to_current();
let new_nonce_hash = match nonce_state { let new_nonce_hash = match nonce_state {
nonce::State::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);
@ -183,7 +183,7 @@ fn test_transfer() {
.unwrap() .unwrap()
.convert_to_current(); .convert_to_current();
let nonce_hash = match nonce_state { let nonce_hash = match nonce_state {
nonce::State::Initialized(_meta, hash) => hash, nonce::State::Initialized(ref data) => data.blockhash,
_ => panic!("Nonce is not initialized"), _ => panic!("Nonce is not initialized"),
}; };

View File

@ -921,10 +921,10 @@ mod tests {
nonce.pubkey(), nonce.pubkey(),
Account::new_data( Account::new_data(
min_balance * 2, min_balance * 2,
&nonce::State::Initialized( &nonce::State::Initialized(nonce::state::Data {
nonce::state::Meta::new(&Pubkey::default()), authority: Pubkey::default(),
Hash::default(), blockhash: Hash::default(),
), }),
&system_program::id(), &system_program::id(),
) )
.unwrap(), .unwrap(),

View File

@ -3417,10 +3417,10 @@ mod tests {
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::Initialized( &nonce::State::Initialized(nonce::state::Data {
nonce::state::Meta::new(&Pubkey::default()), authority: Pubkey::default(),
Hash::default(), blockhash: Hash::default(),
), }),
&system_program::id(), &system_program::id(),
) )
.unwrap(); .unwrap();
@ -5101,7 +5101,7 @@ mod tests {
let state = let state =
StateMut::<nonce::state::Versions>::state(&acc).map(|v| v.convert_to_current()); StateMut::<nonce::state::Versions>::state(&acc).map(|v| v.convert_to_current());
match state { match state {
Ok(nonce::State::Initialized(_meta, hash)) => Some(hash), Ok(nonce::State::Initialized(ref data)) => Some(data.blockhash),
_ => None, _ => None,
} }
}) })
@ -5276,10 +5276,10 @@ 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::Initialized( &nonce::State::Initialized(nonce::state::Data {
nonce::state::Meta::new(&Pubkey::default()), authority: Pubkey::default(),
Hash::default(), blockhash: Hash::default(),
), }),
&system_program::id(), &system_program::id(),
) )
.unwrap(); .unwrap();

View File

@ -3,7 +3,7 @@ use solana_sdk::{
account_utils::StateMut, account_utils::StateMut,
hash::Hash, hash::Hash,
instruction::CompiledInstruction, instruction::CompiledInstruction,
nonce::{state::Versions, State}, nonce::{self, state::Versions, State},
program_utils::limited_deserialize, program_utils::limited_deserialize,
pubkey::Pubkey, pubkey::Pubkey,
system_instruction::SystemInstruction, system_instruction::SystemInstruction,
@ -40,7 +40,7 @@ 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 StateMut::<Versions>::state(acc).map(|v| v.convert_to_current()) { match StateMut::<Versions>::state(acc).map(|v| v.convert_to_current()) {
Ok(State::Initialized(_meta, ref nonce)) => hash == nonce, Ok(State::Initialized(ref data)) => *hash == data.blockhash,
_ => false, _ => false,
} }
} }
@ -63,8 +63,11 @@ pub fn prepare_if_nonce_account(
let state = StateMut::<Versions>::state(nonce_acc) let state = StateMut::<Versions>::state(nonce_acc)
.unwrap() .unwrap()
.convert_to_current(); .convert_to_current();
if let State::Initialized(meta, _) = state { if let State::Initialized(ref data) = state {
let new_data = Versions::new_current(State::Initialized(meta, *last_blockhash)); let new_data = Versions::new_current(State::Initialized(nonce::state::Data {
blockhash: *last_blockhash,
..*data
}));
account.set_state(&new_data).unwrap(); account.set_state(&new_data).unwrap();
} }
} }
@ -79,7 +82,7 @@ mod tests {
account_utils::State as AccountUtilsState, account_utils::State as AccountUtilsState,
hash::Hash, hash::Hash,
instruction::InstructionError, instruction::InstructionError,
nonce::{self, account::with_test_keyed_account, Account as 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,
@ -241,10 +244,10 @@ mod tests {
} }
fn create_accounts_prepare_if_nonce_account() -> (Pubkey, Account, Account, Hash) { fn create_accounts_prepare_if_nonce_account() -> (Pubkey, Account, Account, Hash) {
let data = Versions::new_current(State::Initialized( let data = Versions::new_current(State::Initialized(nonce::state::Data {
nonce::state::Meta::new(&Pubkey::default()), authority: Pubkey::default(),
Hash::default(), blockhash: Hash::default(),
)); }));
let account = Account::new_data(42, &data, &system_program::id()).unwrap(); let account = Account::new_data(42, &data, &system_program::id()).unwrap();
let pre_account = Account { let pre_account = Account {
lamports: 43, lamports: 43,
@ -296,10 +299,10 @@ 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();
let data = Versions::new_current(State::Initialized( let data = Versions::new_current(State::Initialized(nonce::state::Data {
nonce::state::Meta::new(&Pubkey::default()), authority: Pubkey::default(),
last_blockhash, blockhash: last_blockhash,
)); }));
expect_account.set_state(&data).unwrap(); expect_account.set_state(&data).unwrap();
assert!(run_prepare_if_nonce_account_test( assert!(run_prepare_if_nonce_account_test(
@ -356,8 +359,10 @@ mod tests {
let mut expect_account = pre_account.clone(); let mut expect_account = pre_account.clone();
expect_account expect_account
.set_state(&Versions::new_current(State::Initialized( .set_state(&Versions::new_current(State::Initialized(
nonce::state::Meta::new(&Pubkey::default()), nonce::state::Data {
last_blockhash, authority: Pubkey::default(),
blockhash: last_blockhash,
},
))) )))
.unwrap(); .unwrap();

View File

@ -306,7 +306,7 @@ 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(nonce::State::Initialized(_, _)) = account.state() { } else if let Ok(nonce::State::Initialized(_)) = account.state() {
Some(SystemAccountKind::Nonce) Some(SystemAccountKind::Nonce)
} else { } else {
None None
@ -733,10 +733,10 @@ 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::Initialized( &nonce::State::Initialized(nonce::state::Data {
nonce::state::Meta::new(&Pubkey::default()), authority: Pubkey::default(),
Hash::default(), blockhash: Hash::default(),
), }),
&system_program::id(), &system_program::id(),
) )
.unwrap(); .unwrap();
@ -875,7 +875,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::Initialized(nonce::state::Meta::new(&from), Hash::default()), &nonce::State::Initialized(nonce::state::Data {
authority: from,
blockhash: Hash::default(),
}),
&system_program::id(), &system_program::id(),
) )
.unwrap(); .unwrap();
@ -1368,10 +1371,10 @@ 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::Initialized( &nonce::State::Initialized(nonce::state::Data {
nonce::state::Meta::new(&Pubkey::default()), authority: Pubkey::default(),
Hash::default(), blockhash: Hash::default(),
), }),
&system_program::id(), &system_program::id(),
) )
.unwrap(); .unwrap();
@ -1399,10 +1402,10 @@ mod tests {
fn test_get_system_account_kind_nonsystem_owner_with_nonce_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::Initialized( &nonce::State::Initialized(nonce::state::Data {
nonce::state::Meta::new(&Pubkey::default()), authority: Pubkey::default(),
Hash::default(), blockhash: Hash::default(),
), }),
&Pubkey::new_rand(), &Pubkey::new_rand(),
) )
.unwrap(); .unwrap();

View File

@ -48,23 +48,23 @@ impl<'a> Account for KeyedAccount<'a> {
} }
let state = AccountUtilsState::<Versions>::state(self)?.convert_to_current(); let state = AccountUtilsState::<Versions>::state(self)?.convert_to_current();
let meta = match state { match state {
State::Initialized(meta, ref hash) => { State::Initialized(data) => {
if !signers.contains(&meta.nonce_authority) { if !signers.contains(&data.authority) {
return Err(InstructionError::MissingRequiredSignature); return Err(InstructionError::MissingRequiredSignature);
} }
if *hash == recent_blockhashes[0] { if data.blockhash == recent_blockhashes[0] {
return Err(NonceError::NotExpired.into()); return Err(NonceError::NotExpired.into());
} }
meta
}
_ => return Err(NonceError::BadAccountState.into()),
};
self.set_state(&Versions::new_current(State::Initialized( let new_data = nonce::state::Data {
meta, blockhash: recent_blockhashes[0],
recent_blockhashes[0], ..data
))) };
self.set_state(&Versions::new_current(State::Initialized(new_data)))
}
_ => Err(NonceError::BadAccountState.into()),
}
} }
fn withdraw_nonce_account( fn withdraw_nonce_account(
@ -82,9 +82,9 @@ impl<'a> Account for KeyedAccount<'a> {
} }
*self.unsigned_key() *self.unsigned_key()
} }
State::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] {
return Err(NonceError::NotExpired.into()); return Err(NonceError::NotExpired.into());
} }
} else { } else {
@ -93,7 +93,7 @@ impl<'a> Account for KeyedAccount<'a> {
return Err(InstructionError::InsufficientFunds); return Err(InstructionError::InsufficientFunds);
} }
} }
meta.nonce_authority data.authority
} }
}; };
@ -117,21 +117,20 @@ impl<'a> Account for KeyedAccount<'a> {
return Err(NonceError::NoRecentBlockhashes.into()); return Err(NonceError::NoRecentBlockhashes.into());
} }
let meta = match AccountUtilsState::<Versions>::state(self)?.convert_to_current() { match AccountUtilsState::<Versions>::state(self)?.convert_to_current() {
State::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);
} }
nonce::state::Meta::new(nonce_authority) let data = nonce::state::Data {
authority: *nonce_authority,
blockhash: recent_blockhashes[0],
};
self.set_state(&Versions::new_current(State::Initialized(data)))
} }
_ => return Err(NonceError::BadAccountState.into()), _ => Err(NonceError::BadAccountState.into()),
}; }
self.set_state(&Versions::new_current(State::Initialized(
meta,
recent_blockhashes[0],
)))
} }
fn authorize_nonce_account( fn authorize_nonce_account(
@ -140,14 +139,15 @@ impl<'a> Account for KeyedAccount<'a> {
signers: &HashSet<Pubkey>, signers: &HashSet<Pubkey>,
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
match AccountUtilsState::<Versions>::state(self)?.convert_to_current() { match AccountUtilsState::<Versions>::state(self)?.convert_to_current() {
State::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(&Versions::new_current(State::Initialized( let new_data = nonce::state::Data {
nonce::state::Meta::new(nonce_authority), authority: *nonce_authority,
nonce, ..data
))) };
self.set_state(&Versions::new_current(State::Initialized(new_data)))
} }
_ => Err(NonceError::BadAccountState.into()), _ => Err(NonceError::BadAccountState.into()),
} }
@ -195,15 +195,6 @@ mod test {
assert_eq!(State::default(), State::Uninitialized) assert_eq!(State::default(), State::Uninitialized)
} }
#[test]
fn new_meta() {
let nonce_authority = Pubkey::default();
assert_eq!(
nonce::state::Meta::new(&nonce_authority),
nonce::state::Meta { nonce_authority }
);
}
#[test] #[test]
fn keyed_account_expected_behavior() { fn keyed_account_expected_behavior() {
let rent = Rent { let rent = Rent {
@ -212,7 +203,10 @@ mod test {
}; };
let min_lamports = rent.minimum_balance(State::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 = nonce::state::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 = AccountUtilsState::<Versions>::state(keyed_account) let state = AccountUtilsState::<Versions>::state(keyed_account)
@ -228,9 +222,12 @@ mod test {
let state = AccountUtilsState::<Versions>::state(keyed_account) let state = AccountUtilsState::<Versions>::state(keyed_account)
.unwrap() .unwrap()
.convert_to_current(); .convert_to_current();
let stored = recent_blockhashes[0]; let data = nonce::state::Data {
blockhash: recent_blockhashes[0],
..data
};
// First nonce instruction drives state from Uninitialized to Initialized // First nonce instruction drives state from Uninitialized to Initialized
assert_eq!(state, State::Initialized(meta, stored)); assert_eq!(state, State::Initialized(data));
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)
@ -238,9 +235,12 @@ mod test {
let state = AccountUtilsState::<Versions>::state(keyed_account) let state = AccountUtilsState::<Versions>::state(keyed_account)
.unwrap() .unwrap()
.convert_to_current(); .convert_to_current();
let stored = recent_blockhashes[0]; let data = nonce::state::Data {
blockhash: recent_blockhashes[0],
..data
};
// Second nonce instruction consumes and replaces stored nonce // Second nonce instruction consumes and replaces stored nonce
assert_eq!(state, State::Initialized(meta, stored)); assert_eq!(state, State::Initialized(data));
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)
@ -248,9 +248,12 @@ mod test {
let state = AccountUtilsState::<Versions>::state(keyed_account) let state = AccountUtilsState::<Versions>::state(keyed_account)
.unwrap() .unwrap()
.convert_to_current(); .convert_to_current();
let stored = recent_blockhashes[0]; let data = nonce::state::Data {
blockhash: recent_blockhashes[0],
..data
};
// Third nonce instruction for fun and profit // Third nonce instruction for fun and profit
assert_eq!(state, State::Initialized(meta, stored)); assert_eq!(state, State::Initialized(data));
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;
@ -286,18 +289,20 @@ mod test {
let min_lamports = rent.minimum_balance(State::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 = nonce::state::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 = AccountUtilsState::<Versions>::state(&nonce_account) let state = AccountUtilsState::<Versions>::state(&nonce_account)
.unwrap() .unwrap()
.convert_to_current(); .convert_to_current();
assert_eq!(state, State::Initialized(meta, stored)); let data = nonce::state::Data {
authority,
blockhash: recent_blockhashes[0],
};
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);
@ -574,16 +579,18 @@ mod test {
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 = nonce::state::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 = AccountUtilsState::<Versions>::state(nonce_keyed) let state = AccountUtilsState::<Versions>::state(nonce_keyed)
.unwrap() .unwrap()
.convert_to_current(); .convert_to_current();
let stored = recent_blockhashes[0]; let data = nonce::state::Data {
assert_eq!(state, State::Initialized(meta, stored)); authority,
blockhash: recent_blockhashes[0],
};
assert_eq!(state, State::Initialized(data));
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 =
@ -601,8 +608,11 @@ mod test {
let state = AccountUtilsState::<Versions>::state(nonce_keyed) let state = AccountUtilsState::<Versions>::state(nonce_keyed)
.unwrap() .unwrap()
.convert_to_current(); .convert_to_current();
let stored = recent_blockhashes[0]; let data = nonce::state::Data {
assert_eq!(state, State::Initialized(meta, stored)); blockhash: recent_blockhashes[0],
..data
};
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);
@ -729,16 +739,18 @@ mod test {
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 = nonce::state::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],
};
assert_eq!(result, Ok(())); assert_eq!(result, Ok(()));
let state = AccountUtilsState::<Versions>::state(keyed_account) let state = AccountUtilsState::<Versions>::state(keyed_account)
.unwrap() .unwrap()
.convert_to_current(); .convert_to_current();
assert_eq!(state, State::Initialized(meta, stored)); assert_eq!(state, State::Initialized(data));
}) })
} }
@ -807,19 +819,21 @@ mod test {
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 = nonce::state::Meta::new(&authorized); let data = nonce::state::Data {
authority,
blockhash: recent_blockhashes[0],
};
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 = AccountUtilsState::<Versions>::state(nonce_account) let state = AccountUtilsState::<Versions>::state(nonce_account)
.unwrap() .unwrap()
.convert_to_current(); .convert_to_current();
assert_eq!(state, State::Initialized(meta, stored)); assert_eq!(state, State::Initialized(data));
}) })
} }

View File

@ -3,22 +3,15 @@ use crate::{hash::Hash, pubkey::Pubkey};
use serde_derive::{Deserialize, Serialize}; use serde_derive::{Deserialize, Serialize};
#[derive(Debug, Default, Serialize, Deserialize, PartialEq, Clone, Copy)] #[derive(Debug, Default, Serialize, Deserialize, PartialEq, Clone, Copy)]
pub struct Meta { pub struct Data {
pub nonce_authority: Pubkey, pub authority: Pubkey,
} pub blockhash: Hash,
impl Meta {
pub fn new(nonce_authority: &Pubkey) -> Self {
Self {
nonce_authority: *nonce_authority,
}
}
} }
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Copy)] #[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Copy)]
pub enum State { pub enum State {
Uninitialized, Uninitialized,
Initialized(Meta, Hash), Initialized(Data),
} }
impl Default for State { impl Default for State {
@ -29,7 +22,7 @@ impl Default for State {
impl State { impl State {
pub fn size() -> usize { pub fn size() -> usize {
let data = Versions::new_current(State::Initialized(Meta::default(), Hash::default())); let data = Versions::new_current(State::Initialized(Data::default()));
bincode::serialized_size(&data).unwrap() as usize bincode::serialized_size(&data).unwrap() as usize
} }
} }

View File

@ -1,5 +1,5 @@
mod current; mod current;
pub use current::{Meta, State}; pub use current::{Data, State};
use serde_derive::{Deserialize, Serialize}; use serde_derive::{Deserialize, Serialize};