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
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
38 changed files with 460 additions and 459 deletions

View File

@ -212,15 +212,14 @@ pub struct UiStakeHistoryEntry {
mod test { mod test {
use super::*; use super::*;
use solana_sdk::{ use solana_sdk::{
fee_calculator::FeeCalculator, account::create_account, fee_calculator::FeeCalculator, hash::Hash,
hash::Hash, sysvar::recent_blockhashes::IterItem,
sysvar::{recent_blockhashes::IterItem, Sysvar},
}; };
use std::iter::FromIterator; use std::iter::FromIterator;
#[test] #[test]
fn test_parse_sysvars() { fn test_parse_sysvars() {
let clock_sysvar = Clock::default().create_account(1); let clock_sysvar = create_account(&Clock::default(), 1);
assert_eq!( assert_eq!(
parse_sysvar(&clock_sysvar.data, &sysvar::clock::id()).unwrap(), parse_sysvar(&clock_sysvar.data, &sysvar::clock::id()).unwrap(),
SysvarAccountType::Clock(UiClock::default()), SysvarAccountType::Clock(UiClock::default()),
@ -233,13 +232,13 @@ mod test {
first_normal_epoch: 1, first_normal_epoch: 1,
first_normal_slot: 12, first_normal_slot: 12,
}; };
let epoch_schedule_sysvar = epoch_schedule.create_account(1); let epoch_schedule_sysvar = create_account(&epoch_schedule, 1);
assert_eq!( assert_eq!(
parse_sysvar(&epoch_schedule_sysvar.data, &sysvar::epoch_schedule::id()).unwrap(), parse_sysvar(&epoch_schedule_sysvar.data, &sysvar::epoch_schedule::id()).unwrap(),
SysvarAccountType::EpochSchedule(epoch_schedule), SysvarAccountType::EpochSchedule(epoch_schedule),
); );
let fees_sysvar = Fees::default().create_account(1); let fees_sysvar = create_account(&Fees::default(), 1);
assert_eq!( assert_eq!(
parse_sysvar(&fees_sysvar.data, &sysvar::fees::id()).unwrap(), parse_sysvar(&fees_sysvar.data, &sysvar::fees::id()).unwrap(),
SysvarAccountType::Fees(UiFees::default()), SysvarAccountType::Fees(UiFees::default()),
@ -251,7 +250,7 @@ mod test {
}; };
let recent_blockhashes = let recent_blockhashes =
RecentBlockhashes::from_iter(vec![IterItem(0, &hash, &fee_calculator)].into_iter()); RecentBlockhashes::from_iter(vec![IterItem(0, &hash, &fee_calculator)].into_iter());
let recent_blockhashes_sysvar = recent_blockhashes.create_account(1); let recent_blockhashes_sysvar = create_account(&recent_blockhashes, 1);
assert_eq!( assert_eq!(
parse_sysvar( parse_sysvar(
&recent_blockhashes_sysvar.data, &recent_blockhashes_sysvar.data,
@ -269,13 +268,13 @@ mod test {
exemption_threshold: 2.0, exemption_threshold: 2.0,
burn_percent: 5, burn_percent: 5,
}; };
let rent_sysvar = rent.create_account(1); let rent_sysvar = create_account(&rent, 1);
assert_eq!( assert_eq!(
parse_sysvar(&rent_sysvar.data, &sysvar::rent::id()).unwrap(), parse_sysvar(&rent_sysvar.data, &sysvar::rent::id()).unwrap(),
SysvarAccountType::Rent(rent.into()), SysvarAccountType::Rent(rent.into()),
); );
let rewards_sysvar = Rewards::default().create_account(1); let rewards_sysvar = create_account(&Rewards::default(), 1);
assert_eq!( assert_eq!(
parse_sysvar(&rewards_sysvar.data, &sysvar::rewards::id()).unwrap(), parse_sysvar(&rewards_sysvar.data, &sysvar::rewards::id()).unwrap(),
SysvarAccountType::Rewards(UiRewards::default()), SysvarAccountType::Rewards(UiRewards::default()),
@ -283,7 +282,7 @@ mod test {
let mut slot_hashes = SlotHashes::default(); let mut slot_hashes = SlotHashes::default();
slot_hashes.add(1, hash); slot_hashes.add(1, hash);
let slot_hashes_sysvar = slot_hashes.create_account(1); let slot_hashes_sysvar = create_account(&slot_hashes, 1);
assert_eq!( assert_eq!(
parse_sysvar(&slot_hashes_sysvar.data, &sysvar::slot_hashes::id()).unwrap(), parse_sysvar(&slot_hashes_sysvar.data, &sysvar::slot_hashes::id()).unwrap(),
SysvarAccountType::SlotHashes(vec![UiSlotHashEntry { SysvarAccountType::SlotHashes(vec![UiSlotHashEntry {
@ -294,7 +293,7 @@ mod test {
let mut slot_history = SlotHistory::default(); let mut slot_history = SlotHistory::default();
slot_history.add(42); slot_history.add(42);
let slot_history_sysvar = slot_history.create_account(1); let slot_history_sysvar = create_account(&slot_history, 1);
assert_eq!( assert_eq!(
parse_sysvar(&slot_history_sysvar.data, &sysvar::slot_history::id()).unwrap(), parse_sysvar(&slot_history_sysvar.data, &sysvar::slot_history::id()).unwrap(),
SysvarAccountType::SlotHistory(UiSlotHistory { SysvarAccountType::SlotHistory(UiSlotHistory {
@ -310,7 +309,7 @@ mod test {
deactivating: 3, deactivating: 3,
}; };
stake_history.add(1, stake_history_entry.clone()); stake_history.add(1, stake_history_entry.clone());
let stake_history_sysvar = stake_history.create_account(1); let stake_history_sysvar = create_account(&stake_history, 1);
assert_eq!( assert_eq!(
parse_sysvar(&stake_history_sysvar.data, &sysvar::stake_history::id()).unwrap(), parse_sysvar(&stake_history_sysvar.data, &sysvar::stake_history::id()).unwrap(),
SysvarAccountType::StakeHistory(vec![UiStakeHistoryEntry { SysvarAccountType::StakeHistory(vec![UiStakeHistoryEntry {

View File

@ -27,6 +27,7 @@ use solana_client::{
}; };
use solana_remote_wallet::remote_wallet::RemoteWalletManager; use solana_remote_wallet::remote_wallet::RemoteWalletManager;
use solana_sdk::{ use solana_sdk::{
account::from_account,
account_utils::StateMut, account_utils::StateMut,
clock::{self, Clock, Slot}, clock::{self, Clock, Slot},
commitment_config::CommitmentConfig, commitment_config::CommitmentConfig,
@ -38,8 +39,7 @@ use solana_sdk::{
system_instruction, system_program, system_instruction, system_program,
sysvar::{ sysvar::{
self, self,
stake_history::{self, StakeHistory}, stake_history::{self},
Sysvar,
}, },
transaction::Transaction, transaction::Transaction,
}; };
@ -624,7 +624,7 @@ pub fn process_cluster_date(rpc_client: &RpcClient, config: &CliConfig) -> Proce
let result = rpc_client let result = rpc_client
.get_account_with_commitment(&sysvar::clock::id(), CommitmentConfig::default())?; .get_account_with_commitment(&sysvar::clock::id(), CommitmentConfig::default())?;
if let Some(clock_account) = result.value { if let Some(clock_account) = result.value {
let clock: Clock = Sysvar::from_account(&clock_account).ok_or_else(|| { let clock: Clock = from_account(&clock_account).ok_or_else(|| {
CliError::RpcRequestError("Failed to deserialize clock sysvar".to_string()) CliError::RpcRequestError("Failed to deserialize clock sysvar".to_string())
})?; })?;
let block_time = CliBlockTime { let block_time = CliBlockTime {
@ -1341,12 +1341,12 @@ pub fn process_show_stakes(
.get_program_accounts_with_config(&solana_stake_program::id(), program_accounts_config)?; .get_program_accounts_with_config(&solana_stake_program::id(), program_accounts_config)?;
let stake_history_account = rpc_client.get_account(&stake_history::id())?; let stake_history_account = rpc_client.get_account(&stake_history::id())?;
let clock_account = rpc_client.get_account(&sysvar::clock::id())?; let clock_account = rpc_client.get_account(&sysvar::clock::id())?;
let clock: Clock = Sysvar::from_account(&clock_account).ok_or_else(|| { let clock: Clock = from_account(&clock_account).ok_or_else(|| {
CliError::RpcRequestError("Failed to deserialize clock sysvar".to_string()) CliError::RpcRequestError("Failed to deserialize clock sysvar".to_string())
})?; })?;
progress_bar.finish_and_clear(); progress_bar.finish_and_clear();
let stake_history = StakeHistory::from_account(&stake_history_account).ok_or_else(|| { let stake_history = from_account(&stake_history_account).ok_or_else(|| {
CliError::RpcRequestError("Failed to deserialize stake history".to_string()) CliError::RpcRequestError("Failed to deserialize stake history".to_string())
})?; })?;

View File

@ -580,6 +580,7 @@ mod tests {
fee_calculator::FeeCalculator, fee_calculator::FeeCalculator,
hash::hash, hash::hash,
nonce::{self, state::Versions, State}, nonce::{self, state::Versions, State},
nonce_account,
signature::{read_keypair_file, write_keypair, Keypair, Signer}, signature::{read_keypair_file, write_keypair, Keypair, Signer},
system_program, system_program,
}; };
@ -891,7 +892,7 @@ mod tests {
#[test] #[test]
fn test_account_identity_ok() { fn test_account_identity_ok() {
let nonce_account = nonce::create_account(1).into_inner(); let nonce_account = nonce_account::create_account(1).into_inner();
assert_eq!(account_identity_ok(&nonce_account), Ok(())); assert_eq!(account_identity_ok(&nonce_account), Ok(()));
let system_account = Account::new(1, 0, &system_program::id()); let system_account = Account::new(1, 0, &system_program::id());
@ -910,7 +911,7 @@ mod tests {
#[test] #[test]
fn test_state_from_account() { fn test_state_from_account() {
let mut nonce_account = nonce::create_account(1).into_inner(); let mut nonce_account = nonce_account::create_account(1).into_inner();
assert_eq!(state_from_account(&nonce_account), Ok(State::Uninitialized)); assert_eq!(state_from_account(&nonce_account), Ok(State::Uninitialized));
let data = nonce::state::Data { let data = nonce::state::Data {
@ -935,7 +936,7 @@ mod tests {
#[test] #[test]
fn test_data_from_helpers() { fn test_data_from_helpers() {
let mut nonce_account = nonce::create_account(1).into_inner(); let mut nonce_account = nonce_account::create_account(1).into_inner();
let state = state_from_account(&nonce_account).unwrap(); let state = state_from_account(&nonce_account).unwrap();
assert_eq!( assert_eq!(
data_from_state(&state), data_from_state(&state),

View File

@ -32,6 +32,7 @@ use solana_client::{
}; };
use solana_remote_wallet::remote_wallet::RemoteWalletManager; use solana_remote_wallet::remote_wallet::RemoteWalletManager;
use solana_sdk::{ use solana_sdk::{
account::from_account,
account_utils::StateMut, account_utils::StateMut,
clock::{Clock, Epoch, Slot, UnixTimestamp, SECONDS_PER_DAY}, clock::{Clock, Epoch, Slot, UnixTimestamp, SECONDS_PER_DAY},
message::Message, message::Message,
@ -40,7 +41,6 @@ use solana_sdk::{
sysvar::{ sysvar::{
clock, clock,
stake_history::{self, StakeHistory}, stake_history::{self, StakeHistory},
Sysvar,
}, },
transaction::Transaction, transaction::Transaction,
}; };
@ -1696,12 +1696,11 @@ pub fn process_show_stake_account(
match stake_account.state() { match stake_account.state() {
Ok(stake_state) => { Ok(stake_state) => {
let stake_history_account = rpc_client.get_account(&stake_history::id())?; let stake_history_account = rpc_client.get_account(&stake_history::id())?;
let stake_history = let stake_history = from_account(&stake_history_account).ok_or_else(|| {
StakeHistory::from_account(&stake_history_account).ok_or_else(|| { CliError::RpcRequestError("Failed to deserialize stake history".to_string())
CliError::RpcRequestError("Failed to deserialize stake history".to_string()) })?;
})?;
let clock_account = rpc_client.get_account(&clock::id())?; let clock_account = rpc_client.get_account(&clock::id())?;
let clock: Clock = Sysvar::from_account(&clock_account).ok_or_else(|| { let clock: Clock = from_account(&clock_account).ok_or_else(|| {
CliError::RpcRequestError("Failed to deserialize clock sysvar".to_string()) CliError::RpcRequestError("Failed to deserialize clock sysvar".to_string())
})?; })?;
@ -1738,7 +1737,7 @@ pub fn process_show_stake_history(
use_lamports_unit: bool, use_lamports_unit: bool,
) -> ProcessResult { ) -> ProcessResult {
let stake_history_account = rpc_client.get_account(&stake_history::id())?; let stake_history_account = rpc_client.get_account(&stake_history::id())?;
let stake_history = StakeHistory::from_account(&stake_history_account).ok_or_else(|| { let stake_history = from_account::<StakeHistory>(&stake_history_account).ok_or_else(|| {
CliError::RpcRequestError("Failed to deserialize stake history".to_string()) CliError::RpcRequestError("Failed to deserialize stake history".to_string())
})?; })?;

View File

@ -55,7 +55,7 @@ use solana_sdk::{
signature::Signature, signature::Signature,
stake_history::StakeHistory, stake_history::StakeHistory,
system_instruction, system_instruction,
sysvar::{stake_history, Sysvar}, sysvar::stake_history,
transaction::{self, Transaction}, transaction::{self, Transaction},
}; };
use solana_stake_program::stake_state::StakeState; use solana_stake_program::stake_state::StakeState;
@ -1036,7 +1036,8 @@ impl JsonRpcRequestProcessor {
.get_account(&stake_history::id()) .get_account(&stake_history::id())
.ok_or_else(Error::internal_error)?; .ok_or_else(Error::internal_error)?;
let stake_history = let stake_history =
StakeHistory::from_account(&stake_history_account).ok_or_else(Error::internal_error)?; solana_sdk::account::from_account::<StakeHistory>(&stake_history_account)
.ok_or_else(Error::internal_error)?;
let (active, activating, deactivating) = let (active, activating, deactivating) =
delegation.stake_activating_and_deactivating(epoch, Some(&stake_history)); delegation.stake_activating_and_deactivating(epoch, Some(&stake_history));

View File

@ -5,7 +5,7 @@ use solana_runtime::{
bank::{Bank, HashAgeKind}, bank::{Bank, HashAgeKind},
transaction_utils::OrderedIterator, transaction_utils::OrderedIterator,
}; };
use solana_sdk::nonce; use solana_sdk::nonce_account;
use solana_transaction_status::{InnerInstructions, TransactionStatusMeta}; use solana_transaction_status::{InnerInstructions, TransactionStatusMeta};
use std::{ use std::{
sync::{ sync::{
@ -78,7 +78,7 @@ impl TransactionStatusService {
if Bank::can_commit(&status) && !transaction.signatures.is_empty() { if Bank::can_commit(&status) && !transaction.signatures.is_empty() {
let fee_calculator = match hash_age_kind { let fee_calculator = match hash_age_kind {
Some(HashAgeKind::DurableNonce(_, account)) => { Some(HashAgeKind::DurableNonce(_, account)) => {
nonce::utils::fee_calculator_of(&account) nonce_account::fee_calculator_of(&account)
} }
_ => bank.get_fee_calculator(&transaction.message().recent_blockhash), _ => bank.get_fee_calculator(&transaction.message().recent_blockhash),
} }

View File

@ -104,15 +104,13 @@ pub(crate) mod tests {
create_genesis_config, GenesisConfigInfo, BOOTSTRAP_VALIDATOR_LAMPORTS, create_genesis_config, GenesisConfigInfo, BOOTSTRAP_VALIDATOR_LAMPORTS,
}; };
use solana_sdk::{ use solana_sdk::{
account::from_account,
clock::Clock, clock::Clock,
instruction::Instruction, instruction::Instruction,
pubkey::Pubkey, pubkey::Pubkey,
signature::{Keypair, Signer}, signature::{Keypair, Signer},
signers::Signers, signers::Signers,
sysvar::{ sysvar::stake_history::{self, StakeHistory},
stake_history::{self, StakeHistory},
Sysvar,
},
transaction::Transaction, transaction::Transaction,
}; };
use solana_stake_program::{ use solana_stake_program::{
@ -244,7 +242,7 @@ pub(crate) mod tests {
let mut result: Vec<_> = epoch_stakes_and_lockouts(&bank, next_leader_schedule_epoch); let mut result: Vec<_> = epoch_stakes_and_lockouts(&bank, next_leader_schedule_epoch);
result.sort(); result.sort();
let stake_history = let stake_history =
StakeHistory::from_account(&bank.get_account(&stake_history::id()).unwrap()).unwrap(); from_account::<StakeHistory>(&bank.get_account(&stake_history::id()).unwrap()).unwrap();
let mut expected = vec![ let mut expected = vec![
(leader_stake.stake(bank.epoch(), Some(&stake_history)), None), (leader_stake.stake(bank.epoch(), Some(&stake_history)), None),
(other_stake.stake(bank.epoch(), Some(&stake_history)), None), (other_stake.stake(bank.epoch(), Some(&stake_history)), None),

View File

@ -211,7 +211,11 @@ fn bench_instruction_count_tuner(_bencher: &mut Bencher) {
let mut measure = Measure::start("tune"); let mut measure = Measure::start("tune");
let accounts = [RefCell::new(Account::new(1, 10000001, &solana_sdk::pubkey::new_rand()))]; let accounts = [RefCell::new(Account::new(
1,
10000001,
&solana_sdk::pubkey::new_rand(),
))];
let keys = [solana_sdk::pubkey::new_rand()]; let keys = [solana_sdk::pubkey::new_rand()];
let keyed_accounts: Vec<_> = keys let keyed_accounts: Vec<_> = keys
.iter() .iter()
@ -229,7 +233,8 @@ fn bench_instruction_count_tuner(_bencher: &mut Bencher) {
) )
.unwrap(); .unwrap();
let _ = vm.execute_program_metered(&mut serialized, &[], &[], instruction_meter.clone()); measure.stop(); let _ = vm.execute_program_metered(&mut serialized, &[], &[], instruction_meter.clone());
measure.stop();
assert_eq!( assert_eq!(
0, 0,
instruction_meter.get_remaining(), instruction_meter.get_remaining(),

View File

@ -524,9 +524,9 @@ mod tests {
use super::*; use super::*;
use bincode::serialize; use bincode::serialize;
use solana_sdk::{ use solana_sdk::{
account::Account, account::{self, Account},
rent::Rent, rent::Rent,
sysvar::{stake_history::StakeHistory, Sysvar}, sysvar::stake_history::StakeHistory,
}; };
use std::cell::RefCell; use std::cell::RefCell;
@ -540,15 +540,15 @@ mod tests {
.iter() .iter()
.map(|meta| { .map(|meta| {
RefCell::new(if sysvar::clock::check_id(&meta.pubkey) { RefCell::new(if sysvar::clock::check_id(&meta.pubkey) {
sysvar::clock::Clock::default().create_account(1) account::create_account(&sysvar::clock::Clock::default(), 1)
} else if sysvar::rewards::check_id(&meta.pubkey) { } else if sysvar::rewards::check_id(&meta.pubkey) {
sysvar::rewards::create_account(1, 0.0) account::create_account(&sysvar::rewards::Rewards::new(0.0), 1)
} else if sysvar::stake_history::check_id(&meta.pubkey) { } else if sysvar::stake_history::check_id(&meta.pubkey) {
sysvar::stake_history::create_account(1, &StakeHistory::default()) account::create_account(&StakeHistory::default(), 1)
} else if config::check_id(&meta.pubkey) { } else if config::check_id(&meta.pubkey) {
config::create_account(0, &config::Config::default()) config::create_account(0, &config::Config::default())
} else if sysvar::rent::check_id(&meta.pubkey) { } else if sysvar::rent::check_id(&meta.pubkey) {
sysvar::rent::create_account(1, &Rent::default()) account::create_account(&Rent::default(), 1)
} else { } else {
Account::default() Account::default()
}) })
@ -709,7 +709,7 @@ mod tests {
KeyedAccount::new( KeyedAccount::new(
&sysvar::rent::id(), &sysvar::rent::id(),
false, false,
&RefCell::new(sysvar::rent::create_account(0, &Rent::default())) &RefCell::new(account::create_account(&Rent::default(), 0))
) )
], ],
&serialize(&StakeInstruction::Initialize( &serialize(&StakeInstruction::Initialize(
@ -759,14 +759,15 @@ mod tests {
KeyedAccount::new( KeyedAccount::new(
&sysvar::clock::id(), &sysvar::clock::id(),
false, false,
&RefCell::new(sysvar::clock::Clock::default().create_account(1)) &RefCell::new(account::create_account(&sysvar::clock::Clock::default(), 1))
), ),
KeyedAccount::new( KeyedAccount::new(
&sysvar::stake_history::id(), &sysvar::stake_history::id(),
false, false,
&RefCell::new( &RefCell::new(account::create_account(
sysvar::stake_history::StakeHistory::default().create_account(1) &sysvar::stake_history::StakeHistory::default(),
) 1
))
), ),
KeyedAccount::new( KeyedAccount::new(
&config::id(), &config::id(),
@ -789,15 +790,15 @@ mod tests {
KeyedAccount::new( KeyedAccount::new(
&sysvar::rewards::id(), &sysvar::rewards::id(),
false, false,
&RefCell::new(sysvar::rewards::create_account(1, 0.0)) &RefCell::new(account::create_account(
&sysvar::rewards::Rewards::new(0.0),
1
))
), ),
KeyedAccount::new( KeyedAccount::new(
&sysvar::stake_history::id(), &sysvar::stake_history::id(),
false, false,
&RefCell::new(sysvar::stake_history::create_account( &RefCell::new(account::create_account(&StakeHistory::default(), 1,))
1,
&StakeHistory::default()
))
), ),
], ],
&serialize(&StakeInstruction::Withdraw(42)).unwrap(), &serialize(&StakeInstruction::Withdraw(42)).unwrap(),
@ -828,7 +829,10 @@ mod tests {
KeyedAccount::new( KeyedAccount::new(
&sysvar::rewards::id(), &sysvar::rewards::id(),
false, false,
&RefCell::new(sysvar::rewards::create_account(1, 0.0)) &RefCell::new(account::create_account(
&sysvar::rewards::Rewards::new(0.0),
1
))
), ),
], ],
&serialize(&StakeInstruction::Deactivate).unwrap(), &serialize(&StakeInstruction::Deactivate).unwrap(),

View File

@ -331,7 +331,10 @@ pub fn process_instruction(
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use solana_sdk::{account::Account, rent::Rent, sysvar::Sysvar}; use solana_sdk::{
account::{self, Account},
rent::Rent,
};
use std::cell::RefCell; use std::cell::RefCell;
// these are for 100% coverage in this file // these are for 100% coverage in this file
@ -350,11 +353,11 @@ mod tests {
.iter() .iter()
.map(|meta| { .map(|meta| {
RefCell::new(if sysvar::clock::check_id(&meta.pubkey) { RefCell::new(if sysvar::clock::check_id(&meta.pubkey) {
Clock::default().create_account(1) account::create_account(&Clock::default(), 1)
} else if sysvar::slot_hashes::check_id(&meta.pubkey) { } else if sysvar::slot_hashes::check_id(&meta.pubkey) {
SlotHashes::default().create_account(1) account::create_account(&SlotHashes::default(), 1)
} else if sysvar::rent::check_id(&meta.pubkey) { } else if sysvar::rent::check_id(&meta.pubkey) {
Rent::free().create_account(1) account::create_account(&Rent::free(), 1)
} else { } else {
Account::default() Account::default()
}) })

View File

@ -2,14 +2,12 @@ use crate::utils;
use log::*; use log::*;
use solana_client::rpc_client::RpcClient; use solana_client::rpc_client::RpcClient;
use solana_sdk::{ use solana_sdk::{
account::from_account,
clock::Epoch, clock::Epoch,
epoch_info::EpochInfo, epoch_info::EpochInfo,
genesis_config::GenesisConfig, genesis_config::GenesisConfig,
stake_history::StakeHistoryEntry, stake_history::StakeHistoryEntry,
sysvar::{ sysvar::stake_history::{self, StakeHistory},
stake_history::{self, StakeHistory},
Sysvar,
},
}; };
use solana_stake_program::config::Config as StakeConfig; use solana_stake_program::config::Config as StakeConfig;
use std::{thread::sleep, time::Duration}; use std::{thread::sleep, time::Duration};
@ -54,7 +52,7 @@ fn calculate_stake_warmup(mut stake_entry: StakeHistoryEntry, stake_config: &Sta
fn stake_history_entry(epoch: Epoch, rpc_client: &RpcClient) -> Option<StakeHistoryEntry> { fn stake_history_entry(epoch: Epoch, rpc_client: &RpcClient) -> Option<StakeHistoryEntry> {
let stake_history_account = rpc_client.get_account(&stake_history::id()).ok()?; let stake_history_account = rpc_client.get_account(&stake_history::id()).ok()?;
let stake_history = StakeHistory::from_account(&stake_history_account)?; let stake_history = from_account::<StakeHistory>(&stake_history_account)?;
stake_history.get(&epoch).cloned() stake_history.get(&epoch).cloned()
} }

View File

@ -22,7 +22,7 @@ use solana_sdk::{
genesis_config::ClusterType, genesis_config::ClusterType,
hash::Hash, hash::Hash,
message::Message, message::Message,
native_loader, nonce, native_loader, nonce, nonce_account,
pubkey::Pubkey, pubkey::Pubkey,
transaction::Result, transaction::Result,
transaction::{Transaction, TransactionError}, transaction::{Transaction, TransactionError},
@ -318,7 +318,7 @@ impl Accounts {
((_, tx), (Ok(()), hash_age_kind)) => { ((_, tx), (Ok(()), hash_age_kind)) => {
let fee_calculator = match hash_age_kind.as_ref() { let fee_calculator = match hash_age_kind.as_ref() {
Some(HashAgeKind::DurableNonce(_, account)) => { Some(HashAgeKind::DurableNonce(_, account)) => {
nonce::utils::fee_calculator_of(account) nonce_account::fee_calculator_of(account)
} }
_ => hash_queue _ => hash_queue
.get_fee_calculator(&tx.message().recent_blockhash) .get_fee_calculator(&tx.message().recent_blockhash)

View File

@ -5117,9 +5117,10 @@ pub mod tests {
#[test] #[test]
fn test_account_balance_for_capitalization_sysvar() { fn test_account_balance_for_capitalization_sysvar() {
use solana_sdk::sysvar::Sysvar; let normal_sysvar = solana_sdk::account::create_account(
&solana_sdk::slot_history::SlotHistory::default(),
let normal_sysvar = solana_sdk::slot_history::SlotHistory::default().create_account(1); 1,
);
assert_eq!( assert_eq!(
AccountsDB::account_balance_for_capitalization( AccountsDB::account_balance_for_capitalization(
normal_sysvar.lamports, normal_sysvar.lamports,

View File

@ -36,7 +36,7 @@ use solana_metrics::{
datapoint_debug, inc_new_counter_debug, inc_new_counter_error, inc_new_counter_info, datapoint_debug, inc_new_counter_debug, inc_new_counter_error, inc_new_counter_info,
}; };
use solana_sdk::{ use solana_sdk::{
account::Account, account::{create_account, from_account, Account},
clock::{ clock::{
Epoch, Slot, SlotCount, SlotIndex, UnixTimestamp, DEFAULT_TICKS_PER_SECOND, Epoch, Slot, SlotCount, SlotIndex, UnixTimestamp, DEFAULT_TICKS_PER_SECOND,
MAX_PROCESSING_AGE, MAX_RECENT_BLOCKHASHES, MAX_TRANSACTION_FORWARDING_DELAY, MAX_PROCESSING_AGE, MAX_RECENT_BLOCKHASHES, MAX_TRANSACTION_FORWARDING_DELAY,
@ -54,16 +54,17 @@ use solana_sdk::{
message::Message, message::Message,
native_loader, native_loader,
native_token::sol_to_lamports, native_token::sol_to_lamports,
nonce, nonce, nonce_account,
program_utils::limited_deserialize, program_utils::limited_deserialize,
pubkey::Pubkey, pubkey::Pubkey,
recent_blockhashes_account,
sanitize::Sanitize, sanitize::Sanitize,
signature::{Keypair, Signature}, signature::{Keypair, Signature},
slot_hashes::SlotHashes, slot_hashes::SlotHashes,
slot_history::SlotHistory, slot_history::SlotHistory,
stake_weighted_timestamp::{calculate_stake_weighted_timestamp, TIMESTAMP_SLOT_RANGE}, stake_weighted_timestamp::{calculate_stake_weighted_timestamp, TIMESTAMP_SLOT_RANGE},
system_transaction, system_transaction,
sysvar::{self, Sysvar}, sysvar::{self},
timing::years_as_slots, timing::years_as_slots,
transaction::{self, Result, Transaction, TransactionError}, transaction::{self, Result, Transaction, TransactionError},
}; };
@ -1086,10 +1087,8 @@ impl Bank {
} }
pub fn clock(&self) -> sysvar::clock::Clock { pub fn clock(&self) -> sysvar::clock::Clock {
sysvar::clock::Clock::from_account( from_account(&self.get_account(&sysvar::clock::id()).unwrap_or_default())
&self.get_account(&sysvar::clock::id()).unwrap_or_default(), .unwrap_or_default()
)
.unwrap_or_default()
} }
fn update_clock(&self) { fn update_clock(&self) {
@ -1117,7 +1116,7 @@ impl Bank {
unix_timestamp, unix_timestamp,
}; };
self.update_sysvar_account(&sysvar::clock::id(), |account| { self.update_sysvar_account(&sysvar::clock::id(), |account| {
clock.create_account(self.inherit_sysvar_account_balance(account)) create_account(&clock, self.inherit_sysvar_account_balance(account))
}); });
} }
@ -1125,10 +1124,10 @@ impl Bank {
self.update_sysvar_account(&sysvar::slot_history::id(), |account| { self.update_sysvar_account(&sysvar::slot_history::id(), |account| {
let mut slot_history = account let mut slot_history = account
.as_ref() .as_ref()
.map(|account| SlotHistory::from_account(&account).unwrap()) .map(|account| from_account::<SlotHistory>(&account).unwrap())
.unwrap_or_default(); .unwrap_or_default();
slot_history.add(self.slot()); slot_history.add(self.slot());
slot_history.create_account(self.inherit_sysvar_account_balance(account)) create_account(&slot_history, self.inherit_sysvar_account_balance(account))
}); });
} }
@ -1136,15 +1135,15 @@ impl Bank {
self.update_sysvar_account(&sysvar::slot_hashes::id(), |account| { self.update_sysvar_account(&sysvar::slot_hashes::id(), |account| {
let mut slot_hashes = account let mut slot_hashes = account
.as_ref() .as_ref()
.map(|account| SlotHashes::from_account(&account).unwrap()) .map(|account| from_account::<SlotHashes>(&account).unwrap())
.unwrap_or_default(); .unwrap_or_default();
slot_hashes.add(self.parent_slot, self.parent_hash); slot_hashes.add(self.parent_slot, self.parent_hash);
slot_hashes.create_account(self.inherit_sysvar_account_balance(account)) create_account(&slot_hashes, self.inherit_sysvar_account_balance(account))
}); });
} }
pub fn get_slot_history(&self) -> SlotHistory { pub fn get_slot_history(&self) -> SlotHistory {
SlotHistory::from_account(&self.get_account(&sysvar::slot_history::id()).unwrap()).unwrap() from_account(&self.get_account(&sysvar::slot_history::id()).unwrap()).unwrap()
} }
fn update_epoch_stakes(&mut self, leader_schedule_epoch: Epoch) { fn update_epoch_stakes(&mut self, leader_schedule_epoch: Epoch) {
@ -1179,27 +1178,27 @@ impl Bank {
fn update_fees(&self) { fn update_fees(&self) {
self.update_sysvar_account(&sysvar::fees::id(), |account| { self.update_sysvar_account(&sysvar::fees::id(), |account| {
sysvar::fees::create_account( create_account(
&sysvar::fees::Fees::new(&self.fee_calculator),
self.inherit_sysvar_account_balance(account), self.inherit_sysvar_account_balance(account),
&self.fee_calculator,
) )
}); });
} }
fn update_rent(&self) { fn update_rent(&self) {
self.update_sysvar_account(&sysvar::rent::id(), |account| { self.update_sysvar_account(&sysvar::rent::id(), |account| {
sysvar::rent::create_account( create_account(
self.inherit_sysvar_account_balance(account),
&self.rent_collector.rent, &self.rent_collector.rent,
self.inherit_sysvar_account_balance(account),
) )
}); });
} }
fn update_epoch_schedule(&self) { fn update_epoch_schedule(&self) {
self.update_sysvar_account(&sysvar::epoch_schedule::id(), |account| { self.update_sysvar_account(&sysvar::epoch_schedule::id(), |account| {
sysvar::epoch_schedule::create_account( create_account(
self.inherit_sysvar_account_balance(account),
&self.epoch_schedule, &self.epoch_schedule,
self.inherit_sysvar_account_balance(account),
) )
}); });
} }
@ -1210,9 +1209,9 @@ impl Bank {
} }
// if I'm the first Bank in an epoch, ensure stake_history is updated // if I'm the first Bank in an epoch, ensure stake_history is updated
self.update_sysvar_account(&sysvar::stake_history::id(), |account| { self.update_sysvar_account(&sysvar::stake_history::id(), |account| {
sysvar::stake_history::create_account( create_account::<sysvar::stake_history::StakeHistory>(
&self.stakes.read().unwrap().history(),
self.inherit_sysvar_account_balance(account), self.inherit_sysvar_account_balance(account),
self.stakes.read().unwrap().history(),
) )
}); });
} }
@ -1259,9 +1258,9 @@ impl Bank {
{ {
// this sysvar can be retired once `pico_inflation` is enabled on all clusters // this sysvar can be retired once `pico_inflation` is enabled on all clusters
self.update_sysvar_account(&sysvar::rewards::id(), |account| { self.update_sysvar_account(&sysvar::rewards::id(), |account| {
sysvar::rewards::create_account( create_account(
&sysvar::rewards::Rewards::new(validator_point_value),
self.inherit_sysvar_account_balance(account), self.inherit_sysvar_account_balance(account),
validator_point_value,
) )
}); });
} }
@ -1434,7 +1433,7 @@ impl Bank {
fn update_recent_blockhashes_locked(&self, locked_blockhash_queue: &BlockhashQueue) { fn update_recent_blockhashes_locked(&self, locked_blockhash_queue: &BlockhashQueue) {
self.update_sysvar_account(&sysvar::recent_blockhashes::id(), |account| { self.update_sysvar_account(&sysvar::recent_blockhashes::id(), |account| {
let recent_blockhash_iter = locked_blockhash_queue.get_recent_blockhashes(); let recent_blockhash_iter = locked_blockhash_queue.get_recent_blockhashes();
sysvar::recent_blockhashes::create_account_with_data( recent_blockhashes_account::create_account_with_data(
self.inherit_sysvar_account_balance(account), self.inherit_sysvar_account_balance(account),
recent_blockhash_iter, recent_blockhash_iter,
) )
@ -2063,7 +2062,7 @@ impl Bank {
.map(|acc| (*nonce_pubkey, acc)) .map(|acc| (*nonce_pubkey, acc))
}) })
.filter(|(_pubkey, nonce_account)| { .filter(|(_pubkey, nonce_account)| {
nonce::utils::verify_nonce_account(nonce_account, &tx.message().recent_blockhash) nonce_account::verify_nonce_account(nonce_account, &tx.message().recent_blockhash)
}) })
} }
@ -2520,7 +2519,7 @@ impl Bank {
.map(|((_, tx), (res, hash_age_kind))| { .map(|((_, tx), (res, hash_age_kind))| {
let (fee_calculator, is_durable_nonce) = match hash_age_kind { let (fee_calculator, is_durable_nonce) = match hash_age_kind {
Some(HashAgeKind::DurableNonce(_, account)) => { Some(HashAgeKind::DurableNonce(_, account)) => {
(nonce::utils::fee_calculator_of(account), true) (nonce_account::fee_calculator_of(account), true)
} }
_ => ( _ => (
hash_queue hash_queue
@ -4216,7 +4215,7 @@ mod tests {
); );
let rent_account = bank.get_account(&sysvar::rent::id()).unwrap(); let rent_account = bank.get_account(&sysvar::rent::id()).unwrap();
let rent = sysvar::rent::Rent::from_account(&rent_account).unwrap(); let rent = from_account::<sysvar::rent::Rent>(&rent_account).unwrap();
assert_eq!(rent.burn_percent, 5); assert_eq!(rent.burn_percent, 5);
assert_eq!(rent.exemption_threshold, 1.2); assert_eq!(rent.exemption_threshold, 1.2);
@ -5905,7 +5904,7 @@ mod tests {
let rewards = bank1 let rewards = bank1
.get_account(&sysvar::rewards::id()) .get_account(&sysvar::rewards::id())
.map(|account| Rewards::from_account(&account).unwrap()) .map(|account| from_account::<Rewards>(&account).unwrap())
.unwrap(); .unwrap();
// verify the stake and vote accounts are the right size // verify the stake and vote accounts are the right size
@ -7188,56 +7187,63 @@ mod tests {
let bank1 = Arc::new(Bank::new(&genesis_config)); let bank1 = Arc::new(Bank::new(&genesis_config));
bank1.update_sysvar_account(&dummy_clock_id, |optional_account| { bank1.update_sysvar_account(&dummy_clock_id, |optional_account| {
assert!(optional_account.is_none()); assert!(optional_account.is_none());
Clock {
slot: expected_previous_slot, create_account(
..Clock::default() &Clock {
} slot: expected_previous_slot,
.create_account(1) ..Clock::default()
},
1,
)
}); });
let current_account = bank1.get_account(&dummy_clock_id).unwrap(); let current_account = bank1.get_account(&dummy_clock_id).unwrap();
assert_eq!( assert_eq!(
expected_previous_slot, expected_previous_slot,
Clock::from_account(&current_account).unwrap().slot from_account::<Clock>(&current_account).unwrap().slot
); );
// Updating should increment the clock's slot // Updating should increment the clock's slot
let bank2 = Arc::new(Bank::new_from_parent(&bank1, &Pubkey::default(), 1)); let bank2 = Arc::new(Bank::new_from_parent(&bank1, &Pubkey::default(), 1));
bank2.update_sysvar_account(&dummy_clock_id, |optional_account| { bank2.update_sysvar_account(&dummy_clock_id, |optional_account| {
let slot = Clock::from_account(optional_account.as_ref().unwrap()) let slot = from_account::<Clock>(optional_account.as_ref().unwrap())
.unwrap() .unwrap()
.slot .slot
+ 1; + 1;
Clock { create_account(
slot, &Clock {
..Clock::default() slot,
} ..Clock::default()
.create_account(1) },
1,
)
}); });
let current_account = bank2.get_account(&dummy_clock_id).unwrap(); let current_account = bank2.get_account(&dummy_clock_id).unwrap();
assert_eq!( assert_eq!(
expected_next_slot, expected_next_slot,
Clock::from_account(&current_account).unwrap().slot from_account::<Clock>(&current_account).unwrap().slot
); );
// Updating again should give bank1's sysvar to the closure not bank2's. // Updating again should give bank1's sysvar to the closure not bank2's.
// Thus, assert with same expected_next_slot as previously // Thus, assert with same expected_next_slot as previously
bank2.update_sysvar_account(&dummy_clock_id, |optional_account| { bank2.update_sysvar_account(&dummy_clock_id, |optional_account| {
let slot = Clock::from_account(optional_account.as_ref().unwrap()) let slot = from_account::<Clock>(optional_account.as_ref().unwrap())
.unwrap() .unwrap()
.slot .slot
+ 1; + 1;
Clock { create_account(
slot, &Clock {
..Clock::default() slot,
} ..Clock::default()
.create_account(1) },
1,
)
}); });
let current_account = bank2.get_account(&dummy_clock_id).unwrap(); let current_account = bank2.get_account(&dummy_clock_id).unwrap();
assert_eq!( assert_eq!(
expected_next_slot, expected_next_slot,
Clock::from_account(&current_account).unwrap().slot from_account::<Clock>(&current_account).unwrap().slot
); );
} }
@ -7584,7 +7590,7 @@ mod tests {
let bank = Arc::new(Bank::new(&genesis_config)); let bank = Arc::new(Bank::new(&genesis_config));
let fees_account = bank.get_account(&sysvar::fees::id()).unwrap(); let fees_account = bank.get_account(&sysvar::fees::id()).unwrap();
let fees = Fees::from_account(&fees_account).unwrap(); let fees = from_account::<Fees>(&fees_account).unwrap();
assert_eq!( assert_eq!(
bank.fee_calculator.lamports_per_signature, bank.fee_calculator.lamports_per_signature,
fees.fee_calculator.lamports_per_signature fees.fee_calculator.lamports_per_signature
@ -7865,7 +7871,8 @@ mod tests {
for i in 1..5 { for i in 1..5 {
let bhq_account = bank.get_account(&sysvar::recent_blockhashes::id()).unwrap(); let bhq_account = bank.get_account(&sysvar::recent_blockhashes::id()).unwrap();
let recent_blockhashes = let recent_blockhashes =
sysvar::recent_blockhashes::RecentBlockhashes::from_account(&bhq_account).unwrap(); from_account::<sysvar::recent_blockhashes::RecentBlockhashes>(&bhq_account)
.unwrap();
// Check length // Check length
assert_eq!(recent_blockhashes.len(), i); assert_eq!(recent_blockhashes.len(), i);
let most_recent_hash = recent_blockhashes.iter().next().unwrap().blockhash; let most_recent_hash = recent_blockhashes.iter().next().unwrap().blockhash;
@ -7884,7 +7891,7 @@ mod tests {
let bhq_account = bank.get_account(&sysvar::recent_blockhashes::id()).unwrap(); let bhq_account = bank.get_account(&sysvar::recent_blockhashes::id()).unwrap();
let recent_blockhashes = let recent_blockhashes =
sysvar::recent_blockhashes::RecentBlockhashes::from_account(&bhq_account).unwrap(); from_account::<sysvar::recent_blockhashes::RecentBlockhashes>(&bhq_account).unwrap();
let sysvar_recent_blockhash = recent_blockhashes[0].blockhash; let sysvar_recent_blockhash = recent_blockhashes[0].blockhash;
let bank_last_blockhash = bank.last_blockhash(); let bank_last_blockhash = bank.last_blockhash();
@ -9735,7 +9742,7 @@ mod tests {
// Bank::new_from_parent should not adjust timestamp before feature activation // Bank::new_from_parent should not adjust timestamp before feature activation
let mut bank = new_from_parent(&Arc::new(bank)); let mut bank = new_from_parent(&Arc::new(bank));
let clock = let clock =
sysvar::clock::Clock::from_account(&bank.get_account(&sysvar::clock::id()).unwrap()) from_account::<sysvar::clock::Clock>(&bank.get_account(&sysvar::clock::id()).unwrap())
.unwrap(); .unwrap();
assert_eq!(clock.unix_timestamp, bank.unix_timestamp_from_genesis()); assert_eq!(clock.unix_timestamp, bank.unix_timestamp_from_genesis());
@ -9752,7 +9759,7 @@ mod tests {
// Now Bank::new_from_parent should adjust timestamp // Now Bank::new_from_parent should adjust timestamp
let bank = Arc::new(new_from_parent(&Arc::new(bank))); let bank = Arc::new(new_from_parent(&Arc::new(bank)));
let clock = let clock =
sysvar::clock::Clock::from_account(&bank.get_account(&sysvar::clock::id()).unwrap()) from_account::<sysvar::clock::Clock>(&bank.get_account(&sysvar::clock::id()).unwrap())
.unwrap(); .unwrap();
assert_eq!( assert_eq!(
clock.unix_timestamp, clock.unix_timestamp,

View File

@ -262,7 +262,7 @@ mod test_bank_serialize {
// These some what long test harness is required to freeze the ABI of // These some what long test harness is required to freeze the ABI of
// Bank's serialization due to versioned nature // Bank's serialization due to versioned nature
#[frozen_abi(digest = "7f8quGr9ia7Dg5o339uKrPd4bLesNVdPuKMLpGQ9c3SR")] #[frozen_abi(digest = "Giao4XJq9QgW78sqmT3nRMvENt4BgHXdzphCDGFPbXqW")]
#[derive(Serialize, AbiExample)] #[derive(Serialize, AbiExample)]
pub struct BankAbiTestWrapperFuture { pub struct BankAbiTestWrapperFuture {
#[serde(serialize_with = "wrapper_future")] #[serde(serialize_with = "wrapper_future")]

View File

@ -356,14 +356,14 @@ mod tests {
use crate::{bank::Bank, bank_client::BankClient}; use crate::{bank::Bank, bank_client::BankClient};
use bincode::serialize; use bincode::serialize;
use solana_sdk::{ use solana_sdk::{
account::Account, account::{self, Account},
client::SyncClient, client::SyncClient,
fee_calculator::FeeCalculator, fee_calculator::FeeCalculator,
genesis_config::create_genesis_config, genesis_config::create_genesis_config,
hash::{hash, Hash}, hash::{hash, Hash},
instruction::{AccountMeta, Instruction, InstructionError}, instruction::{AccountMeta, Instruction, InstructionError},
message::Message, message::Message,
nonce, nonce, nonce_account, recent_blockhashes_account,
signature::{Keypair, Signer}, signature::{Keypair, Signer},
system_instruction, system_program, sysvar, system_instruction, system_program, sysvar,
sysvar::recent_blockhashes::IterItem, sysvar::recent_blockhashes::IterItem,
@ -385,7 +385,7 @@ mod tests {
RefCell::new(Account::default()) RefCell::new(Account::default())
} }
fn create_default_recent_blockhashes_account() -> RefCell<Account> { fn create_default_recent_blockhashes_account() -> RefCell<Account> {
RefCell::new(sysvar::recent_blockhashes::create_account_with_data( RefCell::new(recent_blockhashes_account::create_account_with_data(
1, 1,
vec![ vec![
IterItem(0u64, &Hash::default(), &FeeCalculator::default()); IterItem(0u64, &Hash::default(), &FeeCalculator::default());
@ -395,7 +395,7 @@ mod tests {
)) ))
} }
fn create_default_rent_account() -> RefCell<Account> { fn create_default_rent_account() -> RefCell<Account> {
RefCell::new(sysvar::rent::create_account(1, &Rent::free())) RefCell::new(account::create_account(&Rent::free(), 1))
} }
#[test] #[test]
@ -1180,7 +1180,7 @@ mod tests {
RefCell::new(if sysvar::recent_blockhashes::check_id(&meta.pubkey) { RefCell::new(if sysvar::recent_blockhashes::check_id(&meta.pubkey) {
create_default_recent_blockhashes_account().into_inner() create_default_recent_blockhashes_account().into_inner()
} else if sysvar::rent::check_id(&meta.pubkey) { } else if sysvar::rent::check_id(&meta.pubkey) {
sysvar::rent::create_account(1, &Rent::free()) account::create_account(&Rent::free(), 1)
} else { } else {
Account::default() Account::default()
}) })
@ -1258,7 +1258,7 @@ mod tests {
#[test] #[test]
fn test_process_nonce_ix_ok() { fn test_process_nonce_ix_ok() {
let nonce_acc = nonce::create_account(1_000_000); let nonce_acc = nonce_account::create_account(1_000_000);
super::process_instruction( super::process_instruction(
&Pubkey::default(), &Pubkey::default(),
&[ &[
@ -1273,8 +1273,8 @@ mod tests {
&serialize(&SystemInstruction::InitializeNonceAccount(Pubkey::default())).unwrap(), &serialize(&SystemInstruction::InitializeNonceAccount(Pubkey::default())).unwrap(),
) )
.unwrap(); .unwrap();
let new_recent_blockhashes_account = let new_recent_blockhashes_account = RefCell::new(
RefCell::new(sysvar::recent_blockhashes::create_account_with_data( solana_sdk::recent_blockhashes_account::create_account_with_data(
1, 1,
vec![ vec![
IterItem( IterItem(
@ -1285,7 +1285,8 @@ mod tests {
sysvar::recent_blockhashes::MAX_ENTRIES sysvar::recent_blockhashes::MAX_ENTRIES
] ]
.into_iter(), .into_iter(),
)); ),
);
assert_eq!( assert_eq!(
super::process_instruction( super::process_instruction(
&Pubkey::default(), &Pubkey::default(),
@ -1370,7 +1371,11 @@ mod tests {
super::process_instruction( super::process_instruction(
&Pubkey::default(), &Pubkey::default(),
&[ &[
KeyedAccount::new(&Pubkey::default(), true, &nonce::create_account(1_000_000),), KeyedAccount::new(
&Pubkey::default(),
true,
&nonce_account::create_account(1_000_000),
),
KeyedAccount::new(&Pubkey::default(), true, &create_default_account()), KeyedAccount::new(&Pubkey::default(), true, &create_default_account()),
KeyedAccount::new( KeyedAccount::new(
&sysvar::recent_blockhashes::id(), &sysvar::recent_blockhashes::id(),
@ -1391,7 +1396,11 @@ mod tests {
super::process_instruction( super::process_instruction(
&Pubkey::default(), &Pubkey::default(),
&[ &[
KeyedAccount::new(&Pubkey::default(), true, &nonce::create_account(1_000_000),), KeyedAccount::new(
&Pubkey::default(),
true,
&nonce_account::create_account(1_000_000),
),
KeyedAccount::new(&Pubkey::default(), true, &create_default_account()), KeyedAccount::new(&Pubkey::default(), true, &create_default_account()),
KeyedAccount::new( KeyedAccount::new(
&sysvar::recent_blockhashes::id(), &sysvar::recent_blockhashes::id(),
@ -1426,7 +1435,7 @@ mod tests {
&[KeyedAccount::new( &[KeyedAccount::new(
&Pubkey::default(), &Pubkey::default(),
true, true,
&nonce::create_account(1_000_000), &nonce_account::create_account(1_000_000),
),], ),],
&serialize(&SystemInstruction::InitializeNonceAccount(Pubkey::default())).unwrap(), &serialize(&SystemInstruction::InitializeNonceAccount(Pubkey::default())).unwrap(),
), ),
@ -1440,7 +1449,11 @@ mod tests {
super::process_instruction( super::process_instruction(
&Pubkey::default(), &Pubkey::default(),
&[ &[
KeyedAccount::new(&Pubkey::default(), true, &nonce::create_account(1_000_000),), KeyedAccount::new(
&Pubkey::default(),
true,
&nonce_account::create_account(1_000_000),
),
KeyedAccount::new( KeyedAccount::new(
&sysvar::recent_blockhashes::id(), &sysvar::recent_blockhashes::id(),
false, false,
@ -1459,7 +1472,11 @@ mod tests {
super::process_instruction( super::process_instruction(
&Pubkey::default(), &Pubkey::default(),
&[ &[
KeyedAccount::new(&Pubkey::default(), true, &nonce::create_account(1_000_000),), KeyedAccount::new(
&Pubkey::default(),
true,
&nonce_account::create_account(1_000_000),
),
KeyedAccount::new( KeyedAccount::new(
&sysvar::recent_blockhashes::id(), &sysvar::recent_blockhashes::id(),
false, false,
@ -1479,7 +1496,11 @@ mod tests {
super::process_instruction( super::process_instruction(
&Pubkey::default(), &Pubkey::default(),
&[ &[
KeyedAccount::new(&Pubkey::default(), true, &nonce::create_account(1_000_000),), KeyedAccount::new(
&Pubkey::default(),
true,
&nonce_account::create_account(1_000_000),
),
KeyedAccount::new( KeyedAccount::new(
&sysvar::recent_blockhashes::id(), &sysvar::recent_blockhashes::id(),
false, false,
@ -1495,7 +1516,7 @@ mod tests {
#[test] #[test]
fn test_process_authorize_ix_ok() { fn test_process_authorize_ix_ok() {
let nonce_acc = nonce::create_account(1_000_000); let nonce_acc = nonce_account::create_account(1_000_000);
super::process_instruction( super::process_instruction(
&Pubkey::default(), &Pubkey::default(),
&[ &[
@ -1560,7 +1581,7 @@ mod tests {
#[test] #[test]
fn test_get_system_account_kind_uninitialized_nonce_account_fail() { fn test_get_system_account_kind_uninitialized_nonce_account_fail() {
assert_eq!( assert_eq!(
get_system_account_kind(&nonce::create_account(42).borrow()), get_system_account_kind(&nonce_account::create_account(42).borrow()),
None None
); );
} }

View File

@ -4,13 +4,14 @@ use solana_runtime::{
genesis_utils::{create_genesis_config_with_leader, GenesisConfigInfo}, genesis_utils::{create_genesis_config_with_leader, GenesisConfigInfo},
}; };
use solana_sdk::{ use solana_sdk::{
account::from_account,
account_utils::StateMut, account_utils::StateMut,
client::SyncClient, client::SyncClient,
message::Message, message::Message,
pubkey::Pubkey, pubkey::Pubkey,
signature::{Keypair, Signer}, signature::{Keypair, Signer},
system_instruction::SystemError, system_instruction::SystemError,
sysvar::{self, stake_history::StakeHistory, Sysvar}, sysvar::{self, stake_history::StakeHistory},
transaction::TransactionError, transaction::TransactionError,
}; };
use solana_stake_program::{ use solana_stake_program::{
@ -75,7 +76,7 @@ fn warmed_up(bank: &Bank, stake_pubkey: &Pubkey) -> bool {
== stake.stake( == stake.stake(
bank.epoch(), bank.epoch(),
Some( Some(
&StakeHistory::from_account( &from_account::<StakeHistory>(
&bank.get_account(&sysvar::stake_history::id()).unwrap(), &bank.get_account(&sysvar::stake_history::id()).unwrap(),
) )
.unwrap(), .unwrap(),
@ -89,7 +90,7 @@ fn get_staked(bank: &Bank, stake_pubkey: &Pubkey) -> u64 {
.stake( .stake(
bank.epoch(), bank.epoch(),
Some( Some(
&StakeHistory::from_account( &from_account::<StakeHistory>(
&bank.get_account(&sysvar::stake_history::id()).unwrap(), &bank.get_account(&sysvar::stake_history::id()).unwrap(),
) )
.unwrap(), .unwrap(),

View File

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

View File

@ -1,7 +1,10 @@
#![feature(test)] #![feature(test)]
extern crate 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; use test::Bencher;
#[bench] #[bench]
@ -9,8 +12,8 @@ fn bench_to_from_account(b: &mut Bencher) {
let mut slot_history = SlotHistory::default(); let mut slot_history = SlotHistory::default();
b.iter(|| { b.iter(|| {
let account = slot_history.create_account(0); let account = create_account(&slot_history, 0);
slot_history = SlotHistory::from_account(&account).unwrap(); 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::{ use std::{
cell::{Ref, RefCell, RefMut}, cell::{Ref, RefCell, RefMut},
cmp, fmt, cmp, fmt,
@ -148,76 +148,57 @@ impl<'a> AccountInfo<'a> {
} }
} }
impl<'a> From<(&'a Pubkey, &'a mut Account)> for AccountInfo<'a> { /// Constructs an `AccountInfo` from self, used in conversion implementations.
fn from((key, account): (&'a Pubkey, &'a mut Account)) -> Self { pub trait IntoAccountInfo<'a> {
Self::new( fn into_account_info(self) -> AccountInfo<'a>;
key, }
false, impl<'a, T: IntoAccountInfo<'a>> From<T> for AccountInfo<'a> {
false, fn from(src: T) -> Self {
&mut account.lamports, src.into_account_info()
&mut account.data, }
&account.owner, }
account.executable,
account.rent_epoch, /// 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> { /// Convert (&'a Pubkey, bool, &'a mut T) where T: Account into an
fn from((key, is_signer, account): (&'a Pubkey, bool, &'a mut Account)) -> Self { /// `AccountInfo`.
Self::new( impl<'a, T: Account> IntoAccountInfo<'a> for (&'a Pubkey, bool, &'a mut T) {
key, fn into_account_info(self) -> AccountInfo<'a> {
is_signer, let (key, is_signer, account) = self;
false, let (lamports, data, owner, executable, rent_epoch) = account.get();
&mut account.lamports, AccountInfo::new(
&mut account.data, key, is_signer, false, lamports, data, owner, executable, rent_epoch,
&account.owner,
account.executable,
account.rent_epoch,
) )
} }
} }
impl<'a> From<&'a mut (Pubkey, Account)> for AccountInfo<'a> { /// Convert &'a mut (Pubkey, T) where T: Account into an `AccountInfo`.
fn from((key, account): &'a mut (Pubkey, Account)) -> Self { impl<'a, T: Account> IntoAccountInfo<'a> for &'a mut (Pubkey, T) {
Self::new( fn into_account_info(self) -> AccountInfo<'a> {
key, let (ref key, account) = self;
false, let (lamports, data, owner, executable, rent_epoch) = account.get();
false, AccountInfo::new(
&mut account.lamports, key, false, false, lamports, data, owner, executable, rent_epoch,
&mut account.data,
&account.owner,
account.executable,
account.rent_epoch,
) )
} }
} }
pub fn create_account_infos(accounts: &mut [(Pubkey, Account)]) -> Vec<AccountInfo> { /// Return the next AccountInfo or a NotEnoughAccountKeys error.
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
pub fn next_account_info<'a, 'b, I: Iterator<Item = &'a AccountInfo<'b>>>( pub fn next_account_info<'a, 'b, I: Iterator<Item = &'a AccountInfo<'b>>>(
iter: &mut I, iter: &mut I,
) -> Result<I::Item, ProgramError> { ) -> Result<I::Item, ProgramError> {

View File

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

View File

@ -1,18 +1,2 @@
pub mod state; pub mod state;
pub mod utils;
pub use state::State; 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 //! This account contains the current cluster rent
//! //!
pub use crate::epoch_schedule::EpochSchedule; pub use crate::epoch_schedule::EpochSchedule;
use crate::{account::Account, sysvar::Sysvar}; use crate::sysvar::Sysvar;
crate::declare_sysvar_id!("SysvarEpochSchedu1e111111111111111111111111", EpochSchedule); crate::declare_sysvar_id!("SysvarEpochSchedu1e111111111111111111111111", EpochSchedule);
impl Sysvar for 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 //! 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); crate::declare_sysvar_id!("SysvarFees111111111111111111111111111111111", Fees);
@ -9,25 +9,12 @@ crate::declare_sysvar_id!("SysvarFees111111111111111111111111111111111", Fees);
pub struct Fees { pub struct Fees {
pub fee_calculator: FeeCalculator, pub fee_calculator: FeeCalculator,
} }
impl Fees {
pub fn new(fee_calculator: &FeeCalculator) -> Self {
Self {
fee_calculator: fee_calculator.clone(),
}
}
}
impl Sysvar for Fees {} 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. //! named accounts for synthesized data accounts for bank state, etc.
//! //!
use crate::{ use crate::{account_info::AccountInfo, program_error::ProgramError, pubkey::Pubkey};
account::Account, account_info::AccountInfo, program_error::ProgramError, pubkey::Pubkey,
};
pub mod clock; pub mod clock;
pub mod epoch_schedule; pub mod epoch_schedule;
@ -63,12 +61,6 @@ pub trait Sysvar:
fn size_of() -> usize { fn size_of() -> usize {
bincode::serialized_size(&Self::default()).unwrap() as 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> { fn from_account_info(account_info: &AccountInfo) -> Result<Self, ProgramError> {
if !Self::check_id(account_info.unsigned_key()) { if !Self::check_id(account_info.unsigned_key()) {
return Err(ProgramError::InvalidArgument); return Err(ProgramError::InvalidArgument);
@ -78,12 +70,6 @@ pub trait Sysvar:
fn to_account_info(&self, account_info: &mut AccountInfo) -> Option<()> { fn to_account_info(&self, account_info: &mut AccountInfo) -> Option<()> {
bincode::serialize_into(&mut account_info.data.borrow_mut()[..], self).ok() 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)] #[cfg(test)]

View File

@ -1,5 +1,4 @@
use crate::{ use crate::{
account::Account,
declare_sysvar_id, declare_sysvar_id,
fee_calculator::FeeCalculator, fee_calculator::FeeCalculator,
hash::{hash, Hash}, hash::{hash, Hash},
@ -88,6 +87,11 @@ impl<'a> FromIterator<IterItem<'a>> for RecentBlockhashes {
pub struct IntoIterSorted<T> { pub struct IntoIterSorted<T> {
inner: BinaryHeap<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> { impl<T: Ord> Iterator for IntoIterSorted<T> {
type Item = 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 { pub fn create_test_recent_blockhashes(start: usize) -> RecentBlockhashes {
let blocks: Vec<_> = (start..start + MAX_ENTRIES) let blocks: Vec<_> = (start..start + MAX_ENTRIES)
.map(|i| { .map(|i| {
@ -162,9 +142,7 @@ pub fn create_test_recent_blockhashes(start: usize) -> RecentBlockhashes {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::{clock::MAX_PROCESSING_AGE, hash::HASH_BYTES}; use crate::clock::MAX_PROCESSING_AGE;
use rand::seq::SliceRandom;
use rand::thread_rng;
#[test] #[test]
#[allow(clippy::assertions_on_constants)] #[allow(clippy::assertions_on_constants)]
@ -182,72 +160,4 @@ mod tests {
RecentBlockhashes::size_of() 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; pub use crate::rent::Rent;
use crate::{account::Account, sysvar::Sysvar}; use crate::sysvar::Sysvar;
crate::declare_sysvar_id!("SysvarRent111111111111111111111111111111111", Rent); crate::declare_sysvar_id!("SysvarRent111111111111111111111111111111111", Rent);
impl Sysvar for 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 //! 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); crate::declare_sysvar_id!("SysvarRewards111111111111111111111111111111", Rewards);
@ -10,25 +10,13 @@ pub struct Rewards {
pub validator_point_value: f64, pub validator_point_value: f64,
pub unused: 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 {} 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 .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; pub use crate::stake_history::StakeHistory;
use crate::{account::Account, sysvar::Sysvar}; use crate::sysvar::Sysvar;
crate::declare_sysvar_id!("SysvarStakeHistory1111111111111111111111111", StakeHistory); 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)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@ -46,14 +42,7 @@ mod tests {
#[test] #[test]
fn test_create_account() { fn test_create_account() {
let lamports = 42; let mut stake_history = StakeHistory::default();
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();
for i in 0..MAX_ENTRIES as u64 + 1 { for i in 0..MAX_ENTRIES as u64 + 1 {
stake_history.add( stake_history.add(
i, i,
@ -73,10 +62,5 @@ mod tests {
..StakeHistoryEntry::default() ..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 crate::{clock::Epoch, pubkey::Pubkey};
use solana_program::{account_info::AccountInfo, sysvar::Sysvar};
use std::{cell::RefCell, cmp, fmt, rc::Rc}; use std::{cell::RefCell, cmp, fmt, rc::Rc};
/// An Account with data that is stored on chain /// An Account with data that is stored on chain
#[repr(C)] #[repr(C)]
#[frozen_abi(digest = "Upy4zg4EXZTnY371b4JPrGTh2kLcYpRno2K2pvjbN4e")] #[frozen_abi(digest = "727tKRcoDvPiAsXxfvfsUauvZ4tLSw2WSw4HQfRQJ9Xx")]
#[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Default, AbiExample)] #[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Default, AbiExample)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct Account { pub struct Account {
@ -109,3 +110,61 @@ impl Account {
bincode::serialize_into(&mut self.data[..], state) 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)] #[derive(Serialize, Deserialize, Debug, Clone, AbiExample)]
pub struct GenesisConfig { pub struct GenesisConfig {
/// when the network (bootstrap validator) was started relative to the UNIX Epoch /// when the network (bootstrap validator) was started relative to the UNIX Epoch

View File

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

View File

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

View File

@ -5,6 +5,19 @@ use crate::{
hash::Hash, hash::Hash,
nonce::{state::Versions, State}, 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 { 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()) {

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