move Account to solana-sdk (#13198)

This commit is contained in:
Jack May
2020-10-28 22:01:07 -07:00
committed by GitHub
parent d5e439037b
commit c458d4b213
38 changed files with 460 additions and 459 deletions

View File

@ -2,9 +2,9 @@
extern crate test;
use solana_sdk::{
account::{create_account, from_account},
hash::Hash,
slot_hashes::{Slot, SlotHashes, MAX_ENTRIES},
sysvar::Sysvar,
};
use test::Bencher;
@ -15,7 +15,7 @@ fn bench_to_from_account(b: &mut Bencher) {
slot_hashes.add(i as Slot, Hash::default());
}
b.iter(|| {
let account = slot_hashes.create_account(0);
slot_hashes = SlotHashes::from_account(&account).unwrap();
let account = create_account(&slot_hashes, 0);
slot_hashes = from_account::<SlotHashes>(&account).unwrap();
});
}

View File

@ -1,7 +1,10 @@
#![feature(test)]
extern crate test;
use solana_sdk::{slot_history::SlotHistory, sysvar::Sysvar};
use solana_sdk::{
account::{create_account, from_account},
slot_history::SlotHistory,
};
use test::Bencher;
#[bench]
@ -9,8 +12,8 @@ fn bench_to_from_account(b: &mut Bencher) {
let mut slot_history = SlotHistory::default();
b.iter(|| {
let account = slot_history.create_account(0);
slot_history = SlotHistory::from_account(&account).unwrap();
let account = create_account(&slot_history, 0);
slot_history = from_account::<SlotHistory>(&account).unwrap();
});
}

View File

@ -1,4 +1,4 @@
use crate::{account::Account, clock::Epoch, program_error::ProgramError, pubkey::Pubkey};
use crate::{clock::Epoch, program_error::ProgramError, pubkey::Pubkey};
use std::{
cell::{Ref, RefCell, RefMut},
cmp, fmt,
@ -148,76 +148,57 @@ impl<'a> AccountInfo<'a> {
}
}
impl<'a> From<(&'a Pubkey, &'a mut Account)> for AccountInfo<'a> {
fn from((key, account): (&'a Pubkey, &'a mut Account)) -> Self {
Self::new(
key,
false,
false,
&mut account.lamports,
&mut account.data,
&account.owner,
account.executable,
account.rent_epoch,
/// Constructs an `AccountInfo` from self, used in conversion implementations.
pub trait IntoAccountInfo<'a> {
fn into_account_info(self) -> AccountInfo<'a>;
}
impl<'a, T: IntoAccountInfo<'a>> From<T> for AccountInfo<'a> {
fn from(src: T) -> Self {
src.into_account_info()
}
}
/// Provides information required to construct an `AccountInfo`, used in
/// conversion implementations.
pub trait Account {
fn get(&mut self) -> (&mut u64, &mut [u8], &Pubkey, bool, Epoch);
}
/// Convert (&'a Pubkey, &'a mut T) where T: Account into an `AccountInfo`
impl<'a, T: Account> IntoAccountInfo<'a> for (&'a Pubkey, &'a mut T) {
fn into_account_info(self) -> AccountInfo<'a> {
let (key, account) = self;
let (lamports, data, owner, executable, rent_epoch) = account.get();
AccountInfo::new(
key, false, false, lamports, data, owner, executable, rent_epoch,
)
}
}
impl<'a> From<(&'a Pubkey, bool, &'a mut Account)> for AccountInfo<'a> {
fn from((key, is_signer, account): (&'a Pubkey, bool, &'a mut Account)) -> Self {
Self::new(
key,
is_signer,
false,
&mut account.lamports,
&mut account.data,
&account.owner,
account.executable,
account.rent_epoch,
/// Convert (&'a Pubkey, bool, &'a mut T) where T: Account into an
/// `AccountInfo`.
impl<'a, T: Account> IntoAccountInfo<'a> for (&'a Pubkey, bool, &'a mut T) {
fn into_account_info(self) -> AccountInfo<'a> {
let (key, is_signer, account) = self;
let (lamports, data, owner, executable, rent_epoch) = account.get();
AccountInfo::new(
key, is_signer, false, lamports, data, owner, executable, rent_epoch,
)
}
}
impl<'a> From<&'a mut (Pubkey, Account)> for AccountInfo<'a> {
fn from((key, account): &'a mut (Pubkey, Account)) -> Self {
Self::new(
key,
false,
false,
&mut account.lamports,
&mut account.data,
&account.owner,
account.executable,
account.rent_epoch,
/// Convert &'a mut (Pubkey, T) where T: Account into an `AccountInfo`.
impl<'a, T: Account> IntoAccountInfo<'a> for &'a mut (Pubkey, T) {
fn into_account_info(self) -> AccountInfo<'a> {
let (ref key, account) = self;
let (lamports, data, owner, executable, rent_epoch) = account.get();
AccountInfo::new(
key, false, false, lamports, data, owner, executable, rent_epoch,
)
}
}
pub fn create_account_infos(accounts: &mut [(Pubkey, Account)]) -> Vec<AccountInfo> {
accounts.iter_mut().map(Into::into).collect()
}
pub fn create_is_signer_account_infos<'a>(
accounts: &'a mut [(&'a Pubkey, bool, &'a mut Account)],
) -> Vec<AccountInfo<'a>> {
accounts
.iter_mut()
.map(|(key, is_signer, account)| {
AccountInfo::new(
key,
*is_signer,
false,
&mut account.lamports,
&mut account.data,
&account.owner,
account.executable,
account.rent_epoch,
)
})
.collect()
}
/// Return the next AccountInfo or a NotEnoughAccountKeys error
/// Return the next AccountInfo or a NotEnoughAccountKeys error.
pub fn next_account_info<'a, 'b, I: Iterator<Item = &'a AccountInfo<'b>>>(
iter: &mut I,
) -> Result<I::Item, ProgramError> {

View File

@ -4,9 +4,7 @@
// Allows macro expansion of `use ::solana_program::*` to work within this crate
extern crate self as solana_program;
pub mod account;
pub mod account_info;
pub mod account_utils;
pub mod bpf_loader;
pub mod bpf_loader_deprecated;
pub mod clock;

View File

@ -1,18 +1,2 @@
pub mod state;
pub mod utils;
pub use state::State;
use crate::{account, nonce::state::Versions};
use std::cell::RefCell;
pub fn create_account(lamports: u64) -> RefCell<account::Account> {
RefCell::new(
account::Account::new_data_with_space(
lamports,
&Versions::new_current(State::Uninitialized),
State::size(),
&crate::system_program::id(),
)
.expect("nonce_account"),
)
}

View File

@ -1,24 +1,8 @@
//! This account contains the current cluster rent
//!
pub use crate::epoch_schedule::EpochSchedule;
use crate::{account::Account, sysvar::Sysvar};
use crate::sysvar::Sysvar;
crate::declare_sysvar_id!("SysvarEpochSchedu1e111111111111111111111111", EpochSchedule);
impl Sysvar for EpochSchedule {}
pub fn create_account(lamports: u64, epoch_schedule: &EpochSchedule) -> Account {
epoch_schedule.create_account(lamports)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_create_account() {
let account = create_account(42, &EpochSchedule::default());
let epoch_schedule = EpochSchedule::from_account(&account).unwrap();
assert_eq!(epoch_schedule, EpochSchedule::default());
}
}

View File

@ -1,6 +1,6 @@
//! This account contains the current cluster fees
//!
use crate::{account::Account, fee_calculator::FeeCalculator, sysvar::Sysvar};
use crate::{fee_calculator::FeeCalculator, sysvar::Sysvar};
crate::declare_sysvar_id!("SysvarFees111111111111111111111111111111111", Fees);
@ -9,25 +9,12 @@ crate::declare_sysvar_id!("SysvarFees111111111111111111111111111111111", Fees);
pub struct Fees {
pub fee_calculator: FeeCalculator,
}
impl Fees {
pub fn new(fee_calculator: &FeeCalculator) -> Self {
Self {
fee_calculator: fee_calculator.clone(),
}
}
}
impl Sysvar for Fees {}
pub fn create_account(lamports: u64, fee_calculator: &FeeCalculator) -> Account {
Fees {
fee_calculator: fee_calculator.clone(),
}
.create_account(lamports)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_fees_create_account() {
let lamports = 42;
let account = create_account(lamports, &FeeCalculator::default());
let fees = Fees::from_account(&account).unwrap();
assert_eq!(fees.fee_calculator, FeeCalculator::default());
}
}

View File

@ -1,8 +1,6 @@
//! named accounts for synthesized data accounts for bank state, etc.
//!
use crate::{
account::Account, account_info::AccountInfo, program_error::ProgramError, pubkey::Pubkey,
};
use crate::{account_info::AccountInfo, program_error::ProgramError, pubkey::Pubkey};
pub mod clock;
pub mod epoch_schedule;
@ -63,12 +61,6 @@ pub trait Sysvar:
fn size_of() -> usize {
bincode::serialized_size(&Self::default()).unwrap() as usize
}
fn from_account(account: &Account) -> Option<Self> {
bincode::deserialize(&account.data).ok()
}
fn to_account(&self, account: &mut Account) -> Option<()> {
bincode::serialize_into(&mut account.data[..], self).ok()
}
fn from_account_info(account_info: &AccountInfo) -> Result<Self, ProgramError> {
if !Self::check_id(account_info.unsigned_key()) {
return Err(ProgramError::InvalidArgument);
@ -78,12 +70,6 @@ pub trait Sysvar:
fn to_account_info(&self, account_info: &mut AccountInfo) -> Option<()> {
bincode::serialize_into(&mut account_info.data.borrow_mut()[..], self).ok()
}
fn create_account(&self, lamports: u64) -> Account {
let data_len = Self::size_of().max(bincode::serialized_size(self).unwrap() as usize);
let mut account = Account::new(lamports, data_len, &id());
self.to_account(&mut account).unwrap();
account
}
}
#[cfg(test)]

View File

@ -1,5 +1,4 @@
use crate::{
account::Account,
declare_sysvar_id,
fee_calculator::FeeCalculator,
hash::{hash, Hash},
@ -88,6 +87,11 @@ impl<'a> FromIterator<IterItem<'a>> for RecentBlockhashes {
pub struct IntoIterSorted<T> {
inner: BinaryHeap<T>,
}
impl<T> IntoIterSorted<T> {
pub fn new(binary_heap: BinaryHeap<T>) -> Self {
Self { inner: binary_heap }
}
}
impl<T: Ord> Iterator for IntoIterSorted<T> {
type Item = T;
@ -118,30 +122,6 @@ impl Deref for RecentBlockhashes {
}
}
pub fn create_account(lamports: u64) -> Account {
RecentBlockhashes::default().create_account(lamports)
}
pub fn update_account<'a, I>(account: &mut Account, recent_blockhash_iter: I) -> Option<()>
where
I: IntoIterator<Item = IterItem<'a>>,
{
let sorted = BinaryHeap::from_iter(recent_blockhash_iter);
let sorted_iter = IntoIterSorted { inner: sorted };
let recent_blockhash_iter = sorted_iter.take(MAX_ENTRIES);
let recent_blockhashes = RecentBlockhashes::from_iter(recent_blockhash_iter);
recent_blockhashes.to_account(account)
}
pub fn create_account_with_data<'a, I>(lamports: u64, recent_blockhash_iter: I) -> Account
where
I: IntoIterator<Item = IterItem<'a>>,
{
let mut account = create_account(lamports);
update_account(&mut account, recent_blockhash_iter).unwrap();
account
}
pub fn create_test_recent_blockhashes(start: usize) -> RecentBlockhashes {
let blocks: Vec<_> = (start..start + MAX_ENTRIES)
.map(|i| {
@ -162,9 +142,7 @@ pub fn create_test_recent_blockhashes(start: usize) -> RecentBlockhashes {
#[cfg(test)]
mod tests {
use super::*;
use crate::{clock::MAX_PROCESSING_AGE, hash::HASH_BYTES};
use rand::seq::SliceRandom;
use rand::thread_rng;
use crate::clock::MAX_PROCESSING_AGE;
#[test]
#[allow(clippy::assertions_on_constants)]
@ -182,72 +160,4 @@ mod tests {
RecentBlockhashes::size_of()
);
}
#[test]
fn test_create_account_empty() {
let account = create_account_with_data(42, vec![].into_iter());
let recent_blockhashes = RecentBlockhashes::from_account(&account).unwrap();
assert_eq!(recent_blockhashes, RecentBlockhashes::default());
}
#[test]
fn test_create_account_full() {
let def_hash = Hash::default();
let def_fees = FeeCalculator::default();
let account = create_account_with_data(
42,
vec![IterItem(0u64, &def_hash, &def_fees); MAX_ENTRIES].into_iter(),
);
let recent_blockhashes = RecentBlockhashes::from_account(&account).unwrap();
assert_eq!(recent_blockhashes.len(), MAX_ENTRIES);
}
#[test]
fn test_create_account_truncate() {
let def_hash = Hash::default();
let def_fees = FeeCalculator::default();
let account = create_account_with_data(
42,
vec![IterItem(0u64, &def_hash, &def_fees); MAX_ENTRIES + 1].into_iter(),
);
let recent_blockhashes = RecentBlockhashes::from_account(&account).unwrap();
assert_eq!(recent_blockhashes.len(), MAX_ENTRIES);
}
#[test]
fn test_create_account_unsorted() {
let def_fees = FeeCalculator::default();
let mut unsorted_blocks: Vec<_> = (0..MAX_ENTRIES)
.map(|i| {
(i as u64, {
// create hash with visibly recognizable ordering
let mut h = [0; HASH_BYTES];
h[HASH_BYTES - 1] = i as u8;
Hash::new(&h)
})
})
.collect();
unsorted_blocks.shuffle(&mut thread_rng());
let account = create_account_with_data(
42,
unsorted_blocks
.iter()
.map(|(i, hash)| IterItem(*i, hash, &def_fees)),
);
let recent_blockhashes = RecentBlockhashes::from_account(&account).unwrap();
let mut unsorted_recent_blockhashes: Vec<_> = unsorted_blocks
.iter()
.map(|(i, hash)| IterItem(*i, hash, &def_fees))
.collect();
unsorted_recent_blockhashes.sort();
unsorted_recent_blockhashes.reverse();
let expected_recent_blockhashes: Vec<_> = (unsorted_recent_blockhashes
.into_iter()
.map(|IterItem(_, b, f)| Entry::new(b, f)))
.collect();
assert_eq!(*recent_blockhashes, expected_recent_blockhashes);
}
}

View File

@ -2,25 +2,8 @@
//!
pub use crate::rent::Rent;
use crate::{account::Account, sysvar::Sysvar};
use crate::sysvar::Sysvar;
crate::declare_sysvar_id!("SysvarRent111111111111111111111111111111111", Rent);
impl Sysvar for Rent {}
pub fn create_account(lamports: u64, rent: &Rent) -> Account {
rent.create_account(lamports)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_rent_create_account() {
let lamports = 42;
let account = create_account(lamports, &Rent::default());
let rent = Rent::from_account(&account).unwrap();
assert_eq!(rent, Rent::default());
}
}

View File

@ -1,6 +1,6 @@
//! DEPRECATED: This sysvar can be removed once the pico-inflation feature is enabled
//!
use crate::{account::Account, sysvar::Sysvar};
use crate::sysvar::Sysvar;
crate::declare_sysvar_id!("SysvarRewards111111111111111111111111111111", Rewards);
@ -10,25 +10,13 @@ pub struct Rewards {
pub validator_point_value: f64,
pub unused: f64,
}
impl Rewards {
pub fn new(validator_point_value: f64) -> Self {
Self {
validator_point_value,
unused: 0.0,
}
}
}
impl Sysvar for Rewards {}
pub fn create_account(lamports: u64, validator_point_value: f64) -> Account {
Rewards {
validator_point_value,
unused: 0.0,
}
.create_account(lamports)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_create_account() {
let account = create_account(1, 0.0);
let rewards = Rewards::from_account(&account).unwrap();
assert_eq!(rewards, Rewards::default());
}
}

View File

@ -33,13 +33,4 @@ mod tests {
.unwrap() as usize
);
}
#[test]
fn test_create_account() {
let lamports = 42;
let account = SlotHashes::new(&[]).create_account(lamports);
assert_eq!(account.data.len(), SlotHashes::size_of());
let slot_hashes = SlotHashes::from_account(&account);
assert_eq!(slot_hashes, Some(SlotHashes::default()));
}
}

View File

@ -4,7 +4,7 @@
//!
pub use crate::stake_history::StakeHistory;
use crate::{account::Account, sysvar::Sysvar};
use crate::sysvar::Sysvar;
crate::declare_sysvar_id!("SysvarStakeHistory1111111111111111111111111", StakeHistory);
@ -16,10 +16,6 @@ impl Sysvar for StakeHistory {
}
}
pub fn create_account(lamports: u64, stake_history: &StakeHistory) -> Account {
stake_history.create_account(lamports)
}
#[cfg(test)]
mod tests {
use super::*;
@ -46,14 +42,7 @@ mod tests {
#[test]
fn test_create_account() {
let lamports = 42;
let account = StakeHistory::default().create_account(lamports);
assert_eq!(account.data.len(), StakeHistory::size_of());
let stake_history = StakeHistory::from_account(&account);
assert_eq!(stake_history, Some(StakeHistory::default()));
let mut stake_history = stake_history.unwrap();
let mut stake_history = StakeHistory::default();
for i in 0..MAX_ENTRIES as u64 + 1 {
stake_history.add(
i,
@ -73,10 +62,5 @@ mod tests {
..StakeHistoryEntry::default()
})
);
// verify the account can hold a full instance
assert_eq!(
StakeHistory::from_account(&stake_history.create_account(lamports)),
Some(stake_history)
);
}
}

View File

@ -1,9 +1,10 @@
use crate::{clock::Epoch, pubkey::Pubkey};
use solana_program::{account_info::AccountInfo, sysvar::Sysvar};
use std::{cell::RefCell, cmp, fmt, rc::Rc};
/// An Account with data that is stored on chain
#[repr(C)]
#[frozen_abi(digest = "Upy4zg4EXZTnY371b4JPrGTh2kLcYpRno2K2pvjbN4e")]
#[frozen_abi(digest = "727tKRcoDvPiAsXxfvfsUauvZ4tLSw2WSw4HQfRQJ9Xx")]
#[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Default, AbiExample)]
#[serde(rename_all = "camelCase")]
pub struct Account {
@ -109,3 +110,61 @@ impl Account {
bincode::serialize_into(&mut self.data[..], state)
}
}
/// Create an `Account` from a `Sysvar`.
pub fn create_account<S: Sysvar>(sysvar: &S, lamports: u64) -> Account {
let data_len = S::size_of().max(bincode::serialized_size(sysvar).unwrap() as usize);
let mut account = Account::new(lamports, data_len, &solana_program::sysvar::id());
to_account::<S>(sysvar, &mut account).unwrap();
account
}
/// Create a `Sysvar` from an `Account`'s data.
pub fn from_account<S: Sysvar>(account: &Account) -> Option<S> {
bincode::deserialize(&account.data).ok()
}
/// Serialize a `Sysvar` into an `Account`'s data.
pub fn to_account<S: Sysvar>(sysvar: &S, account: &mut Account) -> Option<()> {
bincode::serialize_into(&mut account.data[..], sysvar).ok()
}
/// Return the information required to construct an `AccountInfo`. Used by the
/// `AccountInfo` conversion implementations.
impl solana_program::account_info::Account for Account {
fn get(&mut self) -> (&mut u64, &mut [u8], &Pubkey, bool, Epoch) {
(
&mut self.lamports,
&mut self.data,
&self.owner,
self.executable,
self.rent_epoch,
)
}
}
/// Create `AccountInfo`s
pub fn create_account_infos(accounts: &mut [(Pubkey, Account)]) -> Vec<AccountInfo> {
accounts.iter_mut().map(Into::into).collect()
}
/// Create `AccountInfo`s
pub fn create_is_signer_account_infos<'a>(
accounts: &'a mut [(&'a Pubkey, bool, &'a mut Account)],
) -> Vec<AccountInfo<'a>> {
accounts
.iter_mut()
.map(|(key, is_signer, account)| {
AccountInfo::new(
key,
*is_signer,
false,
&mut account.lamports,
&mut account.data,
&account.owner,
account.executable,
account.rent_epoch,
)
})
.collect()
}

View File

@ -61,7 +61,7 @@ impl FromStr for ClusterType {
}
}
#[frozen_abi(digest = "BAfWTFBwzed5FYCGAyMDq4HLsoZNTp8dZx2bqtYTCmGZ")]
#[frozen_abi(digest = "VxfEg5DXq5czYouMdcCbqDzUE8jGi3iSDSjzrrWp5iG")]
#[derive(Serialize, Deserialize, Debug, Clone, AbiExample)]
pub struct GenesisConfig {
/// when the network (bootstrap validator) was started relative to the UNIX Epoch

View File

@ -1,11 +1,8 @@
use solana_program::{
account::Account,
use crate::{
account::{from_account, Account},
account_utils::{State, StateMut},
clock::Epoch,
instruction::InstructionError,
pubkey::Pubkey,
sysvar::Sysvar,
};
use solana_program::{clock::Epoch, instruction::InstructionError, pubkey::Pubkey, sysvar::Sysvar};
use std::{
cell::{Ref, RefCell, RefMut},
iter::FromIterator,
@ -215,13 +212,16 @@ pub fn from_keyed_account<S: Sysvar>(
if !S::check_id(keyed_account.unsigned_key()) {
return Err(InstructionError::InvalidArgument);
}
S::from_account(&*keyed_account.try_account_ref()?).ok_or(InstructionError::InvalidArgument)
from_account::<S>(&*keyed_account.try_account_ref()?).ok_or(InstructionError::InvalidArgument)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::pubkey::Pubkey;
use crate::{
account::{create_account, to_account},
pubkey::Pubkey,
};
use std::cell::RefCell;
#[repr(C)]
@ -243,13 +243,13 @@ mod tests {
let key = crate::keyed_account::tests::id();
let wrong_key = Pubkey::new_unique();
let account = test_sysvar.create_account(42);
let test_sysvar = TestSysvar::from_account(&account).unwrap();
let account = create_account(&test_sysvar, 42);
let test_sysvar = from_account::<TestSysvar>(&account).unwrap();
assert_eq!(test_sysvar, TestSysvar::default());
let mut account = Account::new(42, TestSysvar::size_of(), &key);
test_sysvar.to_account(&mut account).unwrap();
let test_sysvar = TestSysvar::from_account(&account).unwrap();
to_account(&test_sysvar, &mut account).unwrap();
let test_sysvar = from_account::<TestSysvar>(&account).unwrap();
assert_eq!(test_sysvar, TestSysvar::default());
let account = RefCell::new(account);

View File

@ -6,6 +6,8 @@ extern crate self as solana_sdk;
pub use solana_program::*;
pub mod account;
pub mod account_utils;
pub mod builtins;
pub mod client;
pub mod commitment_config;
@ -21,11 +23,13 @@ pub mod inflation;
pub mod keyed_account;
pub mod log;
pub mod native_loader;
pub mod nonce_account;
pub mod nonce_keyed_account;
pub mod packet;
pub mod poh_config;
pub mod program_utils;
pub mod pubkey;
pub mod recent_blockhashes_account;
pub mod rpc_port;
pub mod secp256k1;
pub mod shred_version;

View File

@ -5,6 +5,19 @@ use crate::{
hash::Hash,
nonce::{state::Versions, State},
};
use std::cell::RefCell;
pub fn create_account(lamports: u64) -> RefCell<Account> {
RefCell::new(
Account::new_data_with_space(
lamports,
&Versions::new_current(State::Uninitialized),
State::size(),
&crate::system_program::id(),
)
.expect("nonce_account"),
)
}
pub fn verify_nonce_account(acc: &Account, hash: &Hash) -> bool {
match StateMut::<Versions>::state(acc).map(|v| v.convert_to_current()) {

View File

@ -1,6 +1,8 @@
use crate::keyed_account::KeyedAccount;
use crate::{
account_utils::State as AccountUtilsState, keyed_account::KeyedAccount,
nonce_account::create_account,
};
use solana_program::{
account_utils::State as AccountUtilsState,
instruction::InstructionError,
nonce::{self, state::Versions, State},
pubkey::Pubkey,
@ -162,7 +164,7 @@ where
F: Fn(&KeyedAccount),
{
let pubkey = Pubkey::new_unique();
let account = solana_program::nonce::create_account(lamports);
let account = create_account(lamports);
let keyed_account = KeyedAccount::new(&pubkey, signer, &account);
f(&keyed_account)
}
@ -174,10 +176,11 @@ mod test {
account_utils::State as AccountUtilsState,
keyed_account::KeyedAccount,
nonce::{self, State},
nonce_account::verify_nonce_account,
system_instruction::NonceError,
sysvar::recent_blockhashes::{create_test_recent_blockhashes, RecentBlockhashes},
};
use solana_program::{hash::Hash, nonce::utils::verify_nonce_account};
use solana_program::hash::Hash;
use std::iter::FromIterator;
#[test]

View File

@ -0,0 +1,105 @@
use crate::account::{create_account, to_account, Account};
use solana_program::sysvar::recent_blockhashes::{
IntoIterSorted, IterItem, RecentBlockhashes, MAX_ENTRIES,
};
use std::{collections::BinaryHeap, iter::FromIterator};
pub fn update_account<'a, I>(account: &mut Account, recent_blockhash_iter: I) -> Option<()>
where
I: IntoIterator<Item = IterItem<'a>>,
{
let sorted = BinaryHeap::from_iter(recent_blockhash_iter);
let sorted_iter = IntoIterSorted::new(sorted);
let recent_blockhash_iter = sorted_iter.take(MAX_ENTRIES);
let recent_blockhashes = RecentBlockhashes::from_iter(recent_blockhash_iter);
to_account(&recent_blockhashes, account)
}
pub fn create_account_with_data<'a, I>(lamports: u64, recent_blockhash_iter: I) -> Account
where
I: IntoIterator<Item = IterItem<'a>>,
{
let mut account = create_account::<RecentBlockhashes>(&RecentBlockhashes::default(), lamports);
update_account(&mut account, recent_blockhash_iter).unwrap();
account
}
#[cfg(test)]
mod tests {
use super::*;
use crate::account::from_account;
use rand::{seq::SliceRandom, thread_rng};
use solana_program::{
fee_calculator::FeeCalculator,
hash::{Hash, HASH_BYTES},
sysvar::recent_blockhashes::Entry,
};
#[test]
fn test_create_account_empty() {
let account = create_account_with_data(42, vec![].into_iter());
let recent_blockhashes = from_account::<RecentBlockhashes>(&account).unwrap();
assert_eq!(recent_blockhashes, RecentBlockhashes::default());
}
#[test]
fn test_create_account_full() {
let def_hash = Hash::default();
let def_fees = FeeCalculator::default();
let account = create_account_with_data(
42,
vec![IterItem(0u64, &def_hash, &def_fees); MAX_ENTRIES].into_iter(),
);
let recent_blockhashes = from_account::<RecentBlockhashes>(&account).unwrap();
assert_eq!(recent_blockhashes.len(), MAX_ENTRIES);
}
#[test]
fn test_create_account_truncate() {
let def_hash = Hash::default();
let def_fees = FeeCalculator::default();
let account = create_account_with_data(
42,
vec![IterItem(0u64, &def_hash, &def_fees); MAX_ENTRIES + 1].into_iter(),
);
let recent_blockhashes = from_account::<RecentBlockhashes>(&account).unwrap();
assert_eq!(recent_blockhashes.len(), MAX_ENTRIES);
}
#[test]
fn test_create_account_unsorted() {
let def_fees = FeeCalculator::default();
let mut unsorted_blocks: Vec<_> = (0..MAX_ENTRIES)
.map(|i| {
(i as u64, {
// create hash with visibly recognizable ordering
let mut h = [0; HASH_BYTES];
h[HASH_BYTES - 1] = i as u8;
Hash::new(&h)
})
})
.collect();
unsorted_blocks.shuffle(&mut thread_rng());
let account = create_account_with_data(
42,
unsorted_blocks
.iter()
.map(|(i, hash)| IterItem(*i, hash, &def_fees)),
);
let recent_blockhashes = from_account::<RecentBlockhashes>(&account).unwrap();
let mut unsorted_recent_blockhashes: Vec<_> = unsorted_blocks
.iter()
.map(|(i, hash)| IterItem(*i, hash, &def_fees))
.collect();
unsorted_recent_blockhashes.sort();
unsorted_recent_blockhashes.reverse();
let expected_recent_blockhashes: Vec<_> = (unsorted_recent_blockhashes
.into_iter()
.map(|IterItem(_, b, f)| Entry::new(b, f)))
.collect();
assert_eq!(*recent_blockhashes, expected_recent_blockhashes);
}
}