Add program and runtime support for Durable Transaction Nonces (#6845)

* Rework transaction processing result forwarding

Durable nonce prereq

* Add Durable Nonce program API

* Add runtime changes for Durable Nonce program

* Register Durable Nonce program

* Concise comments and bad math

* Fix c/p error

* Add rent sysvar to withdraw ix

* Remove rent exempt required balance from Meta struct

* Use the helper
This commit is contained in:
Trent Nelson
2019-12-07 12:54:10 -07:00
committed by GitHub
parent 6469606baf
commit 1ffd6b4b4d
18 changed files with 1832 additions and 143 deletions

View File

@ -45,6 +45,7 @@ serde_bytes = "0.11"
serde_derive = "1.0.103"
serde_json = { version = "1.0.42", optional = true }
sha2 = "0.8.0"
thiserror = "1.0"
ed25519-dalek = { version = "1.0.0-pre.1", optional = true }
solana-crate-features = { path = "../crate-features", version = "0.22.0", optional = true }
solana-logger = { path = "../logger", version = "0.22.0", optional = true }

View File

@ -7,6 +7,7 @@ use crate::{
fee_calculator::FeeCalculator,
hash::{hash, Hash},
inflation::Inflation,
nonce_program::solana_nonce_program,
poh_config::PohConfig,
pubkey::Pubkey,
rent::Rent,
@ -52,7 +53,7 @@ pub fn create_genesis_config(lamports: u64) -> (GenesisConfig, Keypair) {
faucet_keypair.pubkey(),
Account::new(lamports, 0, &system_program::id()),
)],
&[solana_system_program()],
&[solana_nonce_program(), solana_system_program()],
),
faucet_keypair,
)

View File

@ -16,6 +16,9 @@ pub mod message;
pub mod move_loader;
pub mod native_loader;
pub mod native_token;
pub mod nonce_instruction;
pub mod nonce_program;
pub mod nonce_state;
pub mod poh_config;
pub mod pubkey;
pub mod rent;

View File

@ -0,0 +1,432 @@
use crate::{
account::{get_signers, KeyedAccount},
instruction::{AccountMeta, Instruction, InstructionError},
instruction_processor_utils::{limited_deserialize, next_keyed_account, DecodeError},
nonce_program::id,
nonce_state::{NonceAccount, NonceState},
pubkey::Pubkey,
system_instruction,
sysvar::{
recent_blockhashes::{self, RecentBlockhashes},
rent::{self, Rent},
Sysvar,
},
};
use num_derive::{FromPrimitive, ToPrimitive};
use serde_derive::{Deserialize, Serialize};
use thiserror::Error;
#[derive(Error, Debug, Clone, PartialEq, FromPrimitive, ToPrimitive)]
pub enum NonceError {
#[error("recent blockhash list is empty")]
NoRecentBlockhashes,
#[error("stored nonce is still in recent_blockhashes")]
NotExpired,
#[error("specified nonce does not match stored nonce")]
UnexpectedValue,
#[error("cannot handle request in current account state")]
BadAccountState,
}
impl<E> DecodeError<E> for NonceError {
fn type_of() -> &'static str {
"NonceError"
}
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub enum NonceInstruction {
/// `Nonce` consumes a stored nonce, replacing it with a successor
///
/// Expects 3 Accounts:
/// 0 - A NonceAccount
/// 1 - RecentBlockhashes sysvar
/// 2 - Rent sysvar
///
Nonce,
/// `Withdraw` transfers funds out of the nonce account
///
/// Expects 4 Accounts:
/// 0 - A NonceAccount
/// 1 - A system account to which the lamports will be transferred
/// 2 - RecentBlockhashes sysvar
/// 3 - Rent sysvar
///
/// The `u64` parameter is the lamports to withdraw, which must leave the
/// account balance above the rent exempt reserve or at zero.
Withdraw(u64),
}
pub fn create_nonce_account(
from_pubkey: &Pubkey,
nonce_pubkey: &Pubkey,
lamports: u64,
) -> Vec<Instruction> {
vec![
system_instruction::create_account(
from_pubkey,
nonce_pubkey,
lamports,
NonceState::size() as u64,
&id(),
),
nonce(nonce_pubkey),
]
}
pub fn nonce(nonce_pubkey: &Pubkey) -> Instruction {
Instruction::new(
id(),
&NonceInstruction::Nonce,
vec![
AccountMeta::new(*nonce_pubkey, true),
AccountMeta::new_readonly(recent_blockhashes::id(), false),
AccountMeta::new_readonly(rent::id(), false),
],
)
}
pub fn withdraw(nonce_pubkey: &Pubkey, to_pubkey: &Pubkey, lamports: u64) -> Instruction {
Instruction::new(
id(),
&NonceInstruction::Withdraw(lamports),
vec![
AccountMeta::new(*nonce_pubkey, true),
AccountMeta::new(*to_pubkey, false),
AccountMeta::new_readonly(recent_blockhashes::id(), false),
AccountMeta::new_readonly(rent::id(), false),
],
)
}
pub fn process_instruction(
_program_id: &Pubkey,
keyed_accounts: &mut [KeyedAccount],
data: &[u8],
) -> Result<(), InstructionError> {
let signers = get_signers(keyed_accounts);
let keyed_accounts = &mut keyed_accounts.iter_mut();
let me = &mut next_keyed_account(keyed_accounts)?;
match limited_deserialize(data)? {
NonceInstruction::Nonce => me.nonce(
&RecentBlockhashes::from_keyed_account(next_keyed_account(keyed_accounts)?)?,
&Rent::from_keyed_account(next_keyed_account(keyed_accounts)?)?,
&signers,
),
NonceInstruction::Withdraw(lamports) => {
let to = &mut next_keyed_account(keyed_accounts)?;
me.withdraw(
lamports,
to,
&RecentBlockhashes::from_keyed_account(next_keyed_account(keyed_accounts)?)?,
&Rent::from_keyed_account(next_keyed_account(keyed_accounts)?)?,
&signers,
)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{account::Account, hash::Hash, nonce_state, system_program, sysvar};
use bincode::serialize;
fn process_instruction(instruction: &Instruction) -> Result<(), InstructionError> {
let mut accounts: Vec<_> = instruction
.accounts
.iter()
.map(|meta| {
if sysvar::recent_blockhashes::check_id(&meta.pubkey) {
sysvar::recent_blockhashes::create_account_with_data(
1,
vec![(0u64, &Hash::default()); 32].into_iter(),
)
} else if sysvar::rent::check_id(&meta.pubkey) {
sysvar::rent::create_account(1, &Rent::default())
} else {
Account::default()
}
})
.collect();
{
let mut keyed_accounts: Vec<_> = instruction
.accounts
.iter()
.zip(accounts.iter_mut())
.map(|(meta, account)| KeyedAccount::new(&meta.pubkey, meta.is_signer, account))
.collect();
super::process_instruction(&Pubkey::default(), &mut keyed_accounts, &instruction.data)
}
}
#[test]
fn test_create_account() {
let from_pubkey = Pubkey::new_rand();
let nonce_pubkey = Pubkey::new_rand();
let ixs = create_nonce_account(&from_pubkey, &nonce_pubkey, 42);
assert_eq!(ixs.len(), 2);
let ix = &ixs[0];
assert_eq!(ix.program_id, system_program::id());
let pubkeys: Vec<_> = ix.accounts.iter().map(|am| am.pubkey).collect();
assert!(pubkeys.contains(&from_pubkey));
assert!(pubkeys.contains(&nonce_pubkey));
}
#[test]
fn test_process_nonce_ix_no_acc_data_fail() {
assert_eq!(
process_instruction(&nonce(&Pubkey::default(),)),
Err(InstructionError::InvalidAccountData),
);
}
#[test]
fn test_process_nonce_ix_no_keyed_accs_fail() {
assert_eq!(
super::process_instruction(
&Pubkey::default(),
&mut [],
&serialize(&NonceInstruction::Nonce).unwrap()
),
Err(InstructionError::NotEnoughAccountKeys),
);
}
#[test]
fn test_process_nonce_ix_only_nonce_acc_fail() {
assert_eq!(
super::process_instruction(
&Pubkey::default(),
&mut [KeyedAccount::new(
&Pubkey::default(),
true,
&mut Account::default(),
),],
&serialize(&NonceInstruction::Nonce).unwrap(),
),
Err(InstructionError::NotEnoughAccountKeys),
);
}
#[test]
fn test_process_nonce_ix_bad_recent_blockhash_state_fail() {
assert_eq!(
super::process_instruction(
&Pubkey::default(),
&mut [
KeyedAccount::new(&Pubkey::default(), true, &mut Account::default(),),
KeyedAccount::new(
&sysvar::recent_blockhashes::id(),
false,
&mut Account::default(),
),
],
&serialize(&NonceInstruction::Nonce).unwrap(),
),
Err(InstructionError::InvalidArgument),
);
}
#[test]
fn test_process_nonce_ix_bad_rent_state_fail() {
assert_eq!(
super::process_instruction(
&Pubkey::default(),
&mut [
KeyedAccount::new(&Pubkey::default(), true, &mut Account::default(),),
KeyedAccount::new(
&sysvar::recent_blockhashes::id(),
false,
&mut sysvar::recent_blockhashes::create_account(1),
),
KeyedAccount::new(&sysvar::rent::id(), false, &mut Account::default(),),
],
&serialize(&NonceInstruction::Nonce).unwrap(),
),
Err(InstructionError::InvalidArgument),
);
}
#[test]
fn test_process_nonce_ix_ok() {
assert_eq!(
super::process_instruction(
&Pubkey::default(),
&mut [
KeyedAccount::new(
&Pubkey::default(),
true,
&mut nonce_state::create_account(1_000_000),
),
KeyedAccount::new(
&sysvar::recent_blockhashes::id(),
false,
&mut sysvar::recent_blockhashes::create_account_with_data(
1,
vec![(0u64, &Hash::default()); 32].into_iter(),
),
),
KeyedAccount::new(
&sysvar::rent::id(),
false,
&mut sysvar::rent::create_account(1, &Rent::default()),
),
],
&serialize(&NonceInstruction::Nonce).unwrap(),
),
Ok(()),
);
}
#[test]
fn test_process_withdraw_ix_no_acc_data_fail() {
assert_eq!(
process_instruction(&withdraw(&Pubkey::default(), &Pubkey::default(), 1,)),
Err(InstructionError::InvalidAccountData),
);
}
#[test]
fn test_process_withdraw_ix_no_keyed_accs_fail() {
assert_eq!(
super::process_instruction(
&Pubkey::default(),
&mut [],
&serialize(&NonceInstruction::Withdraw(42)).unwrap(),
),
Err(InstructionError::NotEnoughAccountKeys),
);
}
#[test]
fn test_process_withdraw_ix_only_nonce_acc_fail() {
assert_eq!(
super::process_instruction(
&Pubkey::default(),
&mut [KeyedAccount::new(
&Pubkey::default(),
true,
&mut Account::default(),
),],
&serialize(&NonceInstruction::Withdraw(42)).unwrap(),
),
Err(InstructionError::NotEnoughAccountKeys),
);
}
#[test]
fn test_process_withdraw_ix_bad_recent_blockhash_state_fail() {
assert_eq!(
super::process_instruction(
&Pubkey::default(),
&mut [
KeyedAccount::new(&Pubkey::default(), true, &mut Account::default(),),
KeyedAccount::new(&Pubkey::default(), false, &mut Account::default(),),
KeyedAccount::new(
&sysvar::recent_blockhashes::id(),
false,
&mut Account::default(),
),
],
&serialize(&NonceInstruction::Withdraw(42)).unwrap(),
),
Err(InstructionError::InvalidArgument),
);
}
#[test]
fn test_process_withdraw_ix_bad_rent_state_fail() {
assert_eq!(
super::process_instruction(
&Pubkey::default(),
&mut [
KeyedAccount::new(&Pubkey::default(), true, &mut Account::default(),),
KeyedAccount::new(&Pubkey::default(), false, &mut Account::default(),),
KeyedAccount::new(
&sysvar::recent_blockhashes::id(),
false,
&mut Account::default(),
),
KeyedAccount::new(&sysvar::rent::id(), false, &mut Account::default(),),
],
&serialize(&NonceInstruction::Withdraw(42)).unwrap(),
),
Err(InstructionError::InvalidArgument),
);
}
#[test]
fn test_process_withdraw_ix_ok() {
assert_eq!(
super::process_instruction(
&Pubkey::default(),
&mut [
KeyedAccount::new(
&Pubkey::default(),
true,
&mut nonce_state::create_account(1_000_000),
),
KeyedAccount::new(&Pubkey::default(), true, &mut Account::default(),),
KeyedAccount::new(
&sysvar::recent_blockhashes::id(),
false,
&mut sysvar::recent_blockhashes::create_account_with_data(
1,
vec![(0u64, &Hash::default()); 32].into_iter(),
),
),
KeyedAccount::new(
&sysvar::rent::id(),
false,
&mut sysvar::rent::create_account(1, &Rent::default())
),
],
&serialize(&NonceInstruction::Withdraw(42)).unwrap(),
),
Ok(()),
);
}
#[test]
fn test_custom_error_decode() {
use num_traits::FromPrimitive;
fn pretty_err<T>(err: InstructionError) -> String
where
T: 'static + std::error::Error + DecodeError<T> + FromPrimitive,
{
if let InstructionError::CustomError(code) = err {
let specific_error: T = T::decode_custom_error_to_enum(code).unwrap();
format!(
"{:?}: {}::{:?} - {}",
err,
T::type_of(),
specific_error,
specific_error,
)
} else {
"".to_string()
}
}
assert_eq!(
"CustomError(0): NonceError::NoRecentBlockhashes - recent blockhash list is empty",
pretty_err::<NonceError>(NonceError::NoRecentBlockhashes.into())
);
assert_eq!(
"CustomError(1): NonceError::NotExpired - stored nonce is still in recent_blockhashes",
pretty_err::<NonceError>(NonceError::NotExpired.into())
);
assert_eq!(
"CustomError(2): NonceError::UnexpectedValue - specified nonce does not match stored nonce",
pretty_err::<NonceError>(NonceError::UnexpectedValue.into())
);
assert_eq!(
"CustomError(3): NonceError::BadAccountState - cannot handle request in current account state",
pretty_err::<NonceError>(NonceError::BadAccountState.into())
);
}
}

5
sdk/src/nonce_program.rs Normal file
View File

@ -0,0 +1,5 @@
crate::declare_id!("Nonce11111111111111111111111111111111111111");
pub fn solana_nonce_program() -> (String, crate::pubkey::Pubkey) {
("solana_nonce_program".to_string(), id())
}

618
sdk/src/nonce_state.rs Normal file
View File

@ -0,0 +1,618 @@
use crate::{
account::{Account, KeyedAccount},
account_utils::State,
hash::Hash,
instruction::InstructionError,
nonce_instruction::NonceError,
nonce_program,
pubkey::Pubkey,
sysvar::recent_blockhashes::RecentBlockhashes,
sysvar::rent::Rent,
};
use serde_derive::{Deserialize, Serialize};
use std::collections::HashSet;
#[derive(Debug, Default, Serialize, Deserialize, PartialEq, Clone, Copy)]
pub struct Meta {}
impl Meta {
pub fn new() -> Self {
Self {}
}
}
#[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 nonce(
&mut self,
recent_blockhashes: &RecentBlockhashes,
rent: &Rent,
signers: &HashSet<Pubkey>,
) -> Result<(), InstructionError>;
fn withdraw(
&mut self,
lamports: u64,
to: &mut KeyedAccount,
recent_blockhashes: &RecentBlockhashes,
rent: &Rent,
signers: &HashSet<Pubkey>,
) -> Result<(), InstructionError>;
}
impl<'a> NonceAccount for KeyedAccount<'a> {
fn nonce(
&mut self,
recent_blockhashes: &RecentBlockhashes,
rent: &Rent,
signers: &HashSet<Pubkey>,
) -> Result<(), InstructionError> {
if recent_blockhashes.is_empty() {
return Err(NonceError::NoRecentBlockhashes.into());
}
if !signers.contains(self.unsigned_key()) {
return Err(InstructionError::MissingRequiredSignature);
}
let meta = match self.state()? {
NonceState::Initialized(meta, ref hash) => {
if *hash == recent_blockhashes[0] {
return Err(NonceError::NotExpired.into());
}
meta
}
NonceState::Uninitialized => {
let min_balance = rent.minimum_balance(self.account.data.len());
if self.account.lamports < min_balance {
return Err(InstructionError::InsufficientFunds);
}
Meta::new()
}
};
self.set_state(&NonceState::Initialized(meta, recent_blockhashes[0]))
}
fn withdraw(
&mut self,
lamports: u64,
to: &mut KeyedAccount,
recent_blockhashes: &RecentBlockhashes,
rent: &Rent,
signers: &HashSet<Pubkey>,
) -> Result<(), InstructionError> {
if !signers.contains(self.unsigned_key()) {
return Err(InstructionError::MissingRequiredSignature);
}
match self.state()? {
NonceState::Uninitialized => {
if lamports > self.account.lamports {
return Err(InstructionError::InsufficientFunds);
}
}
NonceState::Initialized(_meta, ref hash) => {
if lamports == self.account.lamports {
if *hash == recent_blockhashes[0] {
return Err(NonceError::NotExpired.into());
}
self.set_state(&NonceState::Uninitialized)?;
} else {
let min_balance = rent.minimum_balance(self.account.data.len());
if lamports + min_balance > self.account.lamports {
return Err(InstructionError::InsufficientFunds);
}
}
}
}
self.account.lamports -= lamports;
to.account.lamports += lamports;
Ok(())
}
}
pub fn create_account(lamports: u64) -> Account {
Account::new_data_with_space(
lamports,
&NonceState::Uninitialized,
NonceState::size(),
&nonce_program::id(),
)
.expect("nonce_account")
}
/// Convenience function for working with keyed accounts in tests
#[cfg(not(feature = "program"))]
pub fn with_test_keyed_account<F>(lamports: u64, signer: bool, mut f: F)
where
F: FnMut(&mut KeyedAccount),
{
let pubkey = Pubkey::new_rand();
let mut account = create_account(lamports);
let mut keyed_account = KeyedAccount::new(&pubkey, signer, &mut account);
f(&mut keyed_account)
}
#[cfg(test)]
mod test {
use super::*;
use crate::{
account::KeyedAccount,
nonce_instruction::NonceError,
sysvar::recent_blockhashes::{create_test_recent_blockhashes, RecentBlockhashes},
};
use std::iter::FromIterator;
#[test]
fn default_is_uninitialized() {
assert_eq!(NonceState::default(), NonceState::Uninitialized)
}
#[test]
fn new_meta() {
assert_eq!(Meta::new(), Meta {});
}
#[test]
fn keyed_account_expected_behavior() {
let rent = Rent {
lamports_per_byte_year: 42,
..Rent::default()
};
let min_lamports = rent.minimum_balance(NonceState::size());
let meta = Meta::new();
with_test_keyed_account(min_lamports + 42, true, |keyed_account| {
let mut signers = HashSet::new();
signers.insert(keyed_account.signer_key().unwrap().clone());
let state: NonceState = keyed_account.state().unwrap();
// New is in Uninitialzed state
assert_eq!(state, NonceState::Uninitialized);
let recent_blockhashes = create_test_recent_blockhashes(95);
keyed_account
.nonce(&recent_blockhashes, &rent, &signers)
.unwrap();
let state: NonceState = keyed_account.state().unwrap();
let stored = recent_blockhashes[0];
// First nonce instruction drives state from Uninitialized to Initialized
assert_eq!(state, NonceState::Initialized(meta, stored));
let recent_blockhashes = create_test_recent_blockhashes(63);
keyed_account
.nonce(&recent_blockhashes, &rent, &signers)
.unwrap();
let state: NonceState = keyed_account.state().unwrap();
let stored = recent_blockhashes[0];
// Second nonce instruction consumes and replaces stored nonce
assert_eq!(state, NonceState::Initialized(meta, stored));
let recent_blockhashes = create_test_recent_blockhashes(31);
keyed_account
.nonce(&recent_blockhashes, &rent, &signers)
.unwrap();
let state: NonceState = keyed_account.state().unwrap();
let stored = recent_blockhashes[0];
// Third nonce instruction for fun and profit
assert_eq!(state, NonceState::Initialized(meta, stored));
with_test_keyed_account(42, false, |mut to_keyed| {
let recent_blockhashes = create_test_recent_blockhashes(0);
let withdraw_lamports = keyed_account.account.lamports;
let expect_nonce_lamports = keyed_account.account.lamports - withdraw_lamports;
let expect_to_lamports = to_keyed.account.lamports + withdraw_lamports;
keyed_account
.withdraw(
withdraw_lamports,
&mut to_keyed,
&recent_blockhashes,
&rent,
&signers,
)
.unwrap();
let state: NonceState = keyed_account.state().unwrap();
// Withdraw instruction...
// Deinitializes NonceAccount state
assert_eq!(state, NonceState::Uninitialized);
// Empties NonceAccount balance
assert_eq!(keyed_account.account.lamports, expect_nonce_lamports);
// NonceAccount balance goes to `to`
assert_eq!(to_keyed.account.lamports, expect_to_lamports);
})
})
}
#[test]
fn nonce_inx_uninitialized_account_not_signer_fail() {
let rent = Rent {
lamports_per_byte_year: 42,
..Rent::default()
};
let min_lamports = rent.minimum_balance(NonceState::size());
with_test_keyed_account(min_lamports + 42, false, |nonce_account| {
let signers = HashSet::new();
let recent_blockhashes = create_test_recent_blockhashes(0);
let result = nonce_account.nonce(&recent_blockhashes, &rent, &signers);
assert_eq!(result, Err(InstructionError::MissingRequiredSignature),);
})
}
#[test]
fn nonce_inx_initialized_account_not_signer_fail() {
let rent = Rent {
lamports_per_byte_year: 42,
..Rent::default()
};
let min_lamports = rent.minimum_balance(NonceState::size());
let meta = Meta::new();
with_test_keyed_account(min_lamports + 42, true, |nonce_account| {
let mut signers = HashSet::new();
signers.insert(nonce_account.signer_key().unwrap().clone());
let recent_blockhashes = create_test_recent_blockhashes(31);
let stored = recent_blockhashes[0];
nonce_account
.nonce(&recent_blockhashes, &rent, &signers)
.unwrap();
let pubkey = nonce_account.account.owner.clone();
let mut nonce_account = KeyedAccount::new(&pubkey, false, nonce_account.account);
let state: NonceState = nonce_account.state().unwrap();
assert_eq!(state, NonceState::Initialized(meta, stored));
let signers = HashSet::new();
let recent_blockhashes = create_test_recent_blockhashes(0);
let result = nonce_account.nonce(&recent_blockhashes, &rent, &signers);
assert_eq!(result, Err(InstructionError::MissingRequiredSignature),);
})
}
#[test]
fn nonce_inx_with_empty_recent_blockhashes_fail() {
let rent = Rent {
lamports_per_byte_year: 42,
..Rent::default()
};
let min_lamports = rent.minimum_balance(NonceState::size());
with_test_keyed_account(min_lamports + 42, true, |keyed_account| {
let mut signers = HashSet::new();
signers.insert(keyed_account.signer_key().unwrap().clone());
let recent_blockhashes = RecentBlockhashes::from_iter(vec![].into_iter());
let result = keyed_account.nonce(&recent_blockhashes, &rent, &signers);
assert_eq!(result, Err(NonceError::NoRecentBlockhashes.into()));
})
}
#[test]
fn nonce_inx_too_early_fail() {
let rent = Rent {
lamports_per_byte_year: 42,
..Rent::default()
};
let min_lamports = rent.minimum_balance(NonceState::size());
with_test_keyed_account(min_lamports + 42, true, |keyed_account| {
let mut signers = HashSet::new();
signers.insert(keyed_account.signer_key().unwrap().clone());
let recent_blockhashes = create_test_recent_blockhashes(63);
keyed_account
.nonce(&recent_blockhashes, &rent, &signers)
.unwrap();
let result = keyed_account.nonce(&recent_blockhashes, &rent, &signers);
assert_eq!(result, Err(NonceError::NotExpired.into()));
})
}
#[test]
fn nonce_inx_uninitialized_acc_insuff_funds_fail() {
let rent = Rent {
lamports_per_byte_year: 42,
..Rent::default()
};
let min_lamports = rent.minimum_balance(NonceState::size());
with_test_keyed_account(min_lamports - 42, true, |keyed_account| {
let mut signers = HashSet::new();
signers.insert(keyed_account.signer_key().unwrap().clone());
let recent_blockhashes = create_test_recent_blockhashes(63);
let result = keyed_account.nonce(&recent_blockhashes, &rent, &signers);
assert_eq!(result, Err(InstructionError::InsufficientFunds));
})
}
#[test]
fn withdraw_inx_unintialized_acc_ok() {
let rent = Rent {
lamports_per_byte_year: 42,
..Rent::default()
};
let min_lamports = rent.minimum_balance(NonceState::size());
with_test_keyed_account(min_lamports + 42, true, |nonce_keyed| {
let state: NonceState = nonce_keyed.state().unwrap();
assert_eq!(state, NonceState::Uninitialized);
with_test_keyed_account(42, false, |mut to_keyed| {
let mut signers = HashSet::new();
signers.insert(nonce_keyed.signer_key().unwrap().clone());
let recent_blockhashes = create_test_recent_blockhashes(0);
let withdraw_lamports = nonce_keyed.account.lamports;
let expect_nonce_lamports = nonce_keyed.account.lamports - withdraw_lamports;
let expect_to_lamports = to_keyed.account.lamports + withdraw_lamports;
nonce_keyed
.withdraw(
withdraw_lamports,
&mut to_keyed,
&recent_blockhashes,
&rent,
&signers,
)
.unwrap();
let state: NonceState = nonce_keyed.state().unwrap();
// Withdraw instruction...
// Deinitializes NonceAccount state
assert_eq!(state, NonceState::Uninitialized);
// Empties NonceAccount balance
assert_eq!(nonce_keyed.account.lamports, expect_nonce_lamports);
// NonceAccount balance goes to `to`
assert_eq!(to_keyed.account.lamports, expect_to_lamports);
})
})
}
#[test]
fn withdraw_inx_unintialized_acc_unsigned_fail() {
let rent = Rent {
lamports_per_byte_year: 42,
..Rent::default()
};
let min_lamports = rent.minimum_balance(NonceState::size());
with_test_keyed_account(min_lamports + 42, false, |nonce_keyed| {
let state: NonceState = nonce_keyed.state().unwrap();
assert_eq!(state, NonceState::Uninitialized);
with_test_keyed_account(42, false, |mut to_keyed| {
let signers = HashSet::new();
let recent_blockhashes = create_test_recent_blockhashes(0);
let result = nonce_keyed.withdraw(
nonce_keyed.account.lamports,
&mut to_keyed,
&recent_blockhashes,
&rent,
&signers,
);
assert_eq!(result, Err(InstructionError::MissingRequiredSignature),);
})
})
}
#[test]
fn withdraw_inx_unintialized_acc_insuff_funds_fail() {
let rent = Rent {
lamports_per_byte_year: 42,
..Rent::default()
};
let min_lamports = rent.minimum_balance(NonceState::size());
with_test_keyed_account(min_lamports + 42, true, |nonce_keyed| {
let state: NonceState = nonce_keyed.state().unwrap();
assert_eq!(state, NonceState::Uninitialized);
with_test_keyed_account(42, false, |mut to_keyed| {
let mut signers = HashSet::new();
signers.insert(nonce_keyed.signer_key().unwrap().clone());
let recent_blockhashes = create_test_recent_blockhashes(0);
let result = nonce_keyed.withdraw(
nonce_keyed.account.lamports + 1,
&mut to_keyed,
&recent_blockhashes,
&rent,
&signers,
);
assert_eq!(result, Err(InstructionError::InsufficientFunds));
})
})
}
#[test]
fn withdraw_inx_uninitialized_acc_two_withdraws_ok() {
let rent = Rent {
lamports_per_byte_year: 42,
..Rent::default()
};
let min_lamports = rent.minimum_balance(NonceState::size());
with_test_keyed_account(min_lamports + 42, true, |nonce_keyed| {
with_test_keyed_account(42, false, |mut to_keyed| {
let mut signers = HashSet::new();
signers.insert(nonce_keyed.signer_key().unwrap().clone());
let recent_blockhashes = create_test_recent_blockhashes(0);
let withdraw_lamports = nonce_keyed.account.lamports / 2;
let nonce_expect_lamports = nonce_keyed.account.lamports - withdraw_lamports;
let to_expect_lamports = to_keyed.account.lamports + withdraw_lamports;
nonce_keyed
.withdraw(
withdraw_lamports,
&mut to_keyed,
&recent_blockhashes,
&rent,
&signers,
)
.unwrap();
let state: NonceState = nonce_keyed.state().unwrap();
assert_eq!(state, NonceState::Uninitialized);
assert_eq!(nonce_keyed.account.lamports, nonce_expect_lamports);
assert_eq!(to_keyed.account.lamports, to_expect_lamports);
let withdraw_lamports = nonce_keyed.account.lamports;
let nonce_expect_lamports = nonce_keyed.account.lamports - withdraw_lamports;
let to_expect_lamports = to_keyed.account.lamports + withdraw_lamports;
nonce_keyed
.withdraw(
withdraw_lamports,
&mut to_keyed,
&recent_blockhashes,
&rent,
&signers,
)
.unwrap();
let state: NonceState = nonce_keyed.state().unwrap();
assert_eq!(state, NonceState::Uninitialized);
assert_eq!(nonce_keyed.account.lamports, nonce_expect_lamports);
assert_eq!(to_keyed.account.lamports, to_expect_lamports);
})
})
}
#[test]
fn withdraw_inx_initialized_acc_two_withdraws_ok() {
let rent = Rent {
lamports_per_byte_year: 42,
..Rent::default()
};
let min_lamports = rent.minimum_balance(NonceState::size());
let meta = Meta::new();
with_test_keyed_account(min_lamports + 42, true, |nonce_keyed| {
let mut signers = HashSet::new();
signers.insert(nonce_keyed.signer_key().unwrap().clone());
let recent_blockhashes = create_test_recent_blockhashes(31);
nonce_keyed
.nonce(&recent_blockhashes, &rent, &signers)
.unwrap();
let state: NonceState = nonce_keyed.state().unwrap();
let stored = recent_blockhashes[0];
assert_eq!(state, NonceState::Initialized(meta, stored));
with_test_keyed_account(42, false, |mut to_keyed| {
let withdraw_lamports = nonce_keyed.account.lamports - min_lamports;
let nonce_expect_lamports = nonce_keyed.account.lamports - withdraw_lamports;
let to_expect_lamports = to_keyed.account.lamports + withdraw_lamports;
nonce_keyed
.withdraw(
withdraw_lamports,
&mut to_keyed,
&recent_blockhashes,
&rent,
&signers,
)
.unwrap();
let state: NonceState = nonce_keyed.state().unwrap();
let stored = recent_blockhashes[0];
assert_eq!(state, NonceState::Initialized(meta, stored));
assert_eq!(nonce_keyed.account.lamports, nonce_expect_lamports);
assert_eq!(to_keyed.account.lamports, to_expect_lamports);
let recent_blockhashes = create_test_recent_blockhashes(0);
let withdraw_lamports = nonce_keyed.account.lamports;
let nonce_expect_lamports = nonce_keyed.account.lamports - withdraw_lamports;
let to_expect_lamports = to_keyed.account.lamports + withdraw_lamports;
nonce_keyed
.withdraw(
withdraw_lamports,
&mut to_keyed,
&recent_blockhashes,
&rent,
&signers,
)
.unwrap();
let state: NonceState = nonce_keyed.state().unwrap();
assert_eq!(state, NonceState::Uninitialized);
assert_eq!(nonce_keyed.account.lamports, nonce_expect_lamports);
assert_eq!(to_keyed.account.lamports, to_expect_lamports);
})
})
}
#[test]
fn withdraw_inx_initialized_acc_nonce_too_early_fail() {
let rent = Rent {
lamports_per_byte_year: 42,
..Rent::default()
};
let min_lamports = rent.minimum_balance(NonceState::size());
with_test_keyed_account(min_lamports + 42, true, |nonce_keyed| {
let mut signers = HashSet::new();
signers.insert(nonce_keyed.signer_key().unwrap().clone());
let recent_blockhashes = create_test_recent_blockhashes(0);
nonce_keyed
.nonce(&recent_blockhashes, &rent, &signers)
.unwrap();
with_test_keyed_account(42, false, |mut to_keyed| {
let mut signers = HashSet::new();
signers.insert(nonce_keyed.signer_key().unwrap().clone());
let withdraw_lamports = nonce_keyed.account.lamports;
let result = nonce_keyed.withdraw(
withdraw_lamports,
&mut to_keyed,
&recent_blockhashes,
&rent,
&signers,
);
assert_eq!(result, Err(NonceError::NotExpired.into()));
})
})
}
#[test]
fn withdraw_inx_initialized_acc_insuff_funds_fail() {
let rent = Rent {
lamports_per_byte_year: 42,
..Rent::default()
};
let min_lamports = rent.minimum_balance(NonceState::size());
with_test_keyed_account(min_lamports + 42, true, |nonce_keyed| {
let mut signers = HashSet::new();
signers.insert(nonce_keyed.signer_key().unwrap().clone());
let recent_blockhashes = create_test_recent_blockhashes(95);
nonce_keyed
.nonce(&recent_blockhashes, &rent, &signers)
.unwrap();
with_test_keyed_account(42, false, |mut to_keyed| {
let recent_blockhashes = create_test_recent_blockhashes(63);
let mut signers = HashSet::new();
signers.insert(nonce_keyed.signer_key().unwrap().clone());
let withdraw_lamports = nonce_keyed.account.lamports + 1;
let result = nonce_keyed.withdraw(
withdraw_lamports,
&mut to_keyed,
&recent_blockhashes,
&rent,
&signers,
);
assert_eq!(result, Err(InstructionError::InsufficientFunds));
})
})
}
#[test]
fn withdraw_inx_initialized_acc_insuff_rent_fail() {
let rent = Rent {
lamports_per_byte_year: 42,
..Rent::default()
};
let min_lamports = rent.minimum_balance(NonceState::size());
with_test_keyed_account(min_lamports + 42, true, |nonce_keyed| {
let mut signers = HashSet::new();
signers.insert(nonce_keyed.signer_key().unwrap().clone());
let recent_blockhashes = create_test_recent_blockhashes(95);
nonce_keyed
.nonce(&recent_blockhashes, &rent, &signers)
.unwrap();
with_test_keyed_account(42, false, |mut to_keyed| {
let recent_blockhashes = create_test_recent_blockhashes(63);
let mut signers = HashSet::new();
signers.insert(nonce_keyed.signer_key().unwrap().clone());
let withdraw_lamports = nonce_keyed.account.lamports - min_lamports + 1;
let result = nonce_keyed.withdraw(
withdraw_lamports,
&mut to_keyed,
&recent_blockhashes,
&rent,
&signers,
);
assert_eq!(result, Err(InstructionError::InsufficientFunds));
})
})
}
}

View File

@ -1,4 +1,9 @@
use crate::{account::Account, hash::Hash, sysvar::Sysvar};
use crate::{
account::Account,
hash::{hash, Hash},
sysvar::Sysvar,
};
use bincode::serialize;
use std::collections::BinaryHeap;
use std::iter::FromIterator;
use std::ops::Deref;
@ -69,6 +74,13 @@ where
account
}
pub fn create_test_recent_blockhashes(start: usize) -> RecentBlockhashes {
let bhq: Vec<_> = (start..start + (MAX_ENTRIES - 1))
.map(|i| hash(&serialize(&i).unwrap()))
.collect();
RecentBlockhashes::from_iter(bhq.iter())
}
#[cfg(test)]
mod tests {
use super::*;