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

@ -1,111 +0,0 @@
use crate::{clock::Epoch, pubkey::Pubkey};
use std::{cell::RefCell, cmp, fmt, rc::Rc};
/// An Account with data that is stored on chain
#[repr(C)]
#[frozen_abi(digest = "Upy4zg4EXZTnY371b4JPrGTh2kLcYpRno2K2pvjbN4e")]
#[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Default, AbiExample)]
#[serde(rename_all = "camelCase")]
pub struct Account {
/// lamports in the account
pub lamports: u64,
/// data held in this account
#[serde(with = "serde_bytes")]
pub data: Vec<u8>,
/// the program that owns this account. If executable, the program that loads this account.
pub owner: Pubkey,
/// this account's data contains a loaded program (and is now read-only)
pub executable: bool,
/// the epoch at which this account will next owe rent
pub rent_epoch: Epoch,
}
impl fmt::Debug for Account {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let data_len = cmp::min(64, self.data.len());
let data_str = if data_len > 0 {
format!(" data: {}", hex::encode(self.data[..data_len].to_vec()))
} else {
"".to_string()
};
write!(
f,
"Account {{ lamports: {} data.len: {} owner: {} executable: {} rent_epoch: {}{} }}",
self.lamports,
self.data.len(),
self.owner,
self.executable,
self.rent_epoch,
data_str,
)
}
}
impl Account {
pub fn new(lamports: u64, space: usize, owner: &Pubkey) -> Self {
Self {
lamports,
data: vec![0u8; space],
owner: *owner,
..Self::default()
}
}
pub fn new_ref(lamports: u64, space: usize, owner: &Pubkey) -> Rc<RefCell<Self>> {
Rc::new(RefCell::new(Self::new(lamports, space, owner)))
}
pub fn new_data<T: serde::Serialize>(
lamports: u64,
state: &T,
owner: &Pubkey,
) -> Result<Self, bincode::Error> {
let data = bincode::serialize(state)?;
Ok(Self {
lamports,
data,
owner: *owner,
..Self::default()
})
}
pub fn new_ref_data<T: serde::Serialize>(
lamports: u64,
state: &T,
owner: &Pubkey,
) -> Result<RefCell<Self>, bincode::Error> {
Ok(RefCell::new(Self::new_data(lamports, state, owner)?))
}
pub fn new_data_with_space<T: serde::Serialize>(
lamports: u64,
state: &T,
space: usize,
owner: &Pubkey,
) -> Result<Self, bincode::Error> {
let mut account = Self::new(lamports, space, owner);
account.serialize_data(state)?;
Ok(account)
}
pub fn new_ref_data_with_space<T: serde::Serialize>(
lamports: u64,
state: &T,
space: usize,
owner: &Pubkey,
) -> Result<RefCell<Self>, bincode::Error> {
Ok(RefCell::new(Self::new_data_with_space(
lamports, state, space, owner,
)?))
}
pub fn deserialize_data<T: serde::de::DeserializeOwned>(&self) -> Result<T, bincode::Error> {
bincode::deserialize(&self.data)
}
pub fn serialize_data<T: serde::Serialize>(&mut self, state: &T) -> Result<(), bincode::Error> {
if bincode::serialized_size(state)? > self.data.len() as u64 {
return Err(Box::new(bincode::ErrorKind::SizeLimit));
}
bincode::serialize_into(&mut self.data[..], state)
}
}

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

@ -1,50 +0,0 @@
//! useful extras for Account state
use crate::{account::Account, instruction::InstructionError};
use bincode::ErrorKind;
/// Convenience trait to covert bincode errors to instruction errors.
pub trait StateMut<T> {
fn state(&self) -> Result<T, InstructionError>;
fn set_state(&mut self, state: &T) -> Result<(), InstructionError>;
}
pub trait State<T> {
fn state(&self) -> Result<T, InstructionError>;
fn set_state(&self, state: &T) -> Result<(), InstructionError>;
}
impl<T> StateMut<T> for Account
where
T: serde::Serialize + serde::de::DeserializeOwned,
{
fn state(&self) -> Result<T, InstructionError> {
self.deserialize_data()
.map_err(|_| InstructionError::InvalidAccountData)
}
fn set_state(&mut self, state: &T) -> Result<(), InstructionError> {
self.serialize_data(state).map_err(|err| match *err {
ErrorKind::SizeLimit => InstructionError::AccountDataTooSmall,
_ => InstructionError::GenericError,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{account::Account, pubkey::Pubkey};
#[test]
fn test_account_state() {
let state = 42u64;
assert!(Account::default().set_state(&state).is_err());
let res = Account::default().state() as Result<u64, InstructionError>;
assert!(res.is_err());
let mut account = Account::new(0, std::mem::size_of::<u64>(), &Pubkey::default());
assert!(account.set_state(&state).is_ok());
let stored_state: u64 = account.state().unwrap();
assert_eq!(stored_state, state);
}
}

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 +0,0 @@
use crate::{
account::Account,
account_utils::StateMut,
fee_calculator::FeeCalculator,
hash::Hash,
nonce::{state::Versions, State},
};
pub fn verify_nonce_account(acc: &Account, hash: &Hash) -> bool {
match StateMut::<Versions>::state(acc).map(|v| v.convert_to_current()) {
Ok(State::Initialized(ref data)) => *hash == data.blockhash,
_ => false,
}
}
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,
}
}

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)
);
}
}