Replaces `KeyedAccount` by `BorrowedAccount` in `system_instruction_processor`. (#23217)

* Adds InstructionContext::check_number_of_instruction_accounts() and InstructionContext::get_instruction_account_key().
Bases check_sysvar_account() on instuction account indices.

* Adds instruction_account_indices enums to system_instruction_processor.

* Reorders parameters and adds InstructionContext.

* Replaces KeyedAccount by BorrowedAccount in system_instruction_processor (part 1).

* Replaces KeyedAccount by BorrowedAccount in system_instruction_processor (part 2).

* Replaces KeyedAccount by BorrowedAccount in system_instruction_processor (part 3).

* Replaces KeyedAccount by BorrowedAccount in system_instruction_processor (part 4).

* Replaces KeyedAccount by BorrowedAccount in system_instruction_processor (part 5).

* Code cleanup
This commit is contained in:
Alexander Meißner 2022-02-19 02:06:33 +01:00 committed by GitHub
parent 970f543ef6
commit ee7e411d68
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 320 additions and 176 deletions

View File

@ -239,11 +239,12 @@ pub mod get_sysvar_with_account_check2 {
fn check_sysvar_account<S: Sysvar>( fn check_sysvar_account<S: Sysvar>(
transaction_context: &TransactionContext, transaction_context: &TransactionContext,
instruction_context: &InstructionContext, instruction_context: &InstructionContext,
index_in_instruction: usize, instruction_account_index: usize,
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
let index_in_transaction = if !S::check_id(
instruction_context.get_index_in_transaction(index_in_instruction)?; instruction_context
if !S::check_id(transaction_context.get_key_of_account_at_index(index_in_transaction)?) { .get_instruction_account_key(transaction_context, instruction_account_index)?,
) {
return Err(InstructionError::InvalidArgument); return Err(InstructionError::InvalidArgument);
} }
Ok(()) Ok(())

View File

@ -12,9 +12,6 @@ use {
std::collections::HashSet, std::collections::HashSet,
}; };
pub const NONCE_ACCOUNT_INDEX: usize = 0;
pub const WITHDRAW_TO_ACCOUNT_INDEX: usize = 1;
pub fn advance_nonce_account( pub fn advance_nonce_account(
invoke_context: &InvokeContext, invoke_context: &InvokeContext,
instruction_context: &InstructionContext, instruction_context: &InstructionContext,
@ -353,6 +350,9 @@ mod test {
}; };
} }
const NONCE_ACCOUNT_INDEX: usize = 0;
const WITHDRAW_TO_ACCOUNT_INDEX: usize = 1;
macro_rules! set_invoke_context_blockhash { macro_rules! set_invoke_context_blockhash {
($invoke_context:expr, $seed:expr) => { ($invoke_context:expr, $seed:expr) => {
$invoke_context.blockhash = hash(&bincode::serialize(&$seed).unwrap()); $invoke_context.blockhash = hash(&bincode::serialize(&$seed).unwrap());

View File

@ -1,18 +1,17 @@
use { use {
crate::nonce_keyed_account::{ crate::nonce_keyed_account::{
advance_nonce_account, authorize_nonce_account, initialize_nonce_account, advance_nonce_account, authorize_nonce_account, initialize_nonce_account,
withdraw_nonce_account, NONCE_ACCOUNT_INDEX, WITHDRAW_TO_ACCOUNT_INDEX, withdraw_nonce_account,
}, },
log::*, log::*,
solana_program_runtime::{ solana_program_runtime::{
ic_msg, invoke_context::InvokeContext, sysvar_cache::get_sysvar_with_account_check2, ic_msg, invoke_context::InvokeContext, sysvar_cache::get_sysvar_with_account_check2,
}, },
solana_sdk::{ solana_sdk::{
account::{AccountSharedData, ReadableAccount, WritableAccount}, account::{AccountSharedData, ReadableAccount},
account_utils::StateMut, account_utils::StateMut,
feature_set, feature_set,
instruction::InstructionError, instruction::InstructionError,
keyed_account::{keyed_account_at_index, KeyedAccount},
nonce, nonce,
program_utils::limited_deserialize, program_utils::limited_deserialize,
pubkey::Pubkey, pubkey::Pubkey,
@ -20,6 +19,7 @@ use {
NonceError, SystemError, SystemInstruction, MAX_PERMITTED_DATA_LENGTH, NonceError, SystemError, SystemInstruction, MAX_PERMITTED_DATA_LENGTH,
}, },
system_program, system_program,
transaction_context::{BorrowedAccount, InstructionContext},
}, },
std::collections::HashSet, std::collections::HashSet,
}; };
@ -70,11 +70,11 @@ impl Address {
} }
fn allocate( fn allocate(
account: &mut AccountSharedData, invoke_context: &InvokeContext,
signers: &HashSet<Pubkey>,
account: &mut BorrowedAccount,
address: &Address, address: &Address,
space: u64, space: u64,
signers: &HashSet<Pubkey>,
invoke_context: &InvokeContext,
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
if !address.is_signer(signers) { if !address.is_signer(signers) {
ic_msg!( ic_msg!(
@ -87,7 +87,7 @@ fn allocate(
// if it looks like the `to` account is already in use, bail // if it looks like the `to` account is already in use, bail
// (note that the id check is also enforced by message_processor) // (note that the id check is also enforced by message_processor)
if !account.data().is_empty() || !system_program::check_id(account.owner()) { if !account.get_data().is_empty() || !system_program::check_id(account.get_owner()) {
ic_msg!( ic_msg!(
invoke_context, invoke_context,
"Allocate: account {:?} already in use", "Allocate: account {:?} already in use",
@ -106,20 +106,20 @@ fn allocate(
return Err(SystemError::InvalidAccountDataLength.into()); return Err(SystemError::InvalidAccountDataLength.into());
} }
account.set_data(vec![0; space as usize]); account.set_data(vec![0; space as usize].as_slice());
Ok(()) Ok(())
} }
fn assign( fn assign(
account: &mut AccountSharedData, invoke_context: &InvokeContext,
signers: &HashSet<Pubkey>,
account: &mut BorrowedAccount,
address: &Address, address: &Address,
owner: &Pubkey, owner: &Pubkey,
signers: &HashSet<Pubkey>,
invoke_context: &InvokeContext,
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
// no work to do, just return // no work to do, just return
if account.owner() == owner { if account.get_owner() == owner {
return Ok(()); return Ok(());
} }
@ -128,36 +128,38 @@ fn assign(
return Err(InstructionError::MissingRequiredSignature); return Err(InstructionError::MissingRequiredSignature);
} }
account.set_owner(*owner); account.set_owner(&owner.to_bytes());
Ok(()) Ok(())
} }
fn allocate_and_assign( fn allocate_and_assign(
to: &mut AccountSharedData, invoke_context: &InvokeContext,
signers: &HashSet<Pubkey>,
to_account: &mut BorrowedAccount,
to_address: &Address, to_address: &Address,
space: u64, space: u64,
owner: &Pubkey, owner: &Pubkey,
signers: &HashSet<Pubkey>,
invoke_context: &InvokeContext,
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
allocate(to, to_address, space, signers, invoke_context)?; allocate(invoke_context, signers, to_account, to_address, space)?;
assign(to, to_address, owner, signers, invoke_context) assign(invoke_context, signers, to_account, to_address, owner)
} }
fn create_account( fn create_account(
from: &KeyedAccount, invoke_context: &InvokeContext,
to: &KeyedAccount, instruction_context: &InstructionContext,
signers: &HashSet<Pubkey>,
from_account_index: usize,
to_account_index: usize,
to_address: &Address, to_address: &Address,
lamports: u64, lamports: u64,
space: u64, space: u64,
owner: &Pubkey, owner: &Pubkey,
signers: &HashSet<Pubkey>,
invoke_context: &InvokeContext,
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
// if it looks like the `to` account is already in use, bail // if it looks like the `to` account is already in use, bail
{ {
let to = &mut to.try_account_ref_mut()?; let mut to_account = instruction_context
if to.lamports() > 0 { .try_borrow_instruction_account(invoke_context.transaction_context, to_account_index)?;
if to_account.get_lamports() > 0 {
ic_msg!( ic_msg!(
invoke_context, invoke_context,
"Create Account: account {:?} already in use", "Create Account: account {:?} already in use",
@ -165,42 +167,60 @@ fn create_account(
); );
return Err(SystemError::AccountAlreadyInUse.into()); return Err(SystemError::AccountAlreadyInUse.into());
} }
allocate_and_assign(
allocate_and_assign(to, to_address, space, owner, signers, invoke_context)?; invoke_context,
signers,
&mut to_account,
to_address,
space,
owner,
)?;
} }
transfer(from, to, lamports, invoke_context) transfer(
invoke_context,
instruction_context,
from_account_index,
to_account_index,
lamports,
)
} }
fn transfer_verified( fn transfer_verified(
from: &KeyedAccount,
to: &KeyedAccount,
lamports: u64,
invoke_context: &InvokeContext, invoke_context: &InvokeContext,
instruction_context: &InstructionContext,
from_account_index: usize,
to_account_index: usize,
lamports: u64,
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
if !from.data_is_empty()? { let mut from_account = instruction_context
.try_borrow_instruction_account(invoke_context.transaction_context, from_account_index)?;
if !from_account.get_data().is_empty() {
ic_msg!(invoke_context, "Transfer: `from` must not carry data"); ic_msg!(invoke_context, "Transfer: `from` must not carry data");
return Err(InstructionError::InvalidArgument); return Err(InstructionError::InvalidArgument);
} }
if lamports > from.lamports()? { if lamports > from_account.get_lamports() {
ic_msg!( ic_msg!(
invoke_context, invoke_context,
"Transfer: insufficient lamports {}, need {}", "Transfer: insufficient lamports {}, need {}",
from.lamports()?, from_account.get_lamports(),
lamports lamports
); );
return Err(SystemError::ResultWithNegativeLamports.into()); return Err(SystemError::ResultWithNegativeLamports.into());
} }
from_account.checked_sub_lamports(lamports)?;
from.try_account_ref_mut()?.checked_sub_lamports(lamports)?; drop(from_account);
to.try_account_ref_mut()?.checked_add_lamports(lamports)?; let mut to_account = instruction_context
.try_borrow_instruction_account(invoke_context.transaction_context, to_account_index)?;
to_account.checked_add_lamports(lamports)?;
Ok(()) Ok(())
} }
fn transfer( fn transfer(
from: &KeyedAccount,
to: &KeyedAccount,
lamports: u64,
invoke_context: &InvokeContext, invoke_context: &InvokeContext,
instruction_context: &InstructionContext,
from_account_index: usize,
to_account_index: usize,
lamports: u64,
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
if !invoke_context if !invoke_context
.feature_set .feature_set
@ -210,26 +230,38 @@ fn transfer(
return Ok(()); return Ok(());
} }
if from.signer_key().is_none() { if !instruction_context
.is_signer(instruction_context.get_number_of_program_accounts() + from_account_index)?
{
ic_msg!( ic_msg!(
invoke_context, invoke_context,
"Transfer: `from` account {} must sign", "Transfer: `from` account {} must sign",
from.unsigned_key() instruction_context.get_instruction_account_key(
invoke_context.transaction_context,
from_account_index
)?,
); );
return Err(InstructionError::MissingRequiredSignature); return Err(InstructionError::MissingRequiredSignature);
} }
transfer_verified(from, to, lamports, invoke_context) transfer_verified(
invoke_context,
instruction_context,
from_account_index,
to_account_index,
lamports,
)
} }
fn transfer_with_seed( fn transfer_with_seed(
from: &KeyedAccount, invoke_context: &InvokeContext,
from_base: &KeyedAccount, instruction_context: &InstructionContext,
from_account_index: usize,
from_base_account_index: usize,
to_account_index: usize,
from_seed: &str, from_seed: &str,
from_owner: &Pubkey, from_owner: &Pubkey,
to: &KeyedAccount,
lamports: u64, lamports: u64,
invoke_context: &InvokeContext,
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
if !invoke_context if !invoke_context
.feature_set .feature_set
@ -239,42 +271,112 @@ fn transfer_with_seed(
return Ok(()); return Ok(());
} }
if from_base.signer_key().is_none() { let from_base_key = instruction_context
.get_instruction_account_key(invoke_context.transaction_context, from_base_account_index)?;
if !instruction_context
.is_signer(instruction_context.get_number_of_program_accounts() + from_base_account_index)?
{
ic_msg!( ic_msg!(
invoke_context, invoke_context,
"Transfer: 'from' account {:?} must sign", "Transfer: 'from' account {:?} must sign",
from_base from_base_key,
); );
return Err(InstructionError::MissingRequiredSignature); return Err(InstructionError::MissingRequiredSignature);
} }
let address_from_seed = let from_key = instruction_context
Pubkey::create_with_seed(from_base.unsigned_key(), from_seed, from_owner)?; .get_instruction_account_key(invoke_context.transaction_context, from_account_index)?;
if *from.unsigned_key() != address_from_seed { let address_from_seed = Pubkey::create_with_seed(from_base_key, from_seed, from_owner)?;
if *from_key != address_from_seed {
ic_msg!( ic_msg!(
invoke_context, invoke_context,
"Transfer: 'from' address {} does not match derived address {}", "Transfer: 'from' address {} does not match derived address {}",
from.unsigned_key(), from_key,
address_from_seed address_from_seed,
); );
return Err(SystemError::AddressWithSeedMismatch.into()); return Err(SystemError::AddressWithSeedMismatch.into());
} }
transfer_verified(from, to, lamports, invoke_context) transfer_verified(
invoke_context,
instruction_context,
from_account_index,
to_account_index,
lamports,
)
}
pub mod instruction_account_indices {
pub enum CreateAccount {
From = 0,
To = 1,
}
pub enum CreateAccountWithSeed {
From = 0,
To = 1,
}
pub enum Assign {
Account = 0,
}
pub enum Transfer {
From = 0,
To = 1,
}
pub enum TransferWithSeed {
From = 0,
Base = 1,
To = 2,
}
pub enum AdvanceNonceAccount {
Nonce = 0,
RecentBlockhashes = 1,
}
pub enum WithdrawNonceAccount {
From = 0,
To = 1,
RecentBlockhashes = 2,
Rent = 3,
}
pub enum InitializeNonceAccount {
Nonce = 0,
RecentBlockhashes = 1,
Rent = 2,
}
pub enum AuthorizeNonceAccount {
Nonce = 0,
}
pub enum Allocate {
Account = 0,
}
pub enum AllocateWithSeed {
Account = 0,
}
pub enum AssignWithSeed {
Account = 0,
}
} }
pub fn process_instruction( pub fn process_instruction(
first_instruction_account: usize, _first_instruction_account: usize,
instruction_data: &[u8], instruction_data: &[u8],
invoke_context: &mut InvokeContext, invoke_context: &mut InvokeContext,
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
let transaction_context = &invoke_context.transaction_context; let transaction_context = &invoke_context.transaction_context;
let instruction_context = transaction_context.get_current_instruction_context()?; let instruction_context = transaction_context.get_current_instruction_context()?;
let keyed_accounts = invoke_context.get_keyed_accounts()?;
let instruction = limited_deserialize(instruction_data)?; let instruction = limited_deserialize(instruction_data)?;
trace!("process_instruction: {:?}", instruction); trace!("process_instruction: {:?}", instruction);
trace!("keyed_accounts: {:?}", keyed_accounts);
let signers = instruction_context.get_signers(transaction_context); let signers = instruction_context.get_signers(transaction_context);
match instruction { match instruction {
@ -283,18 +385,22 @@ pub fn process_instruction(
space, space,
owner, owner,
} => { } => {
let from = keyed_account_at_index(keyed_accounts, first_instruction_account)?; instruction_context.check_number_of_instruction_accounts(2)?;
let to = keyed_account_at_index(keyed_accounts, first_instruction_account + 1)?; let to_key = instruction_context.get_instruction_account_key(
let to_address = Address::create(to.unsigned_key(), None, invoke_context)?; invoke_context.transaction_context,
instruction_account_indices::CreateAccount::To as usize,
)?;
let to_address = Address::create(to_key, None, invoke_context)?;
create_account( create_account(
from, invoke_context,
to, instruction_context,
&signers,
instruction_account_indices::CreateAccount::From as usize,
instruction_account_indices::CreateAccount::To as usize,
&to_address, &to_address,
lamports, lamports,
space, space,
&owner, &owner,
&signers,
invoke_context,
) )
} }
SystemInstruction::CreateAccountWithSeed { SystemInstruction::CreateAccountWithSeed {
@ -304,60 +410,66 @@ pub fn process_instruction(
space, space,
owner, owner,
} => { } => {
let from = keyed_account_at_index(keyed_accounts, first_instruction_account)?; instruction_context.check_number_of_instruction_accounts(2)?;
let to = keyed_account_at_index(keyed_accounts, first_instruction_account + 1)?; let to_key = instruction_context.get_instruction_account_key(
let to_address = Address::create( invoke_context.transaction_context,
to.unsigned_key(), instruction_account_indices::CreateAccountWithSeed::To as usize,
Some((&base, &seed, &owner)),
invoke_context,
)?; )?;
let to_address = Address::create(to_key, Some((&base, &seed, &owner)), invoke_context)?;
create_account( create_account(
from, invoke_context,
to, instruction_context,
&signers,
instruction_account_indices::CreateAccountWithSeed::From as usize,
instruction_account_indices::CreateAccountWithSeed::To as usize,
&to_address, &to_address,
lamports, lamports,
space, space,
&owner, &owner,
&signers,
invoke_context,
) )
} }
SystemInstruction::Assign { owner } => { SystemInstruction::Assign { owner } => {
let keyed_account = keyed_account_at_index(keyed_accounts, first_instruction_account)?; let mut account = instruction_context.try_borrow_instruction_account(
let mut account = keyed_account.try_account_ref_mut()?; invoke_context.transaction_context,
let address = Address::create(keyed_account.unsigned_key(), None, invoke_context)?; instruction_account_indices::Assign::Account as usize,
assign(&mut account, &address, &owner, &signers, invoke_context) )?;
let address = Address::create(account.get_key(), None, invoke_context)?;
assign(invoke_context, &signers, &mut account, &address, &owner)
} }
SystemInstruction::Transfer { lamports } => { SystemInstruction::Transfer { lamports } => {
let from = keyed_account_at_index(keyed_accounts, first_instruction_account)?; instruction_context.check_number_of_instruction_accounts(2)?;
let to = keyed_account_at_index(keyed_accounts, first_instruction_account + 1)?; transfer(
transfer(from, to, lamports, invoke_context) invoke_context,
instruction_context,
instruction_account_indices::Transfer::From as usize,
instruction_account_indices::Transfer::To as usize,
lamports,
)
} }
SystemInstruction::TransferWithSeed { SystemInstruction::TransferWithSeed {
lamports, lamports,
from_seed, from_seed,
from_owner, from_owner,
} => { } => {
let from = keyed_account_at_index(keyed_accounts, first_instruction_account)?; instruction_context.check_number_of_instruction_accounts(3)?;
let base = keyed_account_at_index(keyed_accounts, first_instruction_account + 1)?;
let to = keyed_account_at_index(keyed_accounts, first_instruction_account + 2)?;
transfer_with_seed( transfer_with_seed(
from, invoke_context,
base, instruction_context,
instruction_account_indices::TransferWithSeed::From as usize,
instruction_account_indices::TransferWithSeed::Base as usize,
instruction_account_indices::TransferWithSeed::To as usize,
&from_seed, &from_seed,
&from_owner, &from_owner,
to,
lamports, lamports,
invoke_context,
) )
} }
SystemInstruction::AdvanceNonceAccount => { SystemInstruction::AdvanceNonceAccount => {
let _me = &mut keyed_account_at_index(keyed_accounts, first_instruction_account)?; instruction_context.check_number_of_instruction_accounts(1)?;
#[allow(deprecated)] #[allow(deprecated)]
let recent_blockhashes = get_sysvar_with_account_check2::recent_blockhashes( let recent_blockhashes = get_sysvar_with_account_check2::recent_blockhashes(
invoke_context, invoke_context,
instruction_context, instruction_context,
first_instruction_account + 1, instruction_account_indices::AdvanceNonceAccount::RecentBlockhashes as usize,
)?; )?;
if recent_blockhashes.is_empty() { if recent_blockhashes.is_empty() {
ic_msg!( ic_msg!(
@ -370,40 +482,39 @@ pub fn process_instruction(
invoke_context, invoke_context,
instruction_context, instruction_context,
&signers, &signers,
NONCE_ACCOUNT_INDEX, instruction_account_indices::AdvanceNonceAccount::Nonce as usize,
) )
} }
SystemInstruction::WithdrawNonceAccount(lamports) => { SystemInstruction::WithdrawNonceAccount(lamports) => {
let _me = &mut keyed_account_at_index(keyed_accounts, first_instruction_account)?; instruction_context.check_number_of_instruction_accounts(2)?;
let _to = &mut keyed_account_at_index(keyed_accounts, first_instruction_account + 1)?;
#[allow(deprecated)] #[allow(deprecated)]
let _recent_blockhashes = get_sysvar_with_account_check2::recent_blockhashes( let _recent_blockhashes = get_sysvar_with_account_check2::recent_blockhashes(
invoke_context, invoke_context,
instruction_context, instruction_context,
first_instruction_account + 2, instruction_account_indices::WithdrawNonceAccount::RecentBlockhashes as usize,
)?; )?;
let rent = get_sysvar_with_account_check2::rent( let rent = get_sysvar_with_account_check2::rent(
invoke_context, invoke_context,
instruction_context, instruction_context,
first_instruction_account + 3, instruction_account_indices::WithdrawNonceAccount::Rent as usize,
)?; )?;
withdraw_nonce_account( withdraw_nonce_account(
invoke_context, invoke_context,
instruction_context, instruction_context,
&signers, &signers,
NONCE_ACCOUNT_INDEX, instruction_account_indices::WithdrawNonceAccount::From as usize,
WITHDRAW_TO_ACCOUNT_INDEX, instruction_account_indices::WithdrawNonceAccount::To as usize,
lamports, lamports,
&rent, &rent,
) )
} }
SystemInstruction::InitializeNonceAccount(authorized) => { SystemInstruction::InitializeNonceAccount(authorized) => {
let _me = &mut keyed_account_at_index(keyed_accounts, first_instruction_account)?; instruction_context.check_number_of_instruction_accounts(1)?;
#[allow(deprecated)] #[allow(deprecated)]
let recent_blockhashes = get_sysvar_with_account_check2::recent_blockhashes( let recent_blockhashes = get_sysvar_with_account_check2::recent_blockhashes(
invoke_context, invoke_context,
instruction_context, instruction_context,
first_instruction_account + 1, instruction_account_indices::InitializeNonceAccount::RecentBlockhashes as usize,
)?; )?;
if recent_blockhashes.is_empty() { if recent_blockhashes.is_empty() {
ic_msg!( ic_msg!(
@ -415,31 +526,33 @@ pub fn process_instruction(
let rent = get_sysvar_with_account_check2::rent( let rent = get_sysvar_with_account_check2::rent(
invoke_context, invoke_context,
instruction_context, instruction_context,
first_instruction_account + 2, instruction_account_indices::InitializeNonceAccount::Rent as usize,
)?; )?;
initialize_nonce_account( initialize_nonce_account(
invoke_context, invoke_context,
instruction_context, instruction_context,
NONCE_ACCOUNT_INDEX, instruction_account_indices::InitializeNonceAccount::Nonce as usize,
&authorized, &authorized,
&rent, &rent,
) )
} }
SystemInstruction::AuthorizeNonceAccount(nonce_authority) => { SystemInstruction::AuthorizeNonceAccount(nonce_authority) => {
let _me = &mut keyed_account_at_index(keyed_accounts, first_instruction_account)?; instruction_context.check_number_of_instruction_accounts(1)?;
authorize_nonce_account( authorize_nonce_account(
invoke_context, invoke_context,
instruction_context, instruction_context,
&signers, &signers,
NONCE_ACCOUNT_INDEX, instruction_account_indices::AuthorizeNonceAccount::Nonce as usize,
&nonce_authority, &nonce_authority,
) )
} }
SystemInstruction::Allocate { space } => { SystemInstruction::Allocate { space } => {
let keyed_account = keyed_account_at_index(keyed_accounts, first_instruction_account)?; let mut account = instruction_context.try_borrow_instruction_account(
let mut account = keyed_account.try_account_ref_mut()?; invoke_context.transaction_context,
let address = Address::create(keyed_account.unsigned_key(), None, invoke_context)?; instruction_account_indices::Allocate::Account as usize,
allocate(&mut account, &address, space, &signers, invoke_context) )?;
let address = Address::create(account.get_key(), None, invoke_context)?;
allocate(invoke_context, &signers, &mut account, &address, space)
} }
SystemInstruction::AllocateWithSeed { SystemInstruction::AllocateWithSeed {
base, base,
@ -447,31 +560,35 @@ pub fn process_instruction(
space, space,
owner, owner,
} => { } => {
let keyed_account = keyed_account_at_index(keyed_accounts, first_instruction_account)?; let mut account = instruction_context.try_borrow_instruction_account(
let mut account = keyed_account.try_account_ref_mut()?; invoke_context.transaction_context,
instruction_account_indices::AllocateWithSeed::Account as usize,
)?;
let address = Address::create( let address = Address::create(
keyed_account.unsigned_key(), account.get_key(),
Some((&base, &seed, &owner)), Some((&base, &seed, &owner)),
invoke_context, invoke_context,
)?; )?;
allocate_and_assign( allocate_and_assign(
invoke_context,
&signers,
&mut account, &mut account,
&address, &address,
space, space,
&owner, &owner,
&signers,
invoke_context,
) )
} }
SystemInstruction::AssignWithSeed { base, seed, owner } => { SystemInstruction::AssignWithSeed { base, seed, owner } => {
let keyed_account = keyed_account_at_index(keyed_accounts, first_instruction_account)?; let mut account = instruction_context.try_borrow_instruction_account(
let mut account = keyed_account.try_account_ref_mut()?; invoke_context.transaction_context,
instruction_account_indices::AssignWithSeed::Account as usize,
)?;
let address = Address::create( let address = Address::create(
keyed_account.unsigned_key(), account.get_key(),
Some((&base, &seed, &owner)), Some((&base, &seed, &owner)),
invoke_context, invoke_context,
)?; )?;
assign(&mut account, &address, &owner, &signers, invoke_context) assign(invoke_context, &signers, &mut account, &address, &owner)
} }
} }
} }
@ -1163,38 +1280,42 @@ mod tests {
#[test] #[test]
fn test_assign() { fn test_assign() {
let mut transaction_context = TransactionContext::new(Vec::new(), 1, 1);
let invoke_context = InvokeContext::new_mock(&mut transaction_context, &[]);
let new_owner = Pubkey::new(&[9; 32]); let new_owner = Pubkey::new(&[9; 32]);
let pubkey = Pubkey::new_unique(); let pubkey = Pubkey::new_unique();
let mut account = AccountSharedData::new(100, 0, &system_program::id()); let account = AccountSharedData::new(100, 0, &system_program::id());
assert_eq!( // owner does not change, no signature needed
assign( process_instruction(
&mut account, &bincode::serialize(&SystemInstruction::Assign {
&pubkey.into(), owner: system_program::id(),
&new_owner, })
&HashSet::new(), .unwrap(),
&invoke_context, vec![(pubkey, account.clone())],
), vec![AccountMeta {
Err(InstructionError::MissingRequiredSignature) pubkey,
is_signer: false,
is_writable: false,
}],
Ok(()),
super::process_instruction,
); );
// no change, no signature needed // owner does change, signature needed
assert_eq!( process_instruction(
assign( &bincode::serialize(&SystemInstruction::Assign { owner: new_owner }).unwrap(),
&mut account, vec![(pubkey, account.clone())],
&pubkey.into(), vec![AccountMeta {
&system_program::id(), pubkey,
&HashSet::new(), is_signer: false,
&invoke_context, is_writable: false,
), }],
Ok(()) Err(InstructionError::MissingRequiredSignature),
super::process_instruction,
); );
process_instruction( process_instruction(
&bincode::serialize(&SystemInstruction::Assign { owner: new_owner }).unwrap(), &bincode::serialize(&SystemInstruction::Assign { owner: new_owner }).unwrap(),
vec![(pubkey, account)], vec![(pubkey, account.clone())],
vec![AccountMeta { vec![AccountMeta {
pubkey, pubkey,
is_signer: true, is_signer: true,
@ -1203,25 +1324,21 @@ mod tests {
Ok(()), Ok(()),
super::process_instruction, super::process_instruction,
); );
}
#[test] // assign to sysvar instead of system_program
fn test_assign_to_sysvar_with_feature() { process_instruction(
let mut transaction_context = TransactionContext::new(Vec::new(), 1, 1); &bincode::serialize(&SystemInstruction::Assign {
let invoke_context = InvokeContext::new_mock(&mut transaction_context, &[]); owner: sysvar::id(),
let new_owner = sysvar::id(); })
let from = Pubkey::new_unique(); .unwrap(),
let mut from_account = AccountSharedData::new(100, 0, &system_program::id()); vec![(pubkey, account)],
vec![AccountMeta {
assert_eq!( pubkey,
assign( is_signer: true,
&mut from_account, is_writable: false,
&from.into(), }],
&new_owner, Ok(()),
&[from].iter().cloned().collect::<HashSet<_>>(), super::process_instruction,
&invoke_context,
),
Ok(())
); );
} }

View File

@ -304,6 +304,18 @@ impl InstructionContext {
self.instruction_accounts.len() self.instruction_accounts.len()
} }
/// Assert that enough account were supplied to this Instruction
pub fn check_number_of_instruction_accounts(
&self,
expected_at_least: usize,
) -> Result<(), InstructionError> {
if self.get_number_of_instruction_accounts() < expected_at_least {
Err(InstructionError::NotEnoughAccountKeys)
} else {
Ok(())
}
}
/// Number of accounts in this Instruction /// Number of accounts in this Instruction
pub fn get_number_of_accounts(&self) -> usize { pub fn get_number_of_accounts(&self) -> usize {
self.program_accounts self.program_accounts
@ -360,6 +372,30 @@ impl InstructionContext {
} }
} }
/// Gets the key of the last program account of this Instruction
pub fn get_program_key<'a, 'b: 'a>(
&'a self,
transaction_context: &'b TransactionContext,
) -> Result<&'b Pubkey, InstructionError> {
let index_in_transaction =
self.get_index_in_transaction(self.program_accounts.len().saturating_sub(1))?;
transaction_context.get_key_of_account_at_index(index_in_transaction)
}
/// Gets the key of an instruction account (skipping program accounts)
pub fn get_instruction_account_key<'a, 'b: 'a>(
&'a self,
transaction_context: &'b TransactionContext,
instruction_account_index: usize,
) -> Result<&'b Pubkey, InstructionError> {
let index_in_transaction = self.get_index_in_transaction(
self.program_accounts
.len()
.saturating_add(instruction_account_index),
)?;
transaction_context.get_key_of_account_at_index(index_in_transaction)
}
/// Tries to borrow an account from this Instruction /// Tries to borrow an account from this Instruction
pub fn try_borrow_account<'a, 'b: 'a>( pub fn try_borrow_account<'a, 'b: 'a>(
&'a self, &'a self,
@ -382,16 +418,6 @@ impl InstructionContext {
}) })
} }
/// Gets the key of the last program account of this Instruction
pub fn get_program_key<'a, 'b: 'a>(
&'a self,
transaction_context: &'b TransactionContext,
) -> Result<&'b Pubkey, InstructionError> {
let index_in_transaction =
self.get_index_in_transaction(self.program_accounts.len().saturating_sub(1))?;
transaction_context.get_key_of_account_at_index(index_in_transaction)
}
/// Gets the last program account of this Instruction /// Gets the last program account of this Instruction
pub fn try_borrow_program_account<'a, 'b: 'a>( pub fn try_borrow_program_account<'a, 'b: 'a>(
&'a self, &'a self,
@ -407,13 +433,13 @@ impl InstructionContext {
pub fn try_borrow_instruction_account<'a, 'b: 'a>( pub fn try_borrow_instruction_account<'a, 'b: 'a>(
&'a self, &'a self,
transaction_context: &'b TransactionContext, transaction_context: &'b TransactionContext,
index_in_instruction: usize, instruction_account_index: usize,
) -> Result<BorrowedAccount<'a>, InstructionError> { ) -> Result<BorrowedAccount<'a>, InstructionError> {
self.try_borrow_account( self.try_borrow_account(
transaction_context, transaction_context,
self.program_accounts self.program_accounts
.len() .len()
.saturating_add(index_in_instruction), .saturating_add(instruction_account_index),
) )
} }