Skip to content

Commit

Permalink
Account->AccountSharedData (#15691)
Browse files Browse the repository at this point in the history
  • Loading branch information
jeffwashington authored Mar 9, 2021
1 parent 61c7ce8 commit 8a3135d
Show file tree
Hide file tree
Showing 71 changed files with 2,031 additions and 1,160 deletions.
57 changes: 33 additions & 24 deletions account-decoder/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,10 @@ pub mod validator_info;

use {
crate::parse_account_data::{parse_account_data, AccountAdditionalData, ParsedAccount},
solana_sdk::{account::Account, clock::Epoch, fee_calculator::FeeCalculator, pubkey::Pubkey},
solana_sdk::{
account::ReadableAccount, account::WritableAccount, clock::Epoch,
fee_calculator::FeeCalculator, pubkey::Pubkey,
},
std::{
io::{Read, Write},
str::FromStr,
Expand Down Expand Up @@ -57,58 +60,61 @@ pub enum UiAccountEncoding {
}

impl UiAccount {
pub fn encode(
pub fn encode<T: ReadableAccount>(
pubkey: &Pubkey,
account: Account,
account: T,
encoding: UiAccountEncoding,
additional_data: Option<AccountAdditionalData>,
data_slice_config: Option<UiDataSliceConfig>,
) -> Self {
let data = match encoding {
UiAccountEncoding::Binary => UiAccountData::LegacyBinary(
bs58::encode(slice_data(&account.data, data_slice_config)).into_string(),
bs58::encode(slice_data(&account.data(), data_slice_config)).into_string(),
),
UiAccountEncoding::Base58 => UiAccountData::Binary(
bs58::encode(slice_data(&account.data, data_slice_config)).into_string(),
bs58::encode(slice_data(&account.data(), data_slice_config)).into_string(),
encoding,
),
UiAccountEncoding::Base64 => UiAccountData::Binary(
base64::encode(slice_data(&account.data, data_slice_config)),
base64::encode(slice_data(&account.data(), data_slice_config)),
encoding,
),
UiAccountEncoding::Base64Zstd => {
let mut encoder = zstd::stream::write::Encoder::new(Vec::new(), 0).unwrap();
match encoder
.write_all(slice_data(&account.data, data_slice_config))
.write_all(slice_data(&account.data(), data_slice_config))
.and_then(|()| encoder.finish())
{
Ok(zstd_data) => UiAccountData::Binary(base64::encode(zstd_data), encoding),
Err(_) => UiAccountData::Binary(
base64::encode(slice_data(&account.data, data_slice_config)),
base64::encode(slice_data(&account.data(), data_slice_config)),
UiAccountEncoding::Base64,
),
}
}
UiAccountEncoding::JsonParsed => {
if let Ok(parsed_data) =
parse_account_data(pubkey, &account.owner, &account.data, additional_data)
parse_account_data(pubkey, &account.owner(), &account.data(), additional_data)
{
UiAccountData::Json(parsed_data)
} else {
UiAccountData::Binary(base64::encode(&account.data), UiAccountEncoding::Base64)
UiAccountData::Binary(
base64::encode(&account.data()),
UiAccountEncoding::Base64,
)
}
}
};
UiAccount {
lamports: account.lamports,
lamports: account.lamports(),
data,
owner: account.owner.to_string(),
executable: account.executable,
rent_epoch: account.rent_epoch,
owner: account.owner().to_string(),
executable: account.executable(),
rent_epoch: account.rent_epoch(),
}
}

pub fn decode(&self) -> Option<Account> {
pub fn decode<T: WritableAccount>(&self) -> Option<T> {
let data = match &self.data {
UiAccountData::Json(_) => None,
UiAccountData::LegacyBinary(blob) => bs58::decode(blob).into_vec().ok(),
Expand All @@ -128,13 +134,13 @@ impl UiAccount {
UiAccountEncoding::Binary | UiAccountEncoding::JsonParsed => None,
},
}?;
Some(Account {
lamports: self.lamports,
Some(T::create(
self.lamports,
data,
owner: Pubkey::from_str(&self.owner).ok()?,
executable: self.executable,
rent_epoch: self.rent_epoch,
})
Pubkey::from_str(&self.owner).ok()?,
self.executable,
self.rent_epoch,
))
}
}

Expand Down Expand Up @@ -184,6 +190,7 @@ fn slice_data(data: &[u8], data_slice_config: Option<UiDataSliceConfig>) -> &[u8
#[cfg(test)]
mod test {
use super::*;
use solana_sdk::account::{Account, AccountSharedData};

#[test]
fn test_slice_data() {
Expand Down Expand Up @@ -217,9 +224,9 @@ mod test {
fn test_base64_zstd() {
let encoded_account = UiAccount::encode(
&Pubkey::default(),
Account {
AccountSharedData {
data: vec![0; 1024],
..Account::default()
..AccountSharedData::default()
},
UiAccountEncoding::Base64Zstd,
None,
Expand All @@ -230,7 +237,9 @@ mod test {
UiAccountData::Binary(_, UiAccountEncoding::Base64Zstd)
));

let decoded_account = encoded_account.decode().unwrap();
let decoded_account = encoded_account.decode::<Account>().unwrap();
assert_eq!(decoded_account.data, vec![0; 1024]);
let decoded_account = encoded_account.decode::<AccountSharedData>().unwrap();
assert_eq!(decoded_account.data, vec![0; 1024]);
}
}
2 changes: 1 addition & 1 deletion banks-client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ impl BanksClient {
self.get_account(sysvar::rent::id()).map(|result| {
let rent_sysvar = result?
.ok_or_else(|| io::Error::new(io::ErrorKind::Other, "Rent sysvar not present"))?;
from_account::<Rent>(&rent_sysvar).ok_or_else(|| {
from_account::<Rent, _>(&rent_sysvar).ok_or_else(|| {
io::Error::new(io::ErrorKind::Other, "Failed to deserialize Rent sysvar")
})
})
Expand Down
2 changes: 1 addition & 1 deletion banks-server/src/banks_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ impl Banks for BanksServer {
commitment: CommitmentLevel,
) -> Option<Account> {
let bank = self.bank(commitment);
bank.get_account(&address)
bank.get_account(&address).map(Account::from)
}
}

Expand Down
7 changes: 4 additions & 3 deletions cli/src/stake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1747,9 +1747,10 @@ 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 = from_account::<StakeHistory>(&stake_history_account).ok_or_else(|| {
CliError::RpcRequestError("Failed to deserialize stake history".to_string())
})?;
let stake_history =
from_account::<StakeHistory, _>(&stake_history_account).ok_or_else(|| {
CliError::RpcRequestError("Failed to deserialize stake history".to_string())
})?;

let mut entries: Vec<CliStakeHistoryEntry> = vec![];
for entry in stake_history.deref() {
Expand Down
16 changes: 10 additions & 6 deletions client/src/nonce_utils.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::rpc_client::RpcClient;
use solana_sdk::{
account::Account,
account::{Account, ReadableAccount},
account_utils::StateMut,
commitment_config::CommitmentConfig,
nonce::{
Expand Down Expand Up @@ -52,24 +52,28 @@ pub fn get_account_with_commitment(
})
}

pub fn account_identity_ok(account: &Account) -> Result<(), Error> {
if account.owner != system_program::id() {
pub fn account_identity_ok<T: ReadableAccount>(account: &T) -> Result<(), Error> {
if account.owner() != &system_program::id() {
Err(Error::InvalidAccountOwner)
} else if account.data.is_empty() {
} else if account.data().is_empty() {
Err(Error::UnexpectedDataSize)
} else {
Ok(())
}
}

pub fn state_from_account(account: &Account) -> Result<State, Error> {
pub fn state_from_account<T: ReadableAccount + StateMut<Versions>>(
account: &T,
) -> Result<State, Error> {
account_identity_ok(account)?;
StateMut::<Versions>::state(account)
.map_err(|_| Error::InvalidAccountData)
.map(|v| v.convert_to_current())
}

pub fn data_from_account(account: &Account) -> Result<Data, Error> {
pub fn data_from_account<T: ReadableAccount + StateMut<Versions>>(
account: &T,
) -> Result<Data, Error> {
account_identity_ok(account)?;
state_from_account(account).and_then(|ref s| data_from_state(s).map(|d| d.clone()))
}
Expand Down
26 changes: 15 additions & 11 deletions core/src/commitment_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ mod tests {
bank_forks::BankForks,
genesis_utils::{create_genesis_config_with_vote_accounts, ValidatorVoteKeypairs},
};
use solana_sdk::{pubkey::Pubkey, signature::Signer};
use solana_sdk::{account::Account, pubkey::Pubkey, signature::Signer};
use solana_stake_program::stake_state;
use solana_vote_program::{
vote_state::{self, VoteStateVersions},
Expand Down Expand Up @@ -411,16 +411,20 @@ mod tests {
rooted_stake_amount,
);

genesis_config.accounts.extend(vec![
(pk1, vote_account1.clone()),
(sk1, stake_account1),
(pk2, vote_account2.clone()),
(sk2, stake_account2),
(pk3, vote_account3.clone()),
(sk3, stake_account3),
(pk4, vote_account4.clone()),
(sk4, stake_account4),
]);
genesis_config.accounts.extend(
vec![
(pk1, vote_account1.clone()),
(sk1, stake_account1),
(pk2, vote_account2.clone()),
(sk2, stake_account2),
(pk3, vote_account3.clone()),
(sk3, stake_account3),
(pk4, vote_account4.clone()),
(sk4, stake_account4),
]
.into_iter()
.map(|(key, account)| (key, Account::from(account))),
);

// Create bank
let bank = Arc::new(Bank::new(&genesis_config));
Expand Down
10 changes: 5 additions & 5 deletions core/src/consensus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1253,7 +1253,7 @@ pub mod test {
},
};
use solana_sdk::{
account::Account, clock::Slot, hash::Hash, pubkey::Pubkey, signature::Signer,
account::AccountSharedData, clock::Slot, hash::Hash, pubkey::Pubkey, signature::Signer,
slot_history::SlotHistory,
};
use solana_vote_program::{
Expand Down Expand Up @@ -1571,10 +1571,10 @@ pub mod test {
fn gen_stakes(stake_votes: &[(u64, &[u64])]) -> Vec<(Pubkey, (u64, ArcVoteAccount))> {
let mut stakes = vec![];
for (lamports, votes) in stake_votes {
let mut account = Account {
let mut account = AccountSharedData {
data: vec![0; VoteState::size_of()],
lamports: *lamports,
..Account::default()
..AccountSharedData::default()
};
let mut vote_state = VoteState::default();
for slot in *votes {
Expand Down Expand Up @@ -2251,9 +2251,9 @@ pub mod test {
#[test]
fn test_stake_is_updated_for_entire_branch() {
let mut voted_stakes = HashMap::new();
let account = Account {
let account = AccountSharedData {
lamports: 1,
..Account::default()
..AccountSharedData::default()
};
let set: HashSet<u64> = vec![0u64, 1u64].into_iter().collect();
let ancestors: HashMap<u64, HashSet<u64>> = [(2u64, set)].iter().cloned().collect();
Expand Down
8 changes: 6 additions & 2 deletions core/src/non_circulating_supply.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ pub fn calculate_non_circulating_supply(bank: &Arc<Bank>) -> NonCirculatingSuppl
bank.get_program_accounts(&solana_stake_program::id())
};
for (pubkey, account) in stake_accounts.iter() {
let stake_account = StakeState::from(&account).unwrap_or_default();
let stake_account = StakeState::from(account).unwrap_or_default();
match stake_account {
StakeState::Initialized(meta) => {
if meta.lockup.is_in_force(&clock, None)
Expand Down Expand Up @@ -138,6 +138,7 @@ mod tests {
use super::*;
use solana_sdk::{
account::Account,
account::AccountSharedData,
epoch_schedule::EpochSchedule,
genesis_config::{ClusterType, GenesisConfig},
};
Expand Down Expand Up @@ -212,7 +213,10 @@ mod tests {
bank = Arc::new(new_from_parent(&bank));
let new_balance = 11;
for key in non_circulating_accounts {
bank.store_account(&key, &Account::new(new_balance, 0, &Pubkey::default()));
bank.store_account(
&key,
&AccountSharedData::new(new_balance, 0, &Pubkey::default()),
);
}
let non_circulating_supply = calculate_non_circulating_supply(&bank);
assert_eq!(
Expand Down
Loading

0 comments on commit 8a3135d

Please sign in to comment.