diff --git a/account-decoder/src/parse_sysvar.rs b/account-decoder/src/parse_sysvar.rs index 755c3e4577..3c84acd99d 100644 --- a/account-decoder/src/parse_sysvar.rs +++ b/account-decoder/src/parse_sysvar.rs @@ -212,15 +212,14 @@ pub struct UiStakeHistoryEntry { mod test { use super::*; use solana_sdk::{ - fee_calculator::FeeCalculator, - hash::Hash, - sysvar::{recent_blockhashes::IterItem, Sysvar}, + account::create_account, fee_calculator::FeeCalculator, hash::Hash, + sysvar::recent_blockhashes::IterItem, }; use std::iter::FromIterator; #[test] fn test_parse_sysvars() { - let clock_sysvar = Clock::default().create_account(1); + let clock_sysvar = create_account(&Clock::default(), 1); assert_eq!( parse_sysvar(&clock_sysvar.data, &sysvar::clock::id()).unwrap(), SysvarAccountType::Clock(UiClock::default()), @@ -233,13 +232,13 @@ mod test { first_normal_epoch: 1, first_normal_slot: 12, }; - let epoch_schedule_sysvar = epoch_schedule.create_account(1); + let epoch_schedule_sysvar = create_account(&epoch_schedule, 1); assert_eq!( parse_sysvar(&epoch_schedule_sysvar.data, &sysvar::epoch_schedule::id()).unwrap(), SysvarAccountType::EpochSchedule(epoch_schedule), ); - let fees_sysvar = Fees::default().create_account(1); + let fees_sysvar = create_account(&Fees::default(), 1); assert_eq!( parse_sysvar(&fees_sysvar.data, &sysvar::fees::id()).unwrap(), SysvarAccountType::Fees(UiFees::default()), @@ -251,7 +250,7 @@ mod test { }; let recent_blockhashes = 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!( parse_sysvar( &recent_blockhashes_sysvar.data, @@ -269,13 +268,13 @@ mod test { exemption_threshold: 2.0, burn_percent: 5, }; - let rent_sysvar = rent.create_account(1); + let rent_sysvar = create_account(&rent, 1); assert_eq!( parse_sysvar(&rent_sysvar.data, &sysvar::rent::id()).unwrap(), SysvarAccountType::Rent(rent.into()), ); - let rewards_sysvar = Rewards::default().create_account(1); + let rewards_sysvar = create_account(&Rewards::default(), 1); assert_eq!( parse_sysvar(&rewards_sysvar.data, &sysvar::rewards::id()).unwrap(), SysvarAccountType::Rewards(UiRewards::default()), @@ -283,7 +282,7 @@ mod test { let mut slot_hashes = SlotHashes::default(); 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!( parse_sysvar(&slot_hashes_sysvar.data, &sysvar::slot_hashes::id()).unwrap(), SysvarAccountType::SlotHashes(vec![UiSlotHashEntry { @@ -294,7 +293,7 @@ mod test { let mut slot_history = SlotHistory::default(); slot_history.add(42); - let slot_history_sysvar = slot_history.create_account(1); + let slot_history_sysvar = create_account(&slot_history, 1); assert_eq!( parse_sysvar(&slot_history_sysvar.data, &sysvar::slot_history::id()).unwrap(), SysvarAccountType::SlotHistory(UiSlotHistory { @@ -310,7 +309,7 @@ mod test { deactivating: 3, }; 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!( parse_sysvar(&stake_history_sysvar.data, &sysvar::stake_history::id()).unwrap(), SysvarAccountType::StakeHistory(vec![UiStakeHistoryEntry { diff --git a/cli/src/cluster_query.rs b/cli/src/cluster_query.rs index fde831ea5f..691e104747 100644 --- a/cli/src/cluster_query.rs +++ b/cli/src/cluster_query.rs @@ -27,6 +27,7 @@ use solana_client::{ }; use solana_remote_wallet::remote_wallet::RemoteWalletManager; use solana_sdk::{ + account::from_account, account_utils::StateMut, clock::{self, Clock, Slot}, commitment_config::CommitmentConfig, @@ -38,8 +39,7 @@ use solana_sdk::{ system_instruction, system_program, sysvar::{ self, - stake_history::{self, StakeHistory}, - Sysvar, + stake_history::{self}, }, transaction::Transaction, }; @@ -624,7 +624,7 @@ pub fn process_cluster_date(rpc_client: &RpcClient, config: &CliConfig) -> Proce let result = rpc_client .get_account_with_commitment(&sysvar::clock::id(), CommitmentConfig::default())?; 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()) })?; 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)?; let stake_history_account = rpc_client.get_account(&stake_history::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()) })?; 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()) })?; diff --git a/cli/src/nonce.rs b/cli/src/nonce.rs index 5d9e964a5e..9a58d31383 100644 --- a/cli/src/nonce.rs +++ b/cli/src/nonce.rs @@ -580,6 +580,7 @@ mod tests { fee_calculator::FeeCalculator, hash::hash, nonce::{self, state::Versions, State}, + nonce_account, signature::{read_keypair_file, write_keypair, Keypair, Signer}, system_program, }; @@ -891,7 +892,7 @@ mod tests { #[test] 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(())); let system_account = Account::new(1, 0, &system_program::id()); @@ -910,7 +911,7 @@ mod tests { #[test] 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)); let data = nonce::state::Data { @@ -935,7 +936,7 @@ mod tests { #[test] 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(); assert_eq!( data_from_state(&state), diff --git a/cli/src/stake.rs b/cli/src/stake.rs index 17c6c116a5..7909f0d84e 100644 --- a/cli/src/stake.rs +++ b/cli/src/stake.rs @@ -32,6 +32,7 @@ use solana_client::{ }; use solana_remote_wallet::remote_wallet::RemoteWalletManager; use solana_sdk::{ + account::from_account, account_utils::StateMut, clock::{Clock, Epoch, Slot, UnixTimestamp, SECONDS_PER_DAY}, message::Message, @@ -40,7 +41,6 @@ use solana_sdk::{ sysvar::{ clock, stake_history::{self, StakeHistory}, - Sysvar, }, transaction::Transaction, }; @@ -1696,12 +1696,11 @@ pub fn process_show_stake_account( match stake_account.state() { Ok(stake_state) => { let stake_history_account = rpc_client.get_account(&stake_history::id())?; - let stake_history = - StakeHistory::from_account(&stake_history_account).ok_or_else(|| { - CliError::RpcRequestError("Failed to deserialize stake history".to_string()) - })?; + let stake_history = from_account(&stake_history_account).ok_or_else(|| { + CliError::RpcRequestError("Failed to deserialize stake history".to_string()) + })?; 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()) })?; @@ -1738,7 +1737,7 @@ pub fn process_show_stake_history( use_lamports_unit: bool, ) -> ProcessResult { 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::(&stake_history_account).ok_or_else(|| { CliError::RpcRequestError("Failed to deserialize stake history".to_string()) })?; diff --git a/core/src/rpc.rs b/core/src/rpc.rs index 11951b849a..be257d0148 100644 --- a/core/src/rpc.rs +++ b/core/src/rpc.rs @@ -55,7 +55,7 @@ use solana_sdk::{ signature::Signature, stake_history::StakeHistory, system_instruction, - sysvar::{stake_history, Sysvar}, + sysvar::stake_history, transaction::{self, Transaction}, }; use solana_stake_program::stake_state::StakeState; @@ -1036,7 +1036,8 @@ impl JsonRpcRequestProcessor { .get_account(&stake_history::id()) .ok_or_else(Error::internal_error)?; let stake_history = - StakeHistory::from_account(&stake_history_account).ok_or_else(Error::internal_error)?; + solana_sdk::account::from_account::(&stake_history_account) + .ok_or_else(Error::internal_error)?; let (active, activating, deactivating) = delegation.stake_activating_and_deactivating(epoch, Some(&stake_history)); diff --git a/core/src/transaction_status_service.rs b/core/src/transaction_status_service.rs index bc00e3bfa4..28dbdf73e6 100644 --- a/core/src/transaction_status_service.rs +++ b/core/src/transaction_status_service.rs @@ -5,7 +5,7 @@ use solana_runtime::{ bank::{Bank, HashAgeKind}, transaction_utils::OrderedIterator, }; -use solana_sdk::nonce; +use solana_sdk::nonce_account; use solana_transaction_status::{InnerInstructions, TransactionStatusMeta}; use std::{ sync::{ @@ -78,7 +78,7 @@ impl TransactionStatusService { if Bank::can_commit(&status) && !transaction.signatures.is_empty() { let fee_calculator = match hash_age_kind { Some(HashAgeKind::DurableNonce(_, account)) => { - nonce::utils::fee_calculator_of(&account) + nonce_account::fee_calculator_of(&account) } _ => bank.get_fee_calculator(&transaction.message().recent_blockhash), } diff --git a/ledger/src/staking_utils.rs b/ledger/src/staking_utils.rs index b2a90aa466..edfeefc8a8 100644 --- a/ledger/src/staking_utils.rs +++ b/ledger/src/staking_utils.rs @@ -104,15 +104,13 @@ pub(crate) mod tests { create_genesis_config, GenesisConfigInfo, BOOTSTRAP_VALIDATOR_LAMPORTS, }; use solana_sdk::{ + account::from_account, clock::Clock, instruction::Instruction, pubkey::Pubkey, signature::{Keypair, Signer}, signers::Signers, - sysvar::{ - stake_history::{self, StakeHistory}, - Sysvar, - }, + sysvar::stake_history::{self, StakeHistory}, transaction::Transaction, }; 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); result.sort(); let stake_history = - StakeHistory::from_account(&bank.get_account(&stake_history::id()).unwrap()).unwrap(); + from_account::(&bank.get_account(&stake_history::id()).unwrap()).unwrap(); let mut expected = vec![ (leader_stake.stake(bank.epoch(), Some(&stake_history)), None), (other_stake.stake(bank.epoch(), Some(&stake_history)), None), diff --git a/programs/bpf/benches/bpf_loader.rs b/programs/bpf/benches/bpf_loader.rs index 826f3c8363..1c308b249b 100644 --- a/programs/bpf/benches/bpf_loader.rs +++ b/programs/bpf/benches/bpf_loader.rs @@ -211,7 +211,11 @@ fn bench_instruction_count_tuner(_bencher: &mut Bencher) { 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 keyed_accounts: Vec<_> = keys .iter() @@ -229,7 +233,8 @@ fn bench_instruction_count_tuner(_bencher: &mut Bencher) { ) .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!( 0, instruction_meter.get_remaining(), diff --git a/programs/stake/src/stake_instruction.rs b/programs/stake/src/stake_instruction.rs index 6a6a9116f0..8175cb0692 100644 --- a/programs/stake/src/stake_instruction.rs +++ b/programs/stake/src/stake_instruction.rs @@ -524,9 +524,9 @@ mod tests { use super::*; use bincode::serialize; use solana_sdk::{ - account::Account, + account::{self, Account}, rent::Rent, - sysvar::{stake_history::StakeHistory, Sysvar}, + sysvar::stake_history::StakeHistory, }; use std::cell::RefCell; @@ -540,15 +540,15 @@ mod tests { .iter() .map(|meta| { 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) { - 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) { - sysvar::stake_history::create_account(1, &StakeHistory::default()) + account::create_account(&StakeHistory::default(), 1) } else if config::check_id(&meta.pubkey) { config::create_account(0, &config::Config::default()) } else if sysvar::rent::check_id(&meta.pubkey) { - sysvar::rent::create_account(1, &Rent::default()) + account::create_account(&Rent::default(), 1) } else { Account::default() }) @@ -709,7 +709,7 @@ mod tests { KeyedAccount::new( &sysvar::rent::id(), false, - &RefCell::new(sysvar::rent::create_account(0, &Rent::default())) + &RefCell::new(account::create_account(&Rent::default(), 0)) ) ], &serialize(&StakeInstruction::Initialize( @@ -759,14 +759,15 @@ mod tests { KeyedAccount::new( &sysvar::clock::id(), false, - &RefCell::new(sysvar::clock::Clock::default().create_account(1)) + &RefCell::new(account::create_account(&sysvar::clock::Clock::default(), 1)) ), KeyedAccount::new( &sysvar::stake_history::id(), false, - &RefCell::new( - sysvar::stake_history::StakeHistory::default().create_account(1) - ) + &RefCell::new(account::create_account( + &sysvar::stake_history::StakeHistory::default(), + 1 + )) ), KeyedAccount::new( &config::id(), @@ -789,15 +790,15 @@ mod tests { KeyedAccount::new( &sysvar::rewards::id(), false, - &RefCell::new(sysvar::rewards::create_account(1, 0.0)) + &RefCell::new(account::create_account( + &sysvar::rewards::Rewards::new(0.0), + 1 + )) ), KeyedAccount::new( &sysvar::stake_history::id(), false, - &RefCell::new(sysvar::stake_history::create_account( - 1, - &StakeHistory::default() - )) + &RefCell::new(account::create_account(&StakeHistory::default(), 1,)) ), ], &serialize(&StakeInstruction::Withdraw(42)).unwrap(), @@ -828,7 +829,10 @@ mod tests { KeyedAccount::new( &sysvar::rewards::id(), 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(), diff --git a/programs/vote/src/vote_instruction.rs b/programs/vote/src/vote_instruction.rs index 40a902d4e4..52ff66ae43 100644 --- a/programs/vote/src/vote_instruction.rs +++ b/programs/vote/src/vote_instruction.rs @@ -331,7 +331,10 @@ pub fn process_instruction( #[cfg(test)] mod tests { use super::*; - use solana_sdk::{account::Account, rent::Rent, sysvar::Sysvar}; + use solana_sdk::{ + account::{self, Account}, + rent::Rent, + }; use std::cell::RefCell; // these are for 100% coverage in this file @@ -350,11 +353,11 @@ mod tests { .iter() .map(|meta| { 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) { - SlotHashes::default().create_account(1) + account::create_account(&SlotHashes::default(), 1) } else if sysvar::rent::check_id(&meta.pubkey) { - Rent::free().create_account(1) + account::create_account(&Rent::free(), 1) } else { Account::default() }) diff --git a/ramp-tps/src/stake.rs b/ramp-tps/src/stake.rs index 8218524ed9..e4ddc0dac9 100644 --- a/ramp-tps/src/stake.rs +++ b/ramp-tps/src/stake.rs @@ -2,14 +2,12 @@ use crate::utils; use log::*; use solana_client::rpc_client::RpcClient; use solana_sdk::{ + account::from_account, clock::Epoch, epoch_info::EpochInfo, genesis_config::GenesisConfig, stake_history::StakeHistoryEntry, - sysvar::{ - stake_history::{self, StakeHistory}, - Sysvar, - }, + sysvar::stake_history::{self, StakeHistory}, }; use solana_stake_program::config::Config as StakeConfig; 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 { 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::(&stake_history_account)?; stake_history.get(&epoch).cloned() } diff --git a/runtime/src/accounts.rs b/runtime/src/accounts.rs index b0ca1797ba..89b651e137 100644 --- a/runtime/src/accounts.rs +++ b/runtime/src/accounts.rs @@ -22,7 +22,7 @@ use solana_sdk::{ genesis_config::ClusterType, hash::Hash, message::Message, - native_loader, nonce, + native_loader, nonce, nonce_account, pubkey::Pubkey, transaction::Result, transaction::{Transaction, TransactionError}, @@ -318,7 +318,7 @@ impl Accounts { ((_, tx), (Ok(()), hash_age_kind)) => { let fee_calculator = match hash_age_kind.as_ref() { Some(HashAgeKind::DurableNonce(_, account)) => { - nonce::utils::fee_calculator_of(account) + nonce_account::fee_calculator_of(account) } _ => hash_queue .get_fee_calculator(&tx.message().recent_blockhash) diff --git a/runtime/src/accounts_db.rs b/runtime/src/accounts_db.rs index 7bb92a1100..3f1a6a18a3 100644 --- a/runtime/src/accounts_db.rs +++ b/runtime/src/accounts_db.rs @@ -5117,9 +5117,10 @@ pub mod tests { #[test] fn test_account_balance_for_capitalization_sysvar() { - use solana_sdk::sysvar::Sysvar; - - let normal_sysvar = solana_sdk::slot_history::SlotHistory::default().create_account(1); + let normal_sysvar = solana_sdk::account::create_account( + &solana_sdk::slot_history::SlotHistory::default(), + 1, + ); assert_eq!( AccountsDB::account_balance_for_capitalization( normal_sysvar.lamports, diff --git a/runtime/src/bank.rs b/runtime/src/bank.rs index 9e46fff7b6..6674774b53 100644 --- a/runtime/src/bank.rs +++ b/runtime/src/bank.rs @@ -36,7 +36,7 @@ use solana_metrics::{ datapoint_debug, inc_new_counter_debug, inc_new_counter_error, inc_new_counter_info, }; use solana_sdk::{ - account::Account, + account::{create_account, from_account, Account}, clock::{ Epoch, Slot, SlotCount, SlotIndex, UnixTimestamp, DEFAULT_TICKS_PER_SECOND, MAX_PROCESSING_AGE, MAX_RECENT_BLOCKHASHES, MAX_TRANSACTION_FORWARDING_DELAY, @@ -54,16 +54,17 @@ use solana_sdk::{ message::Message, native_loader, native_token::sol_to_lamports, - nonce, + nonce, nonce_account, program_utils::limited_deserialize, pubkey::Pubkey, + recent_blockhashes_account, sanitize::Sanitize, signature::{Keypair, Signature}, slot_hashes::SlotHashes, slot_history::SlotHistory, stake_weighted_timestamp::{calculate_stake_weighted_timestamp, TIMESTAMP_SLOT_RANGE}, system_transaction, - sysvar::{self, Sysvar}, + sysvar::{self}, timing::years_as_slots, transaction::{self, Result, Transaction, TransactionError}, }; @@ -1086,10 +1087,8 @@ impl Bank { } pub fn clock(&self) -> sysvar::clock::Clock { - sysvar::clock::Clock::from_account( - &self.get_account(&sysvar::clock::id()).unwrap_or_default(), - ) - .unwrap_or_default() + from_account(&self.get_account(&sysvar::clock::id()).unwrap_or_default()) + .unwrap_or_default() } fn update_clock(&self) { @@ -1117,7 +1116,7 @@ impl Bank { unix_timestamp, }; 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| { let mut slot_history = account .as_ref() - .map(|account| SlotHistory::from_account(&account).unwrap()) + .map(|account| from_account::(&account).unwrap()) .unwrap_or_default(); 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| { let mut slot_hashes = account .as_ref() - .map(|account| SlotHashes::from_account(&account).unwrap()) + .map(|account| from_account::(&account).unwrap()) .unwrap_or_default(); 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 { - 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) { @@ -1179,27 +1178,27 @@ impl Bank { fn update_fees(&self) { 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.fee_calculator, ) }); } fn update_rent(&self) { self.update_sysvar_account(&sysvar::rent::id(), |account| { - sysvar::rent::create_account( - self.inherit_sysvar_account_balance(account), + create_account( &self.rent_collector.rent, + self.inherit_sysvar_account_balance(account), ) }); } fn update_epoch_schedule(&self) { self.update_sysvar_account(&sysvar::epoch_schedule::id(), |account| { - sysvar::epoch_schedule::create_account( - self.inherit_sysvar_account_balance(account), + create_account( &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 self.update_sysvar_account(&sysvar::stake_history::id(), |account| { - sysvar::stake_history::create_account( + create_account::( + &self.stakes.read().unwrap().history(), 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 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), - validator_point_value, ) }); } @@ -1434,7 +1433,7 @@ impl Bank { fn update_recent_blockhashes_locked(&self, locked_blockhash_queue: &BlockhashQueue) { self.update_sysvar_account(&sysvar::recent_blockhashes::id(), |account| { 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), recent_blockhash_iter, ) @@ -2063,7 +2062,7 @@ impl Bank { .map(|acc| (*nonce_pubkey, acc)) }) .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))| { let (fee_calculator, is_durable_nonce) = match hash_age_kind { Some(HashAgeKind::DurableNonce(_, account)) => { - (nonce::utils::fee_calculator_of(account), true) + (nonce_account::fee_calculator_of(account), true) } _ => ( hash_queue @@ -4216,7 +4215,7 @@ mod tests { ); let rent_account = bank.get_account(&sysvar::rent::id()).unwrap(); - let rent = sysvar::rent::Rent::from_account(&rent_account).unwrap(); + let rent = from_account::(&rent_account).unwrap(); assert_eq!(rent.burn_percent, 5); assert_eq!(rent.exemption_threshold, 1.2); @@ -5905,7 +5904,7 @@ mod tests { let rewards = bank1 .get_account(&sysvar::rewards::id()) - .map(|account| Rewards::from_account(&account).unwrap()) + .map(|account| from_account::(&account).unwrap()) .unwrap(); // verify the stake and vote accounts are the right size @@ -7188,56 +7187,63 @@ mod tests { let bank1 = Arc::new(Bank::new(&genesis_config)); bank1.update_sysvar_account(&dummy_clock_id, |optional_account| { assert!(optional_account.is_none()); - Clock { - slot: expected_previous_slot, - ..Clock::default() - } - .create_account(1) + + create_account( + &Clock { + slot: expected_previous_slot, + ..Clock::default() + }, + 1, + ) }); let current_account = bank1.get_account(&dummy_clock_id).unwrap(); assert_eq!( expected_previous_slot, - Clock::from_account(¤t_account).unwrap().slot + from_account::(¤t_account).unwrap().slot ); // Updating should increment the clock's slot let bank2 = Arc::new(Bank::new_from_parent(&bank1, &Pubkey::default(), 1)); bank2.update_sysvar_account(&dummy_clock_id, |optional_account| { - let slot = Clock::from_account(optional_account.as_ref().unwrap()) + let slot = from_account::(optional_account.as_ref().unwrap()) .unwrap() .slot + 1; - Clock { - slot, - ..Clock::default() - } - .create_account(1) + create_account( + &Clock { + slot, + ..Clock::default() + }, + 1, + ) }); let current_account = bank2.get_account(&dummy_clock_id).unwrap(); assert_eq!( expected_next_slot, - Clock::from_account(¤t_account).unwrap().slot + from_account::(¤t_account).unwrap().slot ); // Updating again should give bank1's sysvar to the closure not bank2's. // Thus, assert with same expected_next_slot as previously bank2.update_sysvar_account(&dummy_clock_id, |optional_account| { - let slot = Clock::from_account(optional_account.as_ref().unwrap()) + let slot = from_account::(optional_account.as_ref().unwrap()) .unwrap() .slot + 1; - Clock { - slot, - ..Clock::default() - } - .create_account(1) + create_account( + &Clock { + slot, + ..Clock::default() + }, + 1, + ) }); let current_account = bank2.get_account(&dummy_clock_id).unwrap(); assert_eq!( expected_next_slot, - Clock::from_account(¤t_account).unwrap().slot + from_account::(¤t_account).unwrap().slot ); } @@ -7584,7 +7590,7 @@ mod tests { let bank = Arc::new(Bank::new(&genesis_config)); let fees_account = bank.get_account(&sysvar::fees::id()).unwrap(); - let fees = Fees::from_account(&fees_account).unwrap(); + let fees = from_account::(&fees_account).unwrap(); assert_eq!( bank.fee_calculator.lamports_per_signature, fees.fee_calculator.lamports_per_signature @@ -7865,7 +7871,8 @@ mod tests { for i in 1..5 { let bhq_account = bank.get_account(&sysvar::recent_blockhashes::id()).unwrap(); let recent_blockhashes = - sysvar::recent_blockhashes::RecentBlockhashes::from_account(&bhq_account).unwrap(); + from_account::(&bhq_account) + .unwrap(); // Check length assert_eq!(recent_blockhashes.len(), i); 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 recent_blockhashes = - sysvar::recent_blockhashes::RecentBlockhashes::from_account(&bhq_account).unwrap(); + from_account::(&bhq_account).unwrap(); let sysvar_recent_blockhash = recent_blockhashes[0].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 let mut bank = new_from_parent(&Arc::new(bank)); let clock = - sysvar::clock::Clock::from_account(&bank.get_account(&sysvar::clock::id()).unwrap()) + from_account::(&bank.get_account(&sysvar::clock::id()).unwrap()) .unwrap(); assert_eq!(clock.unix_timestamp, bank.unix_timestamp_from_genesis()); @@ -9752,7 +9759,7 @@ mod tests { // Now Bank::new_from_parent should adjust timestamp let bank = Arc::new(new_from_parent(&Arc::new(bank))); let clock = - sysvar::clock::Clock::from_account(&bank.get_account(&sysvar::clock::id()).unwrap()) + from_account::(&bank.get_account(&sysvar::clock::id()).unwrap()) .unwrap(); assert_eq!( clock.unix_timestamp, diff --git a/runtime/src/serde_snapshot/tests.rs b/runtime/src/serde_snapshot/tests.rs index 7abe26f778..9b623bbf3b 100644 --- a/runtime/src/serde_snapshot/tests.rs +++ b/runtime/src/serde_snapshot/tests.rs @@ -262,7 +262,7 @@ mod test_bank_serialize { // These some what long test harness is required to freeze the ABI of // Bank's serialization due to versioned nature - #[frozen_abi(digest = "7f8quGr9ia7Dg5o339uKrPd4bLesNVdPuKMLpGQ9c3SR")] + #[frozen_abi(digest = "Giao4XJq9QgW78sqmT3nRMvENt4BgHXdzphCDGFPbXqW")] #[derive(Serialize, AbiExample)] pub struct BankAbiTestWrapperFuture { #[serde(serialize_with = "wrapper_future")] diff --git a/runtime/src/system_instruction_processor.rs b/runtime/src/system_instruction_processor.rs index 1b6fa20c60..d8e3d0708d 100644 --- a/runtime/src/system_instruction_processor.rs +++ b/runtime/src/system_instruction_processor.rs @@ -356,14 +356,14 @@ mod tests { use crate::{bank::Bank, bank_client::BankClient}; use bincode::serialize; use solana_sdk::{ - account::Account, + account::{self, Account}, client::SyncClient, fee_calculator::FeeCalculator, genesis_config::create_genesis_config, hash::{hash, Hash}, instruction::{AccountMeta, Instruction, InstructionError}, message::Message, - nonce, + nonce, nonce_account, recent_blockhashes_account, signature::{Keypair, Signer}, system_instruction, system_program, sysvar, sysvar::recent_blockhashes::IterItem, @@ -385,7 +385,7 @@ mod tests { RefCell::new(Account::default()) } fn create_default_recent_blockhashes_account() -> RefCell { - RefCell::new(sysvar::recent_blockhashes::create_account_with_data( + RefCell::new(recent_blockhashes_account::create_account_with_data( 1, vec![ IterItem(0u64, &Hash::default(), &FeeCalculator::default()); @@ -395,7 +395,7 @@ mod tests { )) } fn create_default_rent_account() -> RefCell { - RefCell::new(sysvar::rent::create_account(1, &Rent::free())) + RefCell::new(account::create_account(&Rent::free(), 1)) } #[test] @@ -1180,7 +1180,7 @@ mod tests { RefCell::new(if sysvar::recent_blockhashes::check_id(&meta.pubkey) { create_default_recent_blockhashes_account().into_inner() } else if sysvar::rent::check_id(&meta.pubkey) { - sysvar::rent::create_account(1, &Rent::free()) + account::create_account(&Rent::free(), 1) } else { Account::default() }) @@ -1258,7 +1258,7 @@ mod tests { #[test] 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( &Pubkey::default(), &[ @@ -1273,8 +1273,8 @@ mod tests { &serialize(&SystemInstruction::InitializeNonceAccount(Pubkey::default())).unwrap(), ) .unwrap(); - let new_recent_blockhashes_account = - RefCell::new(sysvar::recent_blockhashes::create_account_with_data( + let new_recent_blockhashes_account = RefCell::new( + solana_sdk::recent_blockhashes_account::create_account_with_data( 1, vec![ IterItem( @@ -1285,7 +1285,8 @@ mod tests { sysvar::recent_blockhashes::MAX_ENTRIES ] .into_iter(), - )); + ), + ); assert_eq!( super::process_instruction( &Pubkey::default(), @@ -1370,7 +1371,11 @@ mod tests { super::process_instruction( &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( &sysvar::recent_blockhashes::id(), @@ -1391,7 +1396,11 @@ mod tests { super::process_instruction( &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( &sysvar::recent_blockhashes::id(), @@ -1426,7 +1435,7 @@ mod tests { &[KeyedAccount::new( &Pubkey::default(), true, - &nonce::create_account(1_000_000), + &nonce_account::create_account(1_000_000), ),], &serialize(&SystemInstruction::InitializeNonceAccount(Pubkey::default())).unwrap(), ), @@ -1440,7 +1449,11 @@ mod tests { super::process_instruction( &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( &sysvar::recent_blockhashes::id(), false, @@ -1459,7 +1472,11 @@ mod tests { super::process_instruction( &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( &sysvar::recent_blockhashes::id(), false, @@ -1479,7 +1496,11 @@ mod tests { super::process_instruction( &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( &sysvar::recent_blockhashes::id(), false, @@ -1495,7 +1516,7 @@ mod tests { #[test] 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( &Pubkey::default(), &[ @@ -1560,7 +1581,7 @@ mod tests { #[test] fn test_get_system_account_kind_uninitialized_nonce_account_fail() { assert_eq!( - get_system_account_kind(&nonce::create_account(42).borrow()), + get_system_account_kind(&nonce_account::create_account(42).borrow()), None ); } diff --git a/runtime/tests/stake.rs b/runtime/tests/stake.rs index 55b0bd65ec..5981a9ca59 100644 --- a/runtime/tests/stake.rs +++ b/runtime/tests/stake.rs @@ -4,13 +4,14 @@ use solana_runtime::{ genesis_utils::{create_genesis_config_with_leader, GenesisConfigInfo}, }; use solana_sdk::{ + account::from_account, account_utils::StateMut, client::SyncClient, message::Message, pubkey::Pubkey, signature::{Keypair, Signer}, system_instruction::SystemError, - sysvar::{self, stake_history::StakeHistory, Sysvar}, + sysvar::{self, stake_history::StakeHistory}, transaction::TransactionError, }; use solana_stake_program::{ @@ -75,7 +76,7 @@ fn warmed_up(bank: &Bank, stake_pubkey: &Pubkey) -> bool { == stake.stake( bank.epoch(), Some( - &StakeHistory::from_account( + &from_account::( &bank.get_account(&sysvar::stake_history::id()).unwrap(), ) .unwrap(), @@ -89,7 +90,7 @@ fn get_staked(bank: &Bank, stake_pubkey: &Pubkey) -> u64 { .stake( bank.epoch(), Some( - &StakeHistory::from_account( + &from_account::( &bank.get_account(&sysvar::stake_history::id()).unwrap(), ) .unwrap(), diff --git a/sdk/benches/slot_hashes.rs b/sdk/benches/slot_hashes.rs index 9affd45df7..0472c27bcf 100644 --- a/sdk/benches/slot_hashes.rs +++ b/sdk/benches/slot_hashes.rs @@ -2,9 +2,9 @@ extern crate test; use solana_sdk::{ + account::{create_account, from_account}, hash::Hash, slot_hashes::{Slot, SlotHashes, MAX_ENTRIES}, - sysvar::Sysvar, }; use test::Bencher; @@ -15,7 +15,7 @@ fn bench_to_from_account(b: &mut Bencher) { slot_hashes.add(i as Slot, Hash::default()); } b.iter(|| { - let account = slot_hashes.create_account(0); - slot_hashes = SlotHashes::from_account(&account).unwrap(); + let account = create_account(&slot_hashes, 0); + slot_hashes = from_account::(&account).unwrap(); }); } diff --git a/sdk/benches/slot_history.rs b/sdk/benches/slot_history.rs index 7c95f10ebc..2aedca3980 100644 --- a/sdk/benches/slot_history.rs +++ b/sdk/benches/slot_history.rs @@ -1,7 +1,10 @@ #![feature(test)] extern crate test; -use solana_sdk::{slot_history::SlotHistory, sysvar::Sysvar}; +use solana_sdk::{ + account::{create_account, from_account}, + slot_history::SlotHistory, +}; use test::Bencher; #[bench] @@ -9,8 +12,8 @@ fn bench_to_from_account(b: &mut Bencher) { let mut slot_history = SlotHistory::default(); b.iter(|| { - let account = slot_history.create_account(0); - slot_history = SlotHistory::from_account(&account).unwrap(); + let account = create_account(&slot_history, 0); + slot_history = from_account::(&account).unwrap(); }); } diff --git a/sdk/program/src/account_info.rs b/sdk/program/src/account_info.rs index 958e30584c..a4ef2bc869 100644 --- a/sdk/program/src/account_info.rs +++ b/sdk/program/src/account_info.rs @@ -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 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 { - 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> { - 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>>( iter: &mut I, ) -> Result { diff --git a/sdk/program/src/lib.rs b/sdk/program/src/lib.rs index ce1fc8d121..c31a019922 100644 --- a/sdk/program/src/lib.rs +++ b/sdk/program/src/lib.rs @@ -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; diff --git a/sdk/program/src/nonce/mod.rs b/sdk/program/src/nonce/mod.rs index db8e79aa81..5aa54121a0 100644 --- a/sdk/program/src/nonce/mod.rs +++ b/sdk/program/src/nonce/mod.rs @@ -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 { - RefCell::new( - account::Account::new_data_with_space( - lamports, - &Versions::new_current(State::Uninitialized), - State::size(), - &crate::system_program::id(), - ) - .expect("nonce_account"), - ) -} diff --git a/sdk/program/src/sysvar/epoch_schedule.rs b/sdk/program/src/sysvar/epoch_schedule.rs index e785602f0e..77b27ec9ce 100644 --- a/sdk/program/src/sysvar/epoch_schedule.rs +++ b/sdk/program/src/sysvar/epoch_schedule.rs @@ -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()); - } -} diff --git a/sdk/program/src/sysvar/fees.rs b/sdk/program/src/sysvar/fees.rs index 1504d66858..3c09281e4b 100644 --- a/sdk/program/src/sysvar/fees.rs +++ b/sdk/program/src/sysvar/fees.rs @@ -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()); - } -} diff --git a/sdk/program/src/sysvar/mod.rs b/sdk/program/src/sysvar/mod.rs index 39af3b2fc8..18735dd145 100644 --- a/sdk/program/src/sysvar/mod.rs +++ b/sdk/program/src/sysvar/mod.rs @@ -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 { - 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 { 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)] diff --git a/sdk/program/src/sysvar/recent_blockhashes.rs b/sdk/program/src/sysvar/recent_blockhashes.rs index f055eefb9a..974908f6dc 100644 --- a/sdk/program/src/sysvar/recent_blockhashes.rs +++ b/sdk/program/src/sysvar/recent_blockhashes.rs @@ -1,5 +1,4 @@ use crate::{ - account::Account, declare_sysvar_id, fee_calculator::FeeCalculator, hash::{hash, Hash}, @@ -88,6 +87,11 @@ impl<'a> FromIterator> for RecentBlockhashes { pub struct IntoIterSorted { inner: BinaryHeap, } +impl IntoIterSorted { + pub fn new(binary_heap: BinaryHeap) -> Self { + Self { inner: binary_heap } + } +} impl Iterator for IntoIterSorted { 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>, -{ - 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>, -{ - 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); - } } diff --git a/sdk/program/src/sysvar/rent.rs b/sdk/program/src/sysvar/rent.rs index ac2028dfad..7ae3cd209f 100644 --- a/sdk/program/src/sysvar/rent.rs +++ b/sdk/program/src/sysvar/rent.rs @@ -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()); - } -} diff --git a/sdk/program/src/sysvar/rewards.rs b/sdk/program/src/sysvar/rewards.rs index b4add8d6b5..5aea49cefe 100644 --- a/sdk/program/src/sysvar/rewards.rs +++ b/sdk/program/src/sysvar/rewards.rs @@ -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()); - } -} diff --git a/sdk/program/src/sysvar/slot_hashes.rs b/sdk/program/src/sysvar/slot_hashes.rs index 757d9f40f3..71865d04d8 100644 --- a/sdk/program/src/sysvar/slot_hashes.rs +++ b/sdk/program/src/sysvar/slot_hashes.rs @@ -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())); - } } diff --git a/sdk/program/src/sysvar/stake_history.rs b/sdk/program/src/sysvar/stake_history.rs index 3731320b2f..8438f3f05d 100644 --- a/sdk/program/src/sysvar/stake_history.rs +++ b/sdk/program/src/sysvar/stake_history.rs @@ -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) - ); } } diff --git a/sdk/program/src/account.rs b/sdk/src/account.rs similarity index 62% rename from sdk/program/src/account.rs rename to sdk/src/account.rs index 2986c4e715..4ac4eedd1a 100644 --- a/sdk/program/src/account.rs +++ b/sdk/src/account.rs @@ -1,9 +1,10 @@ use crate::{clock::Epoch, pubkey::Pubkey}; +use solana_program::{account_info::AccountInfo, sysvar::Sysvar}; use std::{cell::RefCell, cmp, fmt, rc::Rc}; /// An Account with data that is stored on chain #[repr(C)] -#[frozen_abi(digest = "Upy4zg4EXZTnY371b4JPrGTh2kLcYpRno2K2pvjbN4e")] +#[frozen_abi(digest = "727tKRcoDvPiAsXxfvfsUauvZ4tLSw2WSw4HQfRQJ9Xx")] #[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Default, AbiExample)] #[serde(rename_all = "camelCase")] pub struct Account { @@ -109,3 +110,61 @@ impl Account { bincode::serialize_into(&mut self.data[..], state) } } + +/// Create an `Account` from a `Sysvar`. +pub fn create_account(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::(sysvar, &mut account).unwrap(); + account +} + +/// Create a `Sysvar` from an `Account`'s data. +pub fn from_account(account: &Account) -> Option { + bincode::deserialize(&account.data).ok() +} + +/// Serialize a `Sysvar` into an `Account`'s data. +pub fn to_account(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 { + 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> { + 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() +} diff --git a/sdk/program/src/account_utils.rs b/sdk/src/account_utils.rs similarity index 100% rename from sdk/program/src/account_utils.rs rename to sdk/src/account_utils.rs diff --git a/sdk/src/genesis_config.rs b/sdk/src/genesis_config.rs index 40502a1508..17dbb66829 100644 --- a/sdk/src/genesis_config.rs +++ b/sdk/src/genesis_config.rs @@ -61,7 +61,7 @@ impl FromStr for ClusterType { } } -#[frozen_abi(digest = "BAfWTFBwzed5FYCGAyMDq4HLsoZNTp8dZx2bqtYTCmGZ")] +#[frozen_abi(digest = "VxfEg5DXq5czYouMdcCbqDzUE8jGi3iSDSjzrrWp5iG")] #[derive(Serialize, Deserialize, Debug, Clone, AbiExample)] pub struct GenesisConfig { /// when the network (bootstrap validator) was started relative to the UNIX Epoch diff --git a/sdk/src/keyed_account.rs b/sdk/src/keyed_account.rs index daa784841e..9712f4c076 100644 --- a/sdk/src/keyed_account.rs +++ b/sdk/src/keyed_account.rs @@ -1,11 +1,8 @@ -use solana_program::{ - account::Account, +use crate::{ + account::{from_account, Account}, account_utils::{State, StateMut}, - clock::Epoch, - instruction::InstructionError, - pubkey::Pubkey, - sysvar::Sysvar, }; +use solana_program::{clock::Epoch, instruction::InstructionError, pubkey::Pubkey, sysvar::Sysvar}; use std::{ cell::{Ref, RefCell, RefMut}, iter::FromIterator, @@ -215,13 +212,16 @@ pub fn from_keyed_account( if !S::check_id(keyed_account.unsigned_key()) { return Err(InstructionError::InvalidArgument); } - S::from_account(&*keyed_account.try_account_ref()?).ok_or(InstructionError::InvalidArgument) + from_account::(&*keyed_account.try_account_ref()?).ok_or(InstructionError::InvalidArgument) } #[cfg(test)] mod tests { use super::*; - use crate::pubkey::Pubkey; + use crate::{ + account::{create_account, to_account}, + pubkey::Pubkey, + }; use std::cell::RefCell; #[repr(C)] @@ -243,13 +243,13 @@ mod tests { let key = crate::keyed_account::tests::id(); let wrong_key = Pubkey::new_unique(); - let account = test_sysvar.create_account(42); - let test_sysvar = TestSysvar::from_account(&account).unwrap(); + let account = create_account(&test_sysvar, 42); + let test_sysvar = from_account::(&account).unwrap(); assert_eq!(test_sysvar, TestSysvar::default()); let mut account = Account::new(42, TestSysvar::size_of(), &key); - test_sysvar.to_account(&mut account).unwrap(); - let test_sysvar = TestSysvar::from_account(&account).unwrap(); + to_account(&test_sysvar, &mut account).unwrap(); + let test_sysvar = from_account::(&account).unwrap(); assert_eq!(test_sysvar, TestSysvar::default()); let account = RefCell::new(account); diff --git a/sdk/src/lib.rs b/sdk/src/lib.rs index 9f89598d5d..438ea41565 100644 --- a/sdk/src/lib.rs +++ b/sdk/src/lib.rs @@ -6,6 +6,8 @@ extern crate self as solana_sdk; pub use solana_program::*; +pub mod account; +pub mod account_utils; pub mod builtins; pub mod client; pub mod commitment_config; @@ -21,11 +23,13 @@ pub mod inflation; pub mod keyed_account; pub mod log; pub mod native_loader; +pub mod nonce_account; pub mod nonce_keyed_account; pub mod packet; pub mod poh_config; pub mod program_utils; pub mod pubkey; +pub mod recent_blockhashes_account; pub mod rpc_port; pub mod secp256k1; pub mod shred_version; diff --git a/sdk/program/src/nonce/utils.rs b/sdk/src/nonce_account.rs similarity index 66% rename from sdk/program/src/nonce/utils.rs rename to sdk/src/nonce_account.rs index e2ac487a2a..0c533b9a6a 100644 --- a/sdk/program/src/nonce/utils.rs +++ b/sdk/src/nonce_account.rs @@ -5,6 +5,19 @@ use crate::{ hash::Hash, nonce::{state::Versions, State}, }; +use std::cell::RefCell; + +pub fn create_account(lamports: u64) -> RefCell { + RefCell::new( + Account::new_data_with_space( + lamports, + &Versions::new_current(State::Uninitialized), + State::size(), + &crate::system_program::id(), + ) + .expect("nonce_account"), + ) +} pub fn verify_nonce_account(acc: &Account, hash: &Hash) -> bool { match StateMut::::state(acc).map(|v| v.convert_to_current()) { diff --git a/sdk/src/nonce_keyed_account.rs b/sdk/src/nonce_keyed_account.rs index 2690b70917..e44feaecd9 100644 --- a/sdk/src/nonce_keyed_account.rs +++ b/sdk/src/nonce_keyed_account.rs @@ -1,6 +1,8 @@ -use crate::keyed_account::KeyedAccount; +use crate::{ + account_utils::State as AccountUtilsState, keyed_account::KeyedAccount, + nonce_account::create_account, +}; use solana_program::{ - account_utils::State as AccountUtilsState, instruction::InstructionError, nonce::{self, state::Versions, State}, pubkey::Pubkey, @@ -162,7 +164,7 @@ where F: Fn(&KeyedAccount), { let pubkey = Pubkey::new_unique(); - let account = solana_program::nonce::create_account(lamports); + let account = create_account(lamports); let keyed_account = KeyedAccount::new(&pubkey, signer, &account); f(&keyed_account) } @@ -174,10 +176,11 @@ mod test { account_utils::State as AccountUtilsState, keyed_account::KeyedAccount, nonce::{self, State}, + nonce_account::verify_nonce_account, system_instruction::NonceError, sysvar::recent_blockhashes::{create_test_recent_blockhashes, RecentBlockhashes}, }; - use solana_program::{hash::Hash, nonce::utils::verify_nonce_account}; + use solana_program::hash::Hash; use std::iter::FromIterator; #[test] diff --git a/sdk/src/recent_blockhashes_account.rs b/sdk/src/recent_blockhashes_account.rs new file mode 100644 index 0000000000..b91f13773f --- /dev/null +++ b/sdk/src/recent_blockhashes_account.rs @@ -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>, +{ + 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>, +{ + let mut account = create_account::(&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::(&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::(&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::(&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::(&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); + } +}