Boot the mut (#7926)

This commit is contained in:
Jack May 2020-01-22 17:54:06 -08:00 committed by GitHub
parent e54bf563b5
commit c95e5346a4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
37 changed files with 772 additions and 812 deletions

View File

@ -30,7 +30,7 @@ use solana_perf::packet::Packets;
use solana_perf::recycler::Recycler; use solana_perf::recycler::Recycler;
use solana_sdk::packet::Packet; use solana_sdk::packet::Packet;
use solana_sdk::{ use solana_sdk::{
account_utils::State, account_utils::StateMut,
client::{AsyncClient, SyncClient}, client::{AsyncClient, SyncClient},
clock::{get_complete_segment_from_slot, get_segment_from_slot, Slot}, clock::{get_complete_segment_from_slot, get_segment_from_slot, Slot},
commitment_config::CommitmentConfig, commitment_config::CommitmentConfig,

View File

@ -11,7 +11,7 @@ use indicatif::{ProgressBar, ProgressStyle};
use solana_clap_utils::{input_parsers::*, input_validators::*}; use solana_clap_utils::{input_parsers::*, input_validators::*};
use solana_client::{rpc_client::RpcClient, rpc_response::RpcVoteAccountInfo}; use solana_client::{rpc_client::RpcClient, rpc_response::RpcVoteAccountInfo};
use solana_sdk::{ use solana_sdk::{
account_utils::State, account_utils::StateMut,
clock::{self, Slot}, clock::{self, Slot},
commitment_config::CommitmentConfig, commitment_config::CommitmentConfig,
epoch_schedule::{Epoch, EpochSchedule}, epoch_schedule::{Epoch, EpochSchedule},

View File

@ -8,7 +8,7 @@ use solana_clap_utils::{input_parsers::*, input_validators::*, ArgConstant};
use solana_client::rpc_client::RpcClient; use solana_client::rpc_client::RpcClient;
use solana_sdk::{ use solana_sdk::{
account::Account, account::Account,
account_utils::State, account_utils::StateMut,
hash::Hash, hash::Hash,
nonce_state::NonceState, nonce_state::NonceState,
pubkey::Pubkey, pubkey::Pubkey,
@ -420,7 +420,7 @@ pub fn process_create_nonce_account(
if let Ok(nonce_account) = rpc_client.get_account(&nonce_account_address) { if let Ok(nonce_account) = rpc_client.get_account(&nonce_account_address) {
let err_msg = if nonce_account.owner == system_program::id() let err_msg = if nonce_account.owner == system_program::id()
&& State::<NonceState>::state(&nonce_account).is_ok() && StateMut::<NonceState>::state(&nonce_account).is_ok()
{ {
format!("Nonce account {} already exists", nonce_account_address) format!("Nonce account {} already exists", nonce_account_address)
} else { } else {

View File

@ -13,7 +13,7 @@ use solana_clap_utils::{input_parsers::*, input_validators::*, ArgConstant};
use solana_client::rpc_client::RpcClient; use solana_client::rpc_client::RpcClient;
use solana_sdk::signature::{Keypair, Signature}; use solana_sdk::signature::{Keypair, Signature};
use solana_sdk::{ use solana_sdk::{
account_utils::State, account_utils::StateMut,
hash::Hash, hash::Hash,
pubkey::Pubkey, pubkey::Pubkey,
signature::KeypairUtil, signature::KeypairUtil,

View File

@ -7,7 +7,7 @@ use solana_clap_utils::{input_parsers::*, input_validators::*};
use solana_client::rpc_client::RpcClient; use solana_client::rpc_client::RpcClient;
use solana_sdk::signature::Keypair; use solana_sdk::signature::Keypair;
use solana_sdk::{ use solana_sdk::{
account_utils::State, message::Message, pubkey::Pubkey, signature::KeypairUtil, account_utils::StateMut, message::Message, pubkey::Pubkey, signature::KeypairUtil,
system_instruction::SystemError, transaction::Transaction, system_instruction::SystemError, transaction::Transaction,
}; };
use solana_storage_program::storage_instruction::{self, StorageAccountType}; use solana_storage_program::storage_instruction::{self, StorageAccountType};

View File

@ -6,7 +6,7 @@ use solana_cli::cli::{
use solana_client::rpc_client::RpcClient; use solana_client::rpc_client::RpcClient;
use solana_faucet::faucet::run_local_faucet; use solana_faucet::faucet::run_local_faucet;
use solana_sdk::{ use solana_sdk::{
account_utils::State, account_utils::StateMut,
hash::Hash, hash::Hash,
nonce_state::NonceState, nonce_state::NonceState,
pubkey::Pubkey, pubkey::Pubkey,

View File

@ -3,7 +3,7 @@ use solana_cli::cli::{process_command, request_and_confirm_airdrop, CliCommand,
use solana_client::rpc_client::RpcClient; use solana_client::rpc_client::RpcClient;
use solana_faucet::faucet::run_local_faucet; use solana_faucet::faucet::run_local_faucet;
use solana_sdk::{ use solana_sdk::{
account_utils::State, account_utils::StateMut,
hash::Hash, hash::Hash,
nonce_state::NonceState, nonce_state::NonceState,
pubkey::Pubkey, pubkey::Pubkey,

View File

@ -14,7 +14,7 @@ use solana_ledger::{bank_forks::BankForks, blockstore::Blockstore};
use solana_runtime::{bank::Bank, storage_utils::archiver_accounts}; use solana_runtime::{bank::Bank, storage_utils::archiver_accounts};
use solana_sdk::{ use solana_sdk::{
account::Account, account::Account,
account_utils::State, account_utils::StateMut,
clock::{get_segment_from_slot, Slot}, clock::{get_segment_from_slot, Slot},
hash::Hash, hash::Hash,
instruction::Instruction, instruction::Instruction,

View File

@ -48,7 +48,7 @@ pub fn check_elf(prog: &[u8]) -> Result<(), Error> {
pub fn serialize_parameters( pub fn serialize_parameters(
program_id: &Pubkey, program_id: &Pubkey,
keyed_accounts: &mut [KeyedAccount], keyed_accounts: &[KeyedAccount],
data: &[u8], data: &[u8],
) -> Result<Vec<u8>, InstructionError> { ) -> Result<Vec<u8>, InstructionError> {
assert_eq!(32, mem::size_of::<Pubkey>()); assert_eq!(32, mem::size_of::<Pubkey>());
@ -56,7 +56,7 @@ pub fn serialize_parameters(
let mut v: Vec<u8> = Vec::new(); let mut v: Vec<u8> = Vec::new();
v.write_u64::<LittleEndian>(keyed_accounts.len() as u64) v.write_u64::<LittleEndian>(keyed_accounts.len() as u64)
.unwrap(); .unwrap();
for keyed_account in keyed_accounts.iter_mut() { for keyed_account in keyed_accounts.iter() {
v.write_u64::<LittleEndian>(keyed_account.signer_key().is_some() as u64) v.write_u64::<LittleEndian>(keyed_account.signer_key().is_some() as u64)
.unwrap(); .unwrap();
v.write_all(keyed_account.unsigned_key().as_ref()).unwrap(); v.write_all(keyed_account.unsigned_key().as_ref()).unwrap();
@ -74,7 +74,7 @@ pub fn serialize_parameters(
} }
pub fn deserialize_parameters( pub fn deserialize_parameters(
keyed_accounts: &mut [KeyedAccount], keyed_accounts: &[KeyedAccount],
buffer: &[u8], buffer: &[u8],
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
assert_eq!(32, mem::size_of::<Pubkey>()); assert_eq!(32, mem::size_of::<Pubkey>());
@ -103,7 +103,7 @@ pub fn deserialize_parameters(
} }
let mut start = mem::size_of::<u64>(); let mut start = mem::size_of::<u64>();
for keyed_account in keyed_accounts.iter_mut() { for keyed_account in keyed_accounts.iter() {
start += mem::size_of::<u64>() // signer_key boolean start += mem::size_of::<u64>() // signer_key boolean
+ mem::size_of::<Pubkey>(); // pubkey + mem::size_of::<Pubkey>(); // pubkey
let lamports = LittleEndian::read_u64(&buffer[start..]); let lamports = LittleEndian::read_u64(&buffer[start..]);
@ -142,7 +142,7 @@ pub fn deserialize_parameters(
pub fn process_instruction( pub fn process_instruction(
program_id: &Pubkey, program_id: &Pubkey,
keyed_accounts: &mut [KeyedAccount], keyed_accounts: &[KeyedAccount],
instruction_data: &[u8], instruction_data: &[u8],
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
solana_logger::setup_with_default("solana=info"); solana_logger::setup_with_default("solana=info");
@ -153,7 +153,7 @@ pub fn process_instruction(
} }
if is_executable(keyed_accounts)? { if is_executable(keyed_accounts)? {
let mut keyed_accounts_iter = keyed_accounts.iter_mut(); let mut keyed_accounts_iter = keyed_accounts.iter();
let program = next_keyed_account(&mut keyed_accounts_iter)?; let program = next_keyed_account(&mut keyed_accounts_iter)?;
let program_account = program.try_account_ref_mut()?; let program_account = program.try_account_ref_mut()?;
let (mut vm, heap_region) = match create_vm(&program_account.data) { let (mut vm, heap_region) = match create_vm(&program_account.data) {
@ -163,12 +163,12 @@ pub fn process_instruction(
return Err(InstructionError::GenericError); return Err(InstructionError::GenericError);
} }
}; };
let parameter_accounts = keyed_accounts_iter.into_slice(); let parameter_accounts = keyed_accounts_iter.as_slice();
let mut parameter_bytes = let parameter_bytes =
serialize_parameters(program_id, parameter_accounts, &instruction_data)?; serialize_parameters(program_id, parameter_accounts, &instruction_data)?;
info!("Call BPF program"); info!("Call BPF program");
match vm.execute_program(parameter_bytes.as_mut_slice(), &[], &[heap_region]) { match vm.execute_program(parameter_bytes.as_slice(), &[], &[heap_region]) {
Ok(status) => match u32::try_from(status) { Ok(status) => match u32::try_from(status) {
Ok(status) => { Ok(status) => {
if status > 0 { if status > 0 {
@ -191,7 +191,7 @@ pub fn process_instruction(
} else if !keyed_accounts.is_empty() { } else if !keyed_accounts.is_empty() {
match limited_deserialize(instruction_data)? { match limited_deserialize(instruction_data)? {
LoaderInstruction::Write { offset, bytes } => { LoaderInstruction::Write { offset, bytes } => {
let mut keyed_accounts_iter = keyed_accounts.iter_mut(); let mut keyed_accounts_iter = keyed_accounts.iter();
let program = next_keyed_account(&mut keyed_accounts_iter)?; let program = next_keyed_account(&mut keyed_accounts_iter)?;
if program.signer_key().is_none() { if program.signer_key().is_none() {
warn!("key[0] did not sign the transaction"); warn!("key[0] did not sign the transaction");
@ -207,7 +207,7 @@ pub fn process_instruction(
program.try_account_ref_mut()?.data[offset..offset + len].copy_from_slice(&bytes); program.try_account_ref_mut()?.data[offset..offset + len].copy_from_slice(&bytes);
} }
LoaderInstruction::Finalize => { LoaderInstruction::Finalize => {
let mut keyed_accounts_iter = keyed_accounts.iter_mut(); let mut keyed_accounts_iter = keyed_accounts.iter();
let program = next_keyed_account(&mut keyed_accounts_iter)?; let program = next_keyed_account(&mut keyed_accounts_iter)?;
let rent = next_keyed_account(&mut keyed_accounts_iter)?; let rent = next_keyed_account(&mut keyed_accounts_iter)?;
@ -259,8 +259,8 @@ mod tests {
fn test_bpf_loader_write() { fn test_bpf_loader_write() {
let program_id = Pubkey::new_rand(); let program_id = Pubkey::new_rand();
let program_key = Pubkey::new_rand(); let program_key = Pubkey::new_rand();
let mut program_account = Account::new_ref(1, 0, &program_id); let program_account = Account::new_ref(1, 0, &program_id);
let mut keyed_accounts = vec![KeyedAccount::new(&program_key, false, &mut program_account)]; let keyed_accounts = vec![KeyedAccount::new(&program_key, false, &program_account)];
let instruction_data = bincode::serialize(&LoaderInstruction::Write { let instruction_data = bincode::serialize(&LoaderInstruction::Write {
offset: 3, offset: 3,
bytes: vec![1, 2, 3], bytes: vec![1, 2, 3],
@ -270,21 +270,21 @@ mod tests {
// Case: Empty keyed accounts // Case: Empty keyed accounts
assert_eq!( assert_eq!(
Err(InstructionError::NotEnoughAccountKeys), Err(InstructionError::NotEnoughAccountKeys),
process_instruction(&program_id, &mut vec![], &instruction_data) process_instruction(&program_id, &vec![], &instruction_data)
); );
// Case: Not signed // Case: Not signed
assert_eq!( assert_eq!(
Err(InstructionError::MissingRequiredSignature), Err(InstructionError::MissingRequiredSignature),
process_instruction(&program_id, &mut keyed_accounts, &instruction_data) process_instruction(&program_id, &keyed_accounts, &instruction_data)
); );
// Case: Write bytes to an offset // Case: Write bytes to an offset
let mut keyed_accounts = vec![KeyedAccount::new(&program_key, true, &mut program_account)]; let mut keyed_accounts = vec![KeyedAccount::new(&program_key, true, &program_account)];
keyed_accounts[0].account.borrow_mut().data = vec![0; 6]; keyed_accounts[0].account.borrow_mut().data = vec![0; 6];
assert_eq!( assert_eq!(
Ok(()), Ok(()),
process_instruction(&program_id, &mut keyed_accounts, &instruction_data) process_instruction(&program_id, &keyed_accounts, &instruction_data)
); );
assert_eq!( assert_eq!(
vec![0, 0, 0, 1, 2, 3], vec![0, 0, 0, 1, 2, 3],
@ -292,11 +292,11 @@ mod tests {
); );
// Case: Overflow // Case: Overflow
let mut keyed_accounts = vec![KeyedAccount::new(&program_key, true, &mut program_account)]; let mut keyed_accounts = vec![KeyedAccount::new(&program_key, true, &program_account)];
keyed_accounts[0].account.borrow_mut().data = vec![0; 5]; keyed_accounts[0].account.borrow_mut().data = vec![0; 5];
assert_eq!( assert_eq!(
Err(InstructionError::AccountDataTooSmall), Err(InstructionError::AccountDataTooSmall),
process_instruction(&program_id, &mut keyed_accounts, &instruction_data) process_instruction(&program_id, &keyed_accounts, &instruction_data)
); );
} }
@ -309,34 +309,34 @@ mod tests {
let mut elf = Vec::new(); let mut elf = Vec::new();
let rent = rent::Rent::default(); let rent = rent::Rent::default();
file.read_to_end(&mut elf).unwrap(); file.read_to_end(&mut elf).unwrap();
let mut program_account = Account::new_ref(rent.minimum_balance(elf.len()), 0, &program_id); let program_account = Account::new_ref(rent.minimum_balance(elf.len()), 0, &program_id);
program_account.borrow_mut().data = elf; program_account.borrow_mut().data = elf;
let mut keyed_accounts = vec![KeyedAccount::new(&program_key, false, &mut program_account)]; let mut keyed_accounts = vec![KeyedAccount::new(&program_key, false, &program_account)];
let instruction_data = bincode::serialize(&LoaderInstruction::Finalize).unwrap(); let instruction_data = bincode::serialize(&LoaderInstruction::Finalize).unwrap();
// Case: Empty keyed accounts // Case: Empty keyed accounts
assert_eq!( assert_eq!(
Err(InstructionError::NotEnoughAccountKeys), Err(InstructionError::NotEnoughAccountKeys),
process_instruction(&program_id, &mut vec![], &instruction_data) process_instruction(&program_id, &vec![], &instruction_data)
); );
let mut rent_account = RefCell::new(rent::create_account(1, &rent)); let rent_account = RefCell::new(rent::create_account(1, &rent));
keyed_accounts.push(KeyedAccount::new(&rent_key, false, &mut rent_account)); keyed_accounts.push(KeyedAccount::new(&rent_key, false, &rent_account));
// Case: Not signed // Case: Not signed
assert_eq!( assert_eq!(
Err(InstructionError::MissingRequiredSignature), Err(InstructionError::MissingRequiredSignature),
process_instruction(&program_id, &mut keyed_accounts, &instruction_data) process_instruction(&program_id, &keyed_accounts, &instruction_data)
); );
// Case: Finalize // Case: Finalize
let mut keyed_accounts = vec![ let keyed_accounts = vec![
KeyedAccount::new(&program_key, true, &mut program_account), KeyedAccount::new(&program_key, true, &program_account),
KeyedAccount::new(&rent_key, false, &mut rent_account), KeyedAccount::new(&rent_key, false, &rent_account),
]; ];
assert_eq!( assert_eq!(
Ok(()), Ok(()),
process_instruction(&program_id, &mut keyed_accounts, &instruction_data) process_instruction(&program_id, &keyed_accounts, &instruction_data)
); );
assert!(keyed_accounts[0].account.borrow().executable); assert!(keyed_accounts[0].account.borrow().executable);
@ -344,13 +344,13 @@ mod tests {
// Case: Finalize // Case: Finalize
program_account.borrow_mut().data[0] = 0; // bad elf program_account.borrow_mut().data[0] = 0; // bad elf
let mut keyed_accounts = vec![ let keyed_accounts = vec![
KeyedAccount::new(&program_key, true, &mut program_account), KeyedAccount::new(&program_key, true, &program_account),
KeyedAccount::new(&rent_key, false, &mut rent_account), KeyedAccount::new(&rent_key, false, &rent_account),
]; ];
assert_eq!( assert_eq!(
Err(InstructionError::InvalidAccountData), Err(InstructionError::InvalidAccountData),
process_instruction(&program_id, &mut keyed_accounts, &instruction_data) process_instruction(&program_id, &keyed_accounts, &instruction_data)
); );
} }
@ -365,42 +365,38 @@ mod tests {
let mut file = File::open("test_elfs/noop.so").expect("file open failed"); let mut file = File::open("test_elfs/noop.so").expect("file open failed");
let mut elf = Vec::new(); let mut elf = Vec::new();
file.read_to_end(&mut elf).unwrap(); file.read_to_end(&mut elf).unwrap();
let mut program_account = Account::new_ref(1, 0, &program_id); let program_account = Account::new_ref(1, 0, &program_id);
program_account.borrow_mut().data = elf; program_account.borrow_mut().data = elf;
program_account.borrow_mut().executable = true; program_account.borrow_mut().executable = true;
let mut keyed_accounts = vec![KeyedAccount::new(&program_key, false, &mut program_account)]; let mut keyed_accounts = vec![KeyedAccount::new(&program_key, false, &program_account)];
// Case: Empty keyed accounts // Case: Empty keyed accounts
assert_eq!( assert_eq!(
Err(InstructionError::NotEnoughAccountKeys), Err(InstructionError::NotEnoughAccountKeys),
process_instruction(&program_id, &mut vec![], &vec![]) process_instruction(&program_id, &vec![], &vec![])
); );
// Case: Only a program account // Case: Only a program account
assert_eq!( assert_eq!(
Ok(()), Ok(()),
process_instruction(&program_id, &mut keyed_accounts, &vec![]) process_instruction(&program_id, &keyed_accounts, &vec![])
); );
// Case: Account not executable // Case: Account not executable
keyed_accounts[0].account.borrow_mut().executable = false; keyed_accounts[0].account.borrow_mut().executable = false;
assert_eq!( assert_eq!(
Err(InstructionError::InvalidInstructionData), Err(InstructionError::InvalidInstructionData),
process_instruction(&program_id, &mut keyed_accounts, &vec![]) process_instruction(&program_id, &keyed_accounts, &vec![])
); );
keyed_accounts[0].account.borrow_mut().executable = true; keyed_accounts[0].account.borrow_mut().executable = true;
// Case: With program and parameter account // Case: With program and parameter account
let mut parameter_account = Account::new_ref(1, 0, &program_id); let parameter_account = Account::new_ref(1, 0, &program_id);
keyed_accounts.push(KeyedAccount::new( keyed_accounts.push(KeyedAccount::new(&program_key, false, &parameter_account));
&program_key,
false,
&mut parameter_account,
));
assert_eq!( assert_eq!(
Ok(()), Ok(()),
process_instruction(&program_id, &mut keyed_accounts, &vec![]) process_instruction(&program_id, &keyed_accounts, &vec![])
); );
// Case: With duplicate accounts // Case: With duplicate accounts
@ -410,7 +406,7 @@ mod tests {
keyed_accounts.push(KeyedAccount::new(&duplicate_key, false, &parameter_account)); keyed_accounts.push(KeyedAccount::new(&duplicate_key, false, &parameter_account));
assert_eq!( assert_eq!(
Ok(()), Ok(()),
process_instruction(&program_id, &mut keyed_accounts, &vec![]) process_instruction(&program_id, &keyed_accounts, &vec![])
); );
} }
} }

View File

@ -63,7 +63,7 @@ impl SpvProcessor {
} }
pub fn do_client_request( pub fn do_client_request(
keyed_accounts: &mut [KeyedAccount], keyed_accounts: &[KeyedAccount],
request_info: &ClientRequestInfo, request_info: &ClientRequestInfo,
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
if keyed_accounts.len() != 2 { if keyed_accounts.len() != 2 {
@ -76,7 +76,7 @@ impl SpvProcessor {
Ok(()) //placeholder Ok(()) //placeholder
} }
pub fn do_cancel_request(keyed_accounts: &mut [KeyedAccount]) -> Result<(), InstructionError> { pub fn do_cancel_request(keyed_accounts: &[KeyedAccount]) -> Result<(), InstructionError> {
if keyed_accounts.len() != 2 { if keyed_accounts.len() != 2 {
error!("Client Request invalid accounts argument length (should be 2)") error!("Client Request invalid accounts argument length (should be 2)")
} }
@ -86,7 +86,7 @@ impl SpvProcessor {
} }
pub fn do_submit_proof( pub fn do_submit_proof(
keyed_accounts: &mut [KeyedAccount], keyed_accounts: &[KeyedAccount],
proof_info: &Proof, proof_info: &Proof,
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
if keyed_accounts.len() != 2 { if keyed_accounts.len() != 2 {
@ -99,7 +99,7 @@ impl SpvProcessor {
} }
pub fn process_instruction( pub fn process_instruction(
_program_id: &Pubkey, _program_id: &Pubkey,
keyed_accounts: &mut [KeyedAccount], keyed_accounts: &[KeyedAccount],
data: &[u8], data: &[u8],
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
// solana_logger::setup(); // solana_logger::setup();

View File

@ -18,9 +18,9 @@ use solana_sdk::{
/// will progress one step. /// will progress one step.
fn apply_signature( fn apply_signature(
budget_state: &mut BudgetState, budget_state: &mut BudgetState,
witness_keyed_account: &mut KeyedAccount, witness_keyed_account: &KeyedAccount,
contract_keyed_account: &mut KeyedAccount, contract_keyed_account: &KeyedAccount,
to_keyed_account: Result<&mut KeyedAccount, InstructionError>, to_keyed_account: Result<&KeyedAccount, InstructionError>,
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
let mut final_payment = None; let mut final_payment = None;
if let Some(ref mut expr) = budget_state.pending_budget { if let Some(ref mut expr) = budget_state.pending_budget {
@ -54,9 +54,9 @@ fn apply_signature(
/// will progress one step. /// will progress one step.
fn apply_timestamp( fn apply_timestamp(
budget_state: &mut BudgetState, budget_state: &mut BudgetState,
witness_keyed_account: &mut KeyedAccount, witness_keyed_account: &KeyedAccount,
contract_keyed_account: &mut KeyedAccount, contract_keyed_account: &KeyedAccount,
to_keyed_account: Result<&mut KeyedAccount, InstructionError>, to_keyed_account: Result<&KeyedAccount, InstructionError>,
dt: DateTime<Utc>, dt: DateTime<Utc>,
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
// Check to see if any timelocked transactions can be completed. // Check to see if any timelocked transactions can be completed.
@ -84,9 +84,9 @@ fn apply_timestamp(
/// Process an AccountData Witness and any payment waiting on it. /// Process an AccountData Witness and any payment waiting on it.
fn apply_account_data( fn apply_account_data(
budget_state: &mut BudgetState, budget_state: &mut BudgetState,
witness_keyed_account: &mut KeyedAccount, witness_keyed_account: &KeyedAccount,
contract_keyed_account: &mut KeyedAccount, contract_keyed_account: &KeyedAccount,
to_keyed_account: Result<&mut KeyedAccount, InstructionError>, to_keyed_account: Result<&KeyedAccount, InstructionError>,
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
// Check to see if any timelocked transactions can be completed. // Check to see if any timelocked transactions can be completed.
let mut final_payment = None; let mut final_payment = None;
@ -114,10 +114,10 @@ fn apply_account_data(
pub fn process_instruction( pub fn process_instruction(
_program_id: &Pubkey, _program_id: &Pubkey,
keyed_accounts: &mut [KeyedAccount], keyed_accounts: &[KeyedAccount],
data: &[u8], data: &[u8],
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
let keyed_accounts_iter = &mut keyed_accounts.iter_mut(); let keyed_accounts_iter = &mut keyed_accounts.iter();
let instruction = limited_deserialize(data)?; let instruction = limited_deserialize(data)?;
trace!("process_instruction: {:?}", instruction); trace!("process_instruction: {:?}", instruction);

View File

@ -10,7 +10,7 @@ use solana_sdk::pubkey::Pubkey;
pub fn process_instruction( pub fn process_instruction(
_program_id: &Pubkey, _program_id: &Pubkey,
keyed_accounts: &mut [KeyedAccount], keyed_accounts: &[KeyedAccount],
data: &[u8], data: &[u8],
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
let key_list: ConfigKeys = limited_deserialize(data)?; let key_list: ConfigKeys = limited_deserialize(data)?;
@ -154,14 +154,14 @@ mod tests {
} => space, } => space,
_ => panic!("Not a CreateAccount system instruction"), _ => panic!("Not a CreateAccount system instruction"),
}; };
let mut config_account = RefCell::new(Account { let config_account = RefCell::new(Account {
data: vec![0; space as usize], data: vec![0; space as usize],
..Account::default() ..Account::default()
}); });
let mut accounts = vec![(&config_pubkey, true, &mut config_account)]; let accounts = vec![(&config_pubkey, true, &config_account)];
let mut keyed_accounts = create_keyed_is_signer_accounts(&mut accounts); let keyed_accounts = create_keyed_is_signer_accounts(&accounts);
assert_eq!( assert_eq!(
process_instruction(&id(), &mut keyed_accounts, &instructions[1].data), process_instruction(&id(), &keyed_accounts, &instructions[1].data),
Ok(()) Ok(())
); );
@ -183,15 +183,15 @@ mod tests {
fn test_process_store_ok() { fn test_process_store_ok() {
solana_logger::setup(); solana_logger::setup();
let keys = vec![]; let keys = vec![];
let (config_keypair, mut config_account) = create_config_account(keys.clone()); let (config_keypair, config_account) = create_config_account(keys.clone());
let config_pubkey = config_keypair.pubkey(); let config_pubkey = config_keypair.pubkey();
let my_config = MyConfig::new(42); let my_config = MyConfig::new(42);
let instruction = config_instruction::store(&config_pubkey, true, keys.clone(), &my_config); let instruction = config_instruction::store(&config_pubkey, true, keys.clone(), &my_config);
let mut accounts = vec![(&config_pubkey, true, &mut config_account)]; let accounts = vec![(&config_pubkey, true, &config_account)];
let mut keyed_accounts = create_keyed_is_signer_accounts(&mut accounts); let keyed_accounts = create_keyed_is_signer_accounts(&accounts);
assert_eq!( assert_eq!(
process_instruction(&id(), &mut keyed_accounts, &instruction.data), process_instruction(&id(), &keyed_accounts, &instruction.data),
Ok(()) Ok(())
); );
assert_eq!( assert_eq!(
@ -204,17 +204,17 @@ mod tests {
fn test_process_store_fail_instruction_data_too_large() { fn test_process_store_fail_instruction_data_too_large() {
solana_logger::setup(); solana_logger::setup();
let keys = vec![]; let keys = vec![];
let (config_keypair, mut config_account) = create_config_account(keys.clone()); let (config_keypair, config_account) = create_config_account(keys.clone());
let config_pubkey = config_keypair.pubkey(); let config_pubkey = config_keypair.pubkey();
let my_config = MyConfig::new(42); let my_config = MyConfig::new(42);
let mut instruction = let mut instruction =
config_instruction::store(&config_pubkey, true, keys.clone(), &my_config); config_instruction::store(&config_pubkey, true, keys.clone(), &my_config);
instruction.data = vec![0; 123]; // <-- Replace data with a vector that's too large instruction.data = vec![0; 123]; // <-- Replace data with a vector that's too large
let mut accounts = vec![(&config_pubkey, true, &mut config_account)]; let accounts = vec![(&config_pubkey, true, &config_account)];
let mut keyed_accounts = create_keyed_is_signer_accounts(&mut accounts); let keyed_accounts = create_keyed_is_signer_accounts(&accounts);
assert_eq!( assert_eq!(
process_instruction(&id(), &mut keyed_accounts, &instruction.data), process_instruction(&id(), &keyed_accounts, &instruction.data),
Err(InstructionError::InvalidInstructionData) Err(InstructionError::InvalidInstructionData)
); );
} }
@ -223,16 +223,16 @@ mod tests {
fn test_process_store_fail_account0_not_signer() { fn test_process_store_fail_account0_not_signer() {
solana_logger::setup(); solana_logger::setup();
let keys = vec![]; let keys = vec![];
let (config_keypair, mut config_account) = create_config_account(keys.clone()); let (config_keypair, config_account) = create_config_account(keys.clone());
let config_pubkey = config_keypair.pubkey(); let config_pubkey = config_keypair.pubkey();
let my_config = MyConfig::new(42); let my_config = MyConfig::new(42);
let mut instruction = config_instruction::store(&config_pubkey, true, vec![], &my_config); let mut instruction = config_instruction::store(&config_pubkey, true, vec![], &my_config);
instruction.accounts[0].is_signer = false; // <----- not a signer instruction.accounts[0].is_signer = false; // <----- not a signer
let mut accounts = vec![(&config_pubkey, false, &mut config_account)]; let accounts = vec![(&config_pubkey, false, &config_account)];
let mut keyed_accounts = create_keyed_is_signer_accounts(&mut accounts); let keyed_accounts = create_keyed_is_signer_accounts(&accounts);
assert_eq!( assert_eq!(
process_instruction(&id(), &mut keyed_accounts, &instruction.data), process_instruction(&id(), &keyed_accounts, &instruction.data),
Err(InstructionError::MissingRequiredSignature) Err(InstructionError::MissingRequiredSignature)
); );
} }
@ -248,21 +248,21 @@ mod tests {
(signer0_pubkey, true), (signer0_pubkey, true),
(signer1_pubkey, true), (signer1_pubkey, true),
]; ];
let (config_keypair, mut config_account) = create_config_account(keys.clone()); let (config_keypair, config_account) = create_config_account(keys.clone());
let config_pubkey = config_keypair.pubkey(); let config_pubkey = config_keypair.pubkey();
let my_config = MyConfig::new(42); let my_config = MyConfig::new(42);
let instruction = config_instruction::store(&config_pubkey, true, keys.clone(), &my_config); let instruction = config_instruction::store(&config_pubkey, true, keys.clone(), &my_config);
let mut signer0_account = RefCell::new(Account::default()); let signer0_account = RefCell::new(Account::default());
let mut signer1_account = RefCell::new(Account::default()); let signer1_account = RefCell::new(Account::default());
let mut accounts = vec![ let accounts = vec![
(&config_pubkey, true, &mut config_account), (&config_pubkey, true, &config_account),
(&signer0_pubkey, true, &mut signer0_account), (&signer0_pubkey, true, &signer0_account),
(&signer1_pubkey, true, &mut signer1_account), (&signer1_pubkey, true, &signer1_account),
]; ];
let mut keyed_accounts = create_keyed_is_signer_accounts(&mut accounts); let keyed_accounts = create_keyed_is_signer_accounts(&accounts);
assert_eq!( assert_eq!(
process_instruction(&id(), &mut keyed_accounts, &instruction.data), process_instruction(&id(), &keyed_accounts, &instruction.data),
Ok(()) Ok(())
); );
let meta_data: ConfigKeys = deserialize(&config_account.borrow().data).unwrap(); let meta_data: ConfigKeys = deserialize(&config_account.borrow().data).unwrap();
@ -285,11 +285,11 @@ mod tests {
let instruction = let instruction =
config_instruction::store(&config_pubkey, false, keys.clone(), &my_config); config_instruction::store(&config_pubkey, false, keys.clone(), &my_config);
let mut signer0_account = RefCell::new(Account::default()); let signer0_account = RefCell::new(Account::default());
let mut accounts = vec![(&signer0_pubkey, true, &mut signer0_account)]; let accounts = vec![(&signer0_pubkey, true, &signer0_account)];
let mut keyed_accounts = create_keyed_is_signer_accounts(&mut accounts); let keyed_accounts = create_keyed_is_signer_accounts(&accounts);
assert_eq!( assert_eq!(
process_instruction(&id(), &mut keyed_accounts, &instruction.data), process_instruction(&id(), &keyed_accounts, &instruction.data),
Err(InstructionError::InvalidAccountData) Err(InstructionError::InvalidAccountData)
); );
} }
@ -299,34 +299,34 @@ mod tests {
solana_logger::setup(); solana_logger::setup();
let signer0_pubkey = Pubkey::new_rand(); let signer0_pubkey = Pubkey::new_rand();
let signer1_pubkey = Pubkey::new_rand(); let signer1_pubkey = Pubkey::new_rand();
let mut signer0_account = RefCell::new(Account::default()); let signer0_account = RefCell::new(Account::default());
let mut signer1_account = RefCell::new(Account::default()); let signer1_account = RefCell::new(Account::default());
let keys = vec![(signer0_pubkey, true)]; let keys = vec![(signer0_pubkey, true)];
let (config_keypair, mut config_account) = create_config_account(keys.clone()); let (config_keypair, config_account) = create_config_account(keys.clone());
let config_pubkey = config_keypair.pubkey(); let config_pubkey = config_keypair.pubkey();
let my_config = MyConfig::new(42); let my_config = MyConfig::new(42);
let instruction = config_instruction::store(&config_pubkey, true, keys.clone(), &my_config); let instruction = config_instruction::store(&config_pubkey, true, keys.clone(), &my_config);
// Config-data pubkey doesn't match signer // Config-data pubkey doesn't match signer
let mut accounts = vec![ let accounts = vec![
(&config_pubkey, true, &mut config_account), (&config_pubkey, true, &config_account),
(&signer1_pubkey, true, &mut signer1_account), (&signer1_pubkey, true, &signer1_account),
]; ];
let mut keyed_accounts = create_keyed_is_signer_accounts(&mut accounts); let keyed_accounts = create_keyed_is_signer_accounts(&accounts);
assert_eq!( assert_eq!(
process_instruction(&id(), &mut keyed_accounts, &instruction.data), process_instruction(&id(), &keyed_accounts, &instruction.data),
Err(InstructionError::MissingRequiredSignature) Err(InstructionError::MissingRequiredSignature)
); );
// Config-data pubkey not a signer // Config-data pubkey not a signer
let mut accounts = vec![ let accounts = vec![
(&config_pubkey, true, &mut config_account), (&config_pubkey, true, &config_account),
(&signer0_pubkey, false, &mut signer0_account), (&signer0_pubkey, false, &signer0_account),
]; ];
let mut keyed_accounts = create_keyed_is_signer_accounts(&mut accounts); let keyed_accounts = create_keyed_is_signer_accounts(&accounts);
assert_eq!( assert_eq!(
process_instruction(&id(), &mut keyed_accounts, &instruction.data), process_instruction(&id(), &keyed_accounts, &instruction.data),
Err(InstructionError::MissingRequiredSignature) Err(InstructionError::MissingRequiredSignature)
); );
} }
@ -338,27 +338,27 @@ mod tests {
let signer0_pubkey = Pubkey::new_rand(); let signer0_pubkey = Pubkey::new_rand();
let signer1_pubkey = Pubkey::new_rand(); let signer1_pubkey = Pubkey::new_rand();
let signer2_pubkey = Pubkey::new_rand(); let signer2_pubkey = Pubkey::new_rand();
let mut signer0_account = RefCell::new(Account::default()); let signer0_account = RefCell::new(Account::default());
let mut signer1_account = RefCell::new(Account::default()); let signer1_account = RefCell::new(Account::default());
let mut signer2_account = RefCell::new(Account::default()); let signer2_account = RefCell::new(Account::default());
let keys = vec![ let keys = vec![
(pubkey, false), (pubkey, false),
(signer0_pubkey, true), (signer0_pubkey, true),
(signer1_pubkey, true), (signer1_pubkey, true),
]; ];
let (config_keypair, mut config_account) = create_config_account(keys.clone()); let (config_keypair, config_account) = create_config_account(keys.clone());
let config_pubkey = config_keypair.pubkey(); let config_pubkey = config_keypair.pubkey();
let my_config = MyConfig::new(42); let my_config = MyConfig::new(42);
let instruction = config_instruction::store(&config_pubkey, true, keys.clone(), &my_config); let instruction = config_instruction::store(&config_pubkey, true, keys.clone(), &my_config);
let mut accounts = vec![ let accounts = vec![
(&config_pubkey, true, &mut config_account), (&config_pubkey, true, &config_account),
(&signer0_pubkey, true, &mut signer0_account), (&signer0_pubkey, true, &signer0_account),
(&signer1_pubkey, true, &mut signer1_account), (&signer1_pubkey, true, &signer1_account),
]; ];
let mut keyed_accounts = create_keyed_is_signer_accounts(&mut accounts); let keyed_accounts = create_keyed_is_signer_accounts(&accounts);
assert_eq!( assert_eq!(
process_instruction(&id(), &mut keyed_accounts, &instruction.data), process_instruction(&id(), &keyed_accounts, &instruction.data),
Ok(()) Ok(())
); );
@ -366,14 +366,14 @@ mod tests {
let new_config = MyConfig::new(84); let new_config = MyConfig::new(84);
let instruction = let instruction =
config_instruction::store(&config_pubkey, false, keys.clone(), &new_config); config_instruction::store(&config_pubkey, false, keys.clone(), &new_config);
let mut accounts = vec![ let accounts = vec![
(&config_pubkey, false, &mut config_account), (&config_pubkey, false, &config_account),
(&signer0_pubkey, true, &mut signer0_account), (&signer0_pubkey, true, &signer0_account),
(&signer1_pubkey, true, &mut signer1_account), (&signer1_pubkey, true, &signer1_account),
]; ];
let mut keyed_accounts = create_keyed_is_signer_accounts(&mut accounts); let keyed_accounts = create_keyed_is_signer_accounts(&accounts);
assert_eq!( assert_eq!(
process_instruction(&id(), &mut keyed_accounts, &instruction.data), process_instruction(&id(), &keyed_accounts, &instruction.data),
Ok(()) Ok(())
); );
let meta_data: ConfigKeys = deserialize(&config_account.borrow().data).unwrap(); let meta_data: ConfigKeys = deserialize(&config_account.borrow().data).unwrap();
@ -387,14 +387,14 @@ mod tests {
let keys = vec![(pubkey, false), (signer0_pubkey, true)]; let keys = vec![(pubkey, false), (signer0_pubkey, true)];
let instruction = let instruction =
config_instruction::store(&config_pubkey, false, keys.clone(), &my_config); config_instruction::store(&config_pubkey, false, keys.clone(), &my_config);
let mut accounts = vec![ let accounts = vec![
(&config_pubkey, false, &mut config_account), (&config_pubkey, false, &config_account),
(&signer0_pubkey, true, &mut signer0_account), (&signer0_pubkey, true, &signer0_account),
(&signer1_pubkey, false, &mut signer1_account), (&signer1_pubkey, false, &signer1_account),
]; ];
let mut keyed_accounts = create_keyed_is_signer_accounts(&mut accounts); let keyed_accounts = create_keyed_is_signer_accounts(&accounts);
assert_eq!( assert_eq!(
process_instruction(&id(), &mut keyed_accounts, &instruction.data), process_instruction(&id(), &keyed_accounts, &instruction.data),
Err(InstructionError::MissingRequiredSignature) Err(InstructionError::MissingRequiredSignature)
); );
@ -406,14 +406,14 @@ mod tests {
]; ];
let instruction = let instruction =
config_instruction::store(&config_pubkey, false, keys.clone(), &my_config); config_instruction::store(&config_pubkey, false, keys.clone(), &my_config);
let mut accounts = vec![ let accounts = vec![
(&config_pubkey, false, &mut config_account), (&config_pubkey, false, &config_account),
(&signer0_pubkey, true, &mut signer0_account), (&signer0_pubkey, true, &signer0_account),
(&signer2_pubkey, true, &mut signer2_account), (&signer2_pubkey, true, &signer2_account),
]; ];
let mut keyed_accounts = create_keyed_is_signer_accounts(&mut accounts); let keyed_accounts = create_keyed_is_signer_accounts(&accounts);
assert_eq!( assert_eq!(
process_instruction(&id(), &mut keyed_accounts, &instruction.data), process_instruction(&id(), &keyed_accounts, &instruction.data),
Err(InstructionError::MissingRequiredSignature) Err(InstructionError::MissingRequiredSignature)
); );
} }
@ -423,13 +423,13 @@ mod tests {
solana_logger::setup(); solana_logger::setup();
let pubkey = Pubkey::new_rand(); let pubkey = Pubkey::new_rand();
let signer0_pubkey = Pubkey::new_rand(); let signer0_pubkey = Pubkey::new_rand();
let mut signer0_account = RefCell::new(Account::default()); let signer0_account = RefCell::new(Account::default());
let keys = vec![ let keys = vec![
(pubkey, false), (pubkey, false),
(signer0_pubkey, true), (signer0_pubkey, true),
(signer0_pubkey, true), (signer0_pubkey, true),
]; // Dummy keys for account sizing ]; // Dummy keys for account sizing
let (config_keypair, mut config_account) = create_config_account(keys.clone()); let (config_keypair, config_account) = create_config_account(keys.clone());
let config_pubkey = config_keypair.pubkey(); let config_pubkey = config_keypair.pubkey();
let my_config = MyConfig::new(42); let my_config = MyConfig::new(42);
@ -440,13 +440,13 @@ mod tests {
]; ];
let instruction = config_instruction::store(&config_pubkey, true, keys.clone(), &my_config); let instruction = config_instruction::store(&config_pubkey, true, keys.clone(), &my_config);
let mut accounts = vec![ let accounts = vec![
(&config_pubkey, true, &mut config_account), (&config_pubkey, true, &config_account),
(&signer0_pubkey, true, &mut signer0_account), (&signer0_pubkey, true, &signer0_account),
]; ];
let mut keyed_accounts = create_keyed_is_signer_accounts(&mut accounts); let keyed_accounts = create_keyed_is_signer_accounts(&accounts);
assert_eq!( assert_eq!(
process_instruction(&id(), &mut keyed_accounts, &instruction.data), process_instruction(&id(), &keyed_accounts, &instruction.data),
Ok(()) Ok(())
); );
@ -454,13 +454,13 @@ mod tests {
let new_config = MyConfig::new(84); let new_config = MyConfig::new(84);
let instruction = let instruction =
config_instruction::store(&config_pubkey, true, keys.clone(), &new_config); config_instruction::store(&config_pubkey, true, keys.clone(), &new_config);
let mut accounts = vec![ let accounts = vec![
(&config_pubkey, true, &mut config_account), (&config_pubkey, true, &config_account),
(&signer0_pubkey, true, &mut signer0_account), (&signer0_pubkey, true, &signer0_account),
]; ];
let mut keyed_accounts = create_keyed_is_signer_accounts(&mut accounts); let keyed_accounts = create_keyed_is_signer_accounts(&accounts);
assert_eq!( assert_eq!(
process_instruction(&id(), &mut keyed_accounts, &instruction.data), process_instruction(&id(), &keyed_accounts, &instruction.data),
Ok(()) Ok(())
); );
let meta_data: ConfigKeys = deserialize(&config_account.borrow().data).unwrap(); let meta_data: ConfigKeys = deserialize(&config_account.borrow().data).unwrap();
@ -473,10 +473,10 @@ mod tests {
// Attempt update with incomplete signatures // Attempt update with incomplete signatures
let keys = vec![(pubkey, false), (config_keypair.pubkey(), true)]; let keys = vec![(pubkey, false), (config_keypair.pubkey(), true)];
let instruction = config_instruction::store(&config_pubkey, true, keys.clone(), &my_config); let instruction = config_instruction::store(&config_pubkey, true, keys.clone(), &my_config);
let mut accounts = vec![(&config_pubkey, true, &mut config_account)]; let accounts = vec![(&config_pubkey, true, &config_account)];
let mut keyed_accounts = create_keyed_is_signer_accounts(&mut accounts); let keyed_accounts = create_keyed_is_signer_accounts(&accounts);
assert_eq!( assert_eq!(
process_instruction(&id(), &mut keyed_accounts, &instruction.data), process_instruction(&id(), &keyed_accounts, &instruction.data),
Err(InstructionError::MissingRequiredSignature) Err(InstructionError::MissingRequiredSignature)
); );
} }
@ -487,10 +487,10 @@ mod tests {
let config_pubkey = Pubkey::new_rand(); let config_pubkey = Pubkey::new_rand();
let instructions = let instructions =
config_instruction::create_account::<MyConfig>(&from_pubkey, &config_pubkey, 1, vec![]); config_instruction::create_account::<MyConfig>(&from_pubkey, &config_pubkey, 1, vec![]);
let mut accounts = vec![]; let accounts = vec![];
let mut keyed_accounts = create_keyed_is_signer_accounts(&mut accounts); let keyed_accounts = create_keyed_is_signer_accounts(&accounts);
assert_eq!( assert_eq!(
process_instruction(&id(), &mut keyed_accounts, &instructions[1].data), process_instruction(&id(), &keyed_accounts, &instructions[1].data),
Err(InstructionError::NotEnoughAccountKeys) Err(InstructionError::NotEnoughAccountKeys)
); );
} }

View File

@ -156,7 +156,7 @@ impl ExchangeProcessor {
Ok(()) Ok(())
} }
fn do_account_request(keyed_accounts: &mut [KeyedAccount]) -> Result<(), InstructionError> { fn do_account_request(keyed_accounts: &[KeyedAccount]) -> Result<(), InstructionError> {
const OWNER_INDEX: usize = 0; const OWNER_INDEX: usize = 0;
const NEW_ACCOUNT_INDEX: usize = 1; const NEW_ACCOUNT_INDEX: usize = 1;
@ -178,7 +178,7 @@ impl ExchangeProcessor {
} }
fn do_transfer_request( fn do_transfer_request(
keyed_accounts: &mut [KeyedAccount], keyed_accounts: &[KeyedAccount],
token: Token, token: Token,
tokens: u64, tokens: u64,
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
@ -266,7 +266,7 @@ impl ExchangeProcessor {
} }
fn do_order_request( fn do_order_request(
keyed_accounts: &mut [KeyedAccount], keyed_accounts: &[KeyedAccount],
info: &OrderRequestInfo, info: &OrderRequestInfo,
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
const OWNER_INDEX: usize = 0; const OWNER_INDEX: usize = 0;
@ -322,7 +322,7 @@ impl ExchangeProcessor {
) )
} }
fn do_order_cancellation(keyed_accounts: &mut [KeyedAccount]) -> Result<(), InstructionError> { fn do_order_cancellation(keyed_accounts: &[KeyedAccount]) -> Result<(), InstructionError> {
const OWNER_INDEX: usize = 0; const OWNER_INDEX: usize = 0;
const ORDER_INDEX: usize = 1; const ORDER_INDEX: usize = 1;
@ -354,7 +354,7 @@ impl ExchangeProcessor {
) )
} }
fn do_swap_request(keyed_accounts: &mut [KeyedAccount]) -> Result<(), InstructionError> { fn do_swap_request(keyed_accounts: &[KeyedAccount]) -> Result<(), InstructionError> {
const TO_ORDER_INDEX: usize = 1; const TO_ORDER_INDEX: usize = 1;
const FROM_ORDER_INDEX: usize = 2; const FROM_ORDER_INDEX: usize = 2;
const PROFIT_ACCOUNT_INDEX: usize = 3; const PROFIT_ACCOUNT_INDEX: usize = 3;
@ -438,7 +438,7 @@ impl ExchangeProcessor {
pub fn process_instruction( pub fn process_instruction(
_program_id: &Pubkey, _program_id: &Pubkey,
keyed_accounts: &mut [KeyedAccount], keyed_accounts: &[KeyedAccount],
data: &[u8], data: &[u8],
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
solana_logger::setup(); solana_logger::setup();

View File

@ -10,7 +10,7 @@ solana_sdk::declare_program!(
fn process_instruction( fn process_instruction(
_program_id: &Pubkey, _program_id: &Pubkey,
_keyed_accounts: &mut [KeyedAccount], _keyed_accounts: &[KeyedAccount],
_data: &[u8], _data: &[u8],
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
Err(InstructionError::GenericError) Err(InstructionError::GenericError)

View File

@ -6,12 +6,12 @@ use log::*;
use serde_derive::{Deserialize, Serialize}; use serde_derive::{Deserialize, Serialize};
use solana_sdk::{ use solana_sdk::{
account::KeyedAccount, account::KeyedAccount,
account_utils::State,
instruction::InstructionError, instruction::InstructionError,
instruction_processor_utils::{is_executable, limited_deserialize, next_keyed_account}, instruction_processor_utils::{is_executable, limited_deserialize, next_keyed_account},
move_loader::id, move_loader::id,
pubkey::Pubkey, pubkey::Pubkey,
sysvar::rent, sysvar::rent,
account_utils::State,
}; };
use types::{ use types::{
account_address::AccountAddress, account_address::AccountAddress,
@ -206,13 +206,13 @@ impl MoveProcessor {
fn data_store_to_keyed_accounts( fn data_store_to_keyed_accounts(
data_store: DataStore, data_store: DataStore,
keyed_accounts: &mut [KeyedAccount], keyed_accounts: &[KeyedAccount],
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
let mut write_sets = data_store let mut write_sets = data_store
.into_write_sets() .into_write_sets()
.map_err(|_| InstructionError::GenericError)?; .map_err(|_| InstructionError::GenericError)?;
let mut keyed_accounts_iter = keyed_accounts.iter_mut(); let mut keyed_accounts_iter = keyed_accounts.iter();
// Genesis account holds both mint and stdlib // Genesis account holds both mint and stdlib
let genesis = next_keyed_account(&mut keyed_accounts_iter)?; let genesis = next_keyed_account(&mut keyed_accounts_iter)?;
@ -255,11 +255,11 @@ impl MoveProcessor {
} }
pub fn do_write( pub fn do_write(
keyed_accounts: &mut [KeyedAccount], keyed_accounts: &[KeyedAccount],
offset: u32, offset: u32,
bytes: &[u8], bytes: &[u8],
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
let mut keyed_accounts_iter = keyed_accounts.iter_mut(); let mut keyed_accounts_iter = keyed_accounts.iter();
let keyed_account = next_keyed_account(&mut keyed_accounts_iter)?; let keyed_account = next_keyed_account(&mut keyed_accounts_iter)?;
if keyed_account.signer_key().is_none() { if keyed_account.signer_key().is_none() {
@ -281,8 +281,8 @@ impl MoveProcessor {
Ok(()) Ok(())
} }
pub fn do_finalize(keyed_accounts: &mut [KeyedAccount]) -> Result<(), InstructionError> { pub fn do_finalize(keyed_accounts: &[KeyedAccount]) -> Result<(), InstructionError> {
let mut keyed_accounts_iter = keyed_accounts.iter_mut(); let mut keyed_accounts_iter = keyed_accounts.iter();
let finalized = next_keyed_account(&mut keyed_accounts_iter)?; let finalized = next_keyed_account(&mut keyed_accounts_iter)?;
let rent = next_keyed_account(&mut keyed_accounts_iter)?; let rent = next_keyed_account(&mut keyed_accounts_iter)?;
@ -362,10 +362,10 @@ impl MoveProcessor {
} }
pub fn do_create_genesis( pub fn do_create_genesis(
keyed_accounts: &mut [KeyedAccount], keyed_accounts: &[KeyedAccount],
amount: u64, amount: u64,
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
let mut keyed_accounts_iter = keyed_accounts.iter_mut(); let mut keyed_accounts_iter = keyed_accounts.iter();
let genesis = next_keyed_account(&mut keyed_accounts_iter)?; let genesis = next_keyed_account(&mut keyed_accounts_iter)?;
if genesis.owner()? != id() { if genesis.owner()? != id() {
@ -386,12 +386,12 @@ impl MoveProcessor {
} }
pub fn do_invoke_main( pub fn do_invoke_main(
keyed_accounts: &mut [KeyedAccount], keyed_accounts: &[KeyedAccount],
sender_address: AccountAddress, sender_address: AccountAddress,
function_name: String, function_name: String,
args: Vec<TransactionArgument>, args: Vec<TransactionArgument>,
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
let mut keyed_accounts_iter = keyed_accounts.iter_mut(); let mut keyed_accounts_iter = keyed_accounts.iter();
let script = next_keyed_account(&mut keyed_accounts_iter)?; let script = next_keyed_account(&mut keyed_accounts_iter)?;
trace!( trace!(
@ -409,7 +409,7 @@ impl MoveProcessor {
return Err(InstructionError::AccountNotExecutable); return Err(InstructionError::AccountNotExecutable);
} }
let data_accounts = keyed_accounts_iter.into_slice(); let data_accounts = keyed_accounts_iter.as_slice();
let mut data_store = Self::keyed_accounts_to_data_store(&data_accounts)?; let mut data_store = Self::keyed_accounts_to_data_store(&data_accounts)?;
let verified_script = Self::deserialize_verified_script(&script.try_account_ref()?.data)?; let verified_script = Self::deserialize_verified_script(&script.try_account_ref()?.data)?;
@ -431,7 +431,7 @@ impl MoveProcessor {
pub fn process_instruction( pub fn process_instruction(
_program_id: &Pubkey, _program_id: &Pubkey,
keyed_accounts: &mut [KeyedAccount], keyed_accounts: &[KeyedAccount],
instruction_data: &[u8], instruction_data: &[u8],
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
solana_logger::setup(); solana_logger::setup();
@ -500,14 +500,14 @@ mod tests {
let code = "main() { return; }"; let code = "main() { return; }";
let sender_address = AccountAddress::default(); let sender_address = AccountAddress::default();
let mut script = LibraAccount::create_script(&sender_address, code, vec![]); let script = LibraAccount::create_script(&sender_address, code, vec![]);
let rent_id = rent::id(); let rent_id = rent::id();
let mut rent_account = RefCell::new(rent::create_account(1, &Rent::free())); let rent_account = RefCell::new(rent::create_account(1, &Rent::free()));
let mut keyed_accounts = vec![ let keyed_accounts = vec![
KeyedAccount::new(&script.key, true, &mut script.account), KeyedAccount::new(&script.key, true, &script.account),
KeyedAccount::new(&rent_id, false, &mut rent_account), KeyedAccount::new(&rent_id, false, &rent_account),
]; ];
MoveProcessor::do_finalize(&mut keyed_accounts).unwrap(); MoveProcessor::do_finalize(&keyed_accounts).unwrap();
let _ = MoveProcessor::deserialize_verified_script(&script.account.borrow().data).unwrap(); let _ = MoveProcessor::deserialize_verified_script(&script.account.borrow().data).unwrap();
} }
@ -516,14 +516,14 @@ mod tests {
solana_logger::setup(); solana_logger::setup();
let amount = 10_000_000; let amount = 10_000_000;
let mut unallocated = LibraAccount::create_unallocated(BIG_ENOUGH); let unallocated = LibraAccount::create_unallocated(BIG_ENOUGH);
let mut keyed_accounts = vec![KeyedAccount::new( let keyed_accounts = vec![KeyedAccount::new(
&unallocated.key, &unallocated.key,
false, false,
&mut unallocated.account, &unallocated.account,
)]; )];
MoveProcessor::do_create_genesis(&mut keyed_accounts, amount).unwrap(); MoveProcessor::do_create_genesis(&keyed_accounts, amount).unwrap();
assert_eq!( assert_eq!(
bincode::deserialize::<LibraAccountState>( bincode::deserialize::<LibraAccountState>(
@ -541,29 +541,24 @@ mod tests {
let code = "main() { return; }"; let code = "main() { return; }";
let sender_address = AccountAddress::default(); let sender_address = AccountAddress::default();
let mut script = LibraAccount::create_script(&sender_address, code, vec![]); let script = LibraAccount::create_script(&sender_address, code, vec![]);
let mut genesis = LibraAccount::create_genesis(1_000_000_000); let genesis = LibraAccount::create_genesis(1_000_000_000);
let rent_id = rent::id(); let rent_id = rent::id();
let mut rent_account = RefCell::new(rent::create_account(1, &Rent::free())); let rent_account = RefCell::new(rent::create_account(1, &Rent::free()));
let mut keyed_accounts = vec![ let keyed_accounts = vec![
KeyedAccount::new(&script.key, true, &mut script.account), KeyedAccount::new(&script.key, true, &script.account),
KeyedAccount::new(&rent_id, false, &mut rent_account), KeyedAccount::new(&rent_id, false, &rent_account),
]; ];
MoveProcessor::do_finalize(&mut keyed_accounts).unwrap(); MoveProcessor::do_finalize(&keyed_accounts).unwrap();
let mut keyed_accounts = vec![ let keyed_accounts = vec![
KeyedAccount::new(&script.key, true, &mut script.account), KeyedAccount::new(&script.key, true, &script.account),
KeyedAccount::new(&genesis.key, false, &mut genesis.account), KeyedAccount::new(&genesis.key, false, &genesis.account),
]; ];
MoveProcessor::do_invoke_main( MoveProcessor::do_invoke_main(&keyed_accounts, sender_address, "main".to_string(), vec![])
&mut keyed_accounts,
sender_address,
"main".to_string(),
vec![],
)
.unwrap(); .unwrap();
} }
@ -578,12 +573,12 @@ mod tests {
} }
} }
"; ";
let mut module = LibraAccount::create_module(code, vec![]); let module = LibraAccount::create_module(code, vec![]);
let rent_id = rent::id(); let rent_id = rent::id();
let mut rent_account = RefCell::new(rent::create_account(1, &Rent::free())); let rent_account = RefCell::new(rent::create_account(1, &Rent::free()));
let mut keyed_accounts = vec![ let keyed_accounts = vec![
KeyedAccount::new(&module.key, true, &mut module.account), KeyedAccount::new(&module.key, true, &module.account),
KeyedAccount::new(&rent_id, false, &mut rent_account), KeyedAccount::new(&rent_id, false, &rent_account),
]; ];
keyed_accounts[0] keyed_accounts[0]
.account .account
@ -591,7 +586,7 @@ mod tests {
.data .data
.resize(BIG_ENOUGH, 0); .resize(BIG_ENOUGH, 0);
MoveProcessor::do_finalize(&mut keyed_accounts).unwrap(); MoveProcessor::do_finalize(&keyed_accounts).unwrap();
} }
#[test] #[test]
@ -605,26 +600,26 @@ mod tests {
} }
"; ";
let sender_address = AccountAddress::default(); let sender_address = AccountAddress::default();
let mut script = LibraAccount::create_script(&sender_address, code, vec![]); let script = LibraAccount::create_script(&sender_address, code, vec![]);
let mut genesis = LibraAccount::create_genesis(1_000_000_000); let genesis = LibraAccount::create_genesis(1_000_000_000);
let rent_id = rent::id(); let rent_id = rent::id();
let mut rent_account = RefCell::new(rent::create_account(1, &Rent::free())); let rent_account = RefCell::new(rent::create_account(1, &Rent::free()));
let mut keyed_accounts = vec![ let keyed_accounts = vec![
KeyedAccount::new(&script.key, true, &mut script.account), KeyedAccount::new(&script.key, true, &script.account),
KeyedAccount::new(&rent_id, false, &mut rent_account), KeyedAccount::new(&rent_id, false, &rent_account),
]; ];
MoveProcessor::do_finalize(&mut keyed_accounts).unwrap(); MoveProcessor::do_finalize(&keyed_accounts).unwrap();
let mut keyed_accounts = vec![ let keyed_accounts = vec![
KeyedAccount::new(&script.key, true, &mut script.account), KeyedAccount::new(&script.key, true, &script.account),
KeyedAccount::new(&genesis.key, false, &mut genesis.account), KeyedAccount::new(&genesis.key, false, &genesis.account),
]; ];
assert_eq!( assert_eq!(
MoveProcessor::do_invoke_main( MoveProcessor::do_invoke_main(
&mut keyed_accounts, &keyed_accounts,
sender_address, sender_address,
"main".to_string(), "main".to_string(),
vec![], vec![],
@ -640,8 +635,8 @@ mod tests {
let mut data_store = DataStore::default(); let mut data_store = DataStore::default();
let amount = 42; let amount = 42;
let mut accounts = mint_coins(amount).unwrap(); let accounts = mint_coins(amount).unwrap();
let mut accounts_iter = accounts.iter_mut(); let mut accounts_iter = accounts.iter();
let _script = next_libra_account(&mut accounts_iter).unwrap(); let _script = next_libra_account(&mut accounts_iter).unwrap();
let genesis = next_libra_account(&mut accounts_iter).unwrap(); let genesis = next_libra_account(&mut accounts_iter).unwrap();
@ -665,8 +660,8 @@ mod tests {
fn test_invoke_pay_from_sender() { fn test_invoke_pay_from_sender() {
solana_logger::setup(); solana_logger::setup();
let amount_to_mint = 42; let amount_to_mint = 42;
let mut accounts = mint_coins(amount_to_mint).unwrap(); let accounts = mint_coins(amount_to_mint).unwrap();
let mut accounts_iter = accounts.iter_mut(); let mut accounts_iter = accounts.iter();
let _script = next_libra_account(&mut accounts_iter).unwrap(); let _script = next_libra_account(&mut accounts_iter).unwrap();
let genesis = next_libra_account(&mut accounts_iter).unwrap(); let genesis = next_libra_account(&mut accounts_iter).unwrap();
@ -680,28 +675,28 @@ mod tests {
return; return;
} }
"; ";
let mut script = LibraAccount::create_script(&genesis.address, code, vec![]); let script = LibraAccount::create_script(&genesis.address, code, vec![]);
let mut payee = LibraAccount::create_unallocated(BIG_ENOUGH); let payee = LibraAccount::create_unallocated(BIG_ENOUGH);
let rent_id = rent::id(); let rent_id = rent::id();
let mut rent_account = RefCell::new(rent::create_account(1, &Rent::free())); let rent_account = RefCell::new(rent::create_account(1, &Rent::free()));
let mut keyed_accounts = vec![ let keyed_accounts = vec![
KeyedAccount::new(&script.key, true, &mut script.account), KeyedAccount::new(&script.key, true, &script.account),
KeyedAccount::new(&rent_id, false, &mut rent_account), KeyedAccount::new(&rent_id, false, &rent_account),
]; ];
MoveProcessor::do_finalize(&mut keyed_accounts).unwrap(); MoveProcessor::do_finalize(&keyed_accounts).unwrap();
let mut keyed_accounts = vec![ let keyed_accounts = vec![
KeyedAccount::new(&script.key, true, &mut script.account), KeyedAccount::new(&script.key, true, &script.account),
KeyedAccount::new(&genesis.key, false, &mut genesis.account), KeyedAccount::new(&genesis.key, false, &genesis.account),
KeyedAccount::new(&sender.key, false, &mut sender.account), KeyedAccount::new(&sender.key, false, &sender.account),
KeyedAccount::new(&payee.key, false, &mut payee.account), KeyedAccount::new(&payee.key, false, &payee.account),
]; ];
let amount = 2; let amount = 2;
MoveProcessor::do_invoke_main( MoveProcessor::do_invoke_main(
&mut keyed_accounts, &keyed_accounts,
sender.address.clone(), sender.address.clone(),
"main".to_string(), "main".to_string(),
vec![ vec![
@ -739,13 +734,13 @@ mod tests {
", ",
universal_truth universal_truth
); );
let mut module = LibraAccount::create_module(&code, vec![]); let module = LibraAccount::create_module(&code, vec![]);
let rent_id = rent::id(); let rent_id = rent::id();
let mut rent_account = RefCell::new(rent::create_account(1, &Rent::free())); let rent_account = RefCell::new(rent::create_account(1, &Rent::free()));
let mut keyed_accounts = vec![ let keyed_accounts = vec![
KeyedAccount::new(&module.key, true, &mut module.account), KeyedAccount::new(&module.key, true, &module.account),
KeyedAccount::new(&rent_id, false, &mut rent_account), KeyedAccount::new(&rent_id, false, &rent_account),
]; ];
keyed_accounts[0] keyed_accounts[0]
.account .account
@ -753,13 +748,13 @@ mod tests {
.data .data
.resize(BIG_ENOUGH, 0); .resize(BIG_ENOUGH, 0);
MoveProcessor::do_finalize(&mut keyed_accounts).unwrap(); MoveProcessor::do_finalize(&keyed_accounts).unwrap();
// Next invoke the published module // Next invoke the published module
let amount_to_mint = 84; let amount_to_mint = 84;
let mut accounts = mint_coins(amount_to_mint).unwrap(); let accounts = mint_coins(amount_to_mint).unwrap();
let mut accounts_iter = accounts.iter_mut(); let mut accounts_iter = accounts.iter();
let _script = next_libra_account(&mut accounts_iter).unwrap(); let _script = next_libra_account(&mut accounts_iter).unwrap();
let genesis = next_libra_account(&mut accounts_iter).unwrap(); let genesis = next_libra_account(&mut accounts_iter).unwrap();
@ -780,32 +775,32 @@ mod tests {
", ",
module.address module.address
); );
let mut script = LibraAccount::create_script( let script = LibraAccount::create_script(
&genesis.address, &genesis.address,
&code, &code,
vec![&module.account.borrow().data], vec![&module.account.borrow().data],
); );
let mut payee = LibraAccount::create_unallocated(BIG_ENOUGH); let payee = LibraAccount::create_unallocated(BIG_ENOUGH);
let rent_id = rent::id(); let rent_id = rent::id();
let mut rent_account = RefCell::new(rent::create_account(1, &Rent::free())); let rent_account = RefCell::new(rent::create_account(1, &Rent::free()));
let mut keyed_accounts = vec![ let keyed_accounts = vec![
KeyedAccount::new(&script.key, true, &mut script.account), KeyedAccount::new(&script.key, true, &script.account),
KeyedAccount::new(&rent_id, false, &mut rent_account), KeyedAccount::new(&rent_id, false, &rent_account),
]; ];
MoveProcessor::do_finalize(&mut keyed_accounts).unwrap(); MoveProcessor::do_finalize(&keyed_accounts).unwrap();
let mut keyed_accounts = vec![ let keyed_accounts = vec![
KeyedAccount::new(&script.key, true, &mut script.account), KeyedAccount::new(&script.key, true, &script.account),
KeyedAccount::new(&genesis.key, false, &mut genesis.account), KeyedAccount::new(&genesis.key, false, &genesis.account),
KeyedAccount::new(&sender.key, false, &mut sender.account), KeyedAccount::new(&sender.key, false, &sender.account),
KeyedAccount::new(&module.key, false, &mut module.account), KeyedAccount::new(&module.key, false, &module.account),
KeyedAccount::new(&payee.key, false, &mut payee.account), KeyedAccount::new(&payee.key, false, &payee.account),
]; ];
MoveProcessor::do_invoke_main( MoveProcessor::do_invoke_main(
&mut keyed_accounts, &keyed_accounts,
sender.address.clone(), sender.address.clone(),
"main".to_string(), "main".to_string(),
vec![TransactionArgument::Address(payee.address.clone())], vec![TransactionArgument::Address(payee.address.clone())],
@ -833,27 +828,27 @@ mod tests {
return; return;
} }
"; ";
let mut genesis = LibraAccount::create_genesis(1_000_000_000); let genesis = LibraAccount::create_genesis(1_000_000_000);
let mut script = LibraAccount::create_script(&genesis.address.clone(), code, vec![]); let script = LibraAccount::create_script(&genesis.address.clone(), code, vec![]);
let mut payee = LibraAccount::create_unallocated(BIG_ENOUGH); let payee = LibraAccount::create_unallocated(BIG_ENOUGH);
let rent_id = rent::id(); let rent_id = rent::id();
let mut rent_account = RefCell::new(rent::create_account(1, &Rent::free())); let rent_account = RefCell::new(rent::create_account(1, &Rent::free()));
let mut keyed_accounts = vec![ let keyed_accounts = vec![
KeyedAccount::new(&script.key, true, &mut script.account), KeyedAccount::new(&script.key, true, &script.account),
KeyedAccount::new(&rent_id, false, &mut rent_account), KeyedAccount::new(&rent_id, false, &rent_account),
]; ];
MoveProcessor::do_finalize(&mut keyed_accounts).unwrap(); MoveProcessor::do_finalize(&keyed_accounts).unwrap();
let mut keyed_accounts = vec![ let keyed_accounts = vec![
KeyedAccount::new(&script.key, true, &mut script.account), KeyedAccount::new(&script.key, true, &script.account),
KeyedAccount::new(&genesis.key, false, &mut genesis.account), KeyedAccount::new(&genesis.key, false, &genesis.account),
KeyedAccount::new(&payee.key, false, &mut payee.account), KeyedAccount::new(&payee.key, false, &payee.account),
]; ];
MoveProcessor::do_invoke_main( MoveProcessor::do_invoke_main(
&mut keyed_accounts, &keyed_accounts,
account_config::association_address(), account_config::association_address(),
"main".to_string(), "main".to_string(),
vec![ vec![

View File

@ -11,7 +11,7 @@ solana_sdk::declare_program!(
fn process_instruction( fn process_instruction(
program_id: &Pubkey, program_id: &Pubkey,
keyed_accounts: &mut [KeyedAccount], keyed_accounts: &[KeyedAccount],
data: &[u8], data: &[u8],
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
solana_logger::setup(); solana_logger::setup();

View File

@ -28,11 +28,11 @@ fn set_owner(
pub fn process_instruction( pub fn process_instruction(
_program_id: &Pubkey, _program_id: &Pubkey,
keyed_accounts: &mut [KeyedAccount], keyed_accounts: &[KeyedAccount],
data: &[u8], data: &[u8],
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
let new_owner_pubkey: Pubkey = limited_deserialize(data)?; let new_owner_pubkey: Pubkey = limited_deserialize(data)?;
let keyed_accounts_iter = &mut keyed_accounts.iter_mut(); let keyed_accounts_iter = &mut keyed_accounts.iter();
let account_keyed_account = &mut next_keyed_account(keyed_accounts_iter)?; let account_keyed_account = &mut next_keyed_account(keyed_accounts_iter)?;
let mut account_owner_pubkey: Pubkey = let mut account_owner_pubkey: Pubkey =
limited_deserialize(&account_keyed_account.try_account_ref()?.data)?; limited_deserialize(&account_keyed_account.try_account_ref()?.data)?;
@ -154,8 +154,8 @@ mod tests {
let mut account_owner_pubkey = Pubkey::new_rand(); let mut account_owner_pubkey = Pubkey::new_rand();
let owner_pubkey = account_owner_pubkey; let owner_pubkey = account_owner_pubkey;
let new_owner_pubkey = Pubkey::new_rand(); let new_owner_pubkey = Pubkey::new_rand();
let mut account = Account::new_ref(1, 0, &system_program::id()); let account = Account::new_ref(1, 0, &system_program::id());
let owner_keyed_account = KeyedAccount::new(&owner_pubkey, false, &mut account); // <-- Attack! Setting owner without the original owner's signature. let owner_keyed_account = KeyedAccount::new(&owner_pubkey, false, &account); // <-- Attack! Setting owner without the original owner's signature.
let err = set_owner( let err = set_owner(
&mut account_owner_pubkey, &mut account_owner_pubkey,
new_owner_pubkey, new_owner_pubkey,
@ -169,9 +169,9 @@ mod tests {
fn test_ownable_incorrect_owner() { fn test_ownable_incorrect_owner() {
let mut account_owner_pubkey = Pubkey::new_rand(); let mut account_owner_pubkey = Pubkey::new_rand();
let new_owner_pubkey = Pubkey::new_rand(); let new_owner_pubkey = Pubkey::new_rand();
let mut account = Account::new_ref(1, 0, &system_program::id()); let account = Account::new_ref(1, 0, &system_program::id());
let mallory_pubkey = Pubkey::new_rand(); // <-- Attack! Signing with wrong pubkey let mallory_pubkey = Pubkey::new_rand(); // <-- Attack! Signing with wrong pubkey
let owner_keyed_account = KeyedAccount::new(&mallory_pubkey, true, &mut account); let owner_keyed_account = KeyedAccount::new(&mallory_pubkey, true, &account);
let err = set_owner( let err = set_owner(
&mut account_owner_pubkey, &mut account_owner_pubkey,
new_owner_pubkey, new_owner_pubkey,

View File

@ -351,7 +351,7 @@ pub fn deactivate_stake(stake_pubkey: &Pubkey, authorized_pubkey: &Pubkey) -> In
pub fn process_instruction( pub fn process_instruction(
_program_id: &Pubkey, _program_id: &Pubkey,
keyed_accounts: &mut [KeyedAccount], keyed_accounts: &[KeyedAccount],
data: &[u8], data: &[u8],
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
solana_logger::setup(); solana_logger::setup();
@ -361,8 +361,8 @@ pub fn process_instruction(
let signers = get_signers(keyed_accounts); let signers = get_signers(keyed_accounts);
let keyed_accounts = &mut keyed_accounts.iter_mut(); let keyed_accounts = &mut keyed_accounts.iter();
let me = &mut next_keyed_account(keyed_accounts)?; let me = &next_keyed_account(keyed_accounts)?;
match limited_deserialize(data)? { match limited_deserialize(data)? {
StakeInstruction::Initialize(authorized, lockup) => me.initialize( StakeInstruction::Initialize(authorized, lockup) => me.initialize(
@ -387,12 +387,12 @@ pub fn process_instruction(
) )
} }
StakeInstruction::Split(lamports) => { StakeInstruction::Split(lamports) => {
let split_stake = &mut next_keyed_account(keyed_accounts)?; let split_stake = &next_keyed_account(keyed_accounts)?;
me.split(lamports, split_stake, &signers) me.split(lamports, split_stake, &signers)
} }
StakeInstruction::Withdraw(lamports) => { StakeInstruction::Withdraw(lamports) => {
let to = &mut next_keyed_account(keyed_accounts)?; let to = &next_keyed_account(keyed_accounts)?;
me.withdraw( me.withdraw(
lamports, lamports,
to, to,
@ -420,7 +420,7 @@ mod tests {
} }
fn process_instruction(instruction: &Instruction) -> Result<(), InstructionError> { fn process_instruction(instruction: &Instruction) -> Result<(), InstructionError> {
let mut accounts: Vec<_> = instruction let accounts: Vec<_> = instruction
.accounts .accounts
.iter() .iter()
.map(|meta| { .map(|meta| {
@ -441,13 +441,13 @@ mod tests {
.collect(); .collect();
{ {
let mut keyed_accounts: Vec<_> = instruction let keyed_accounts: Vec<_> = instruction
.accounts .accounts
.iter() .iter()
.zip(accounts.iter_mut()) .zip(accounts.iter())
.map(|(meta, account)| KeyedAccount::new(&meta.pubkey, meta.is_signer, account)) .map(|(meta, account)| KeyedAccount::new(&meta.pubkey, meta.is_signer, account))
.collect(); .collect();
super::process_instruction(&Pubkey::default(), &mut keyed_accounts, &instruction.data) super::process_instruction(&Pubkey::default(), &keyed_accounts, &instruction.data)
} }
} }
@ -525,7 +525,7 @@ mod tests {
assert_eq!( assert_eq!(
super::process_instruction( super::process_instruction(
&Pubkey::default(), &Pubkey::default(),
&mut [], &[],
&serialize(&StakeInstruction::Initialize( &serialize(&StakeInstruction::Initialize(
Authorized::default(), Authorized::default(),
Lockup::default() Lockup::default()
@ -539,10 +539,10 @@ mod tests {
assert_eq!( assert_eq!(
super::process_instruction( super::process_instruction(
&Pubkey::default(), &Pubkey::default(),
&mut [KeyedAccount::new( &[KeyedAccount::new(
&Pubkey::default(), &Pubkey::default(),
false, false,
&mut create_default_account(), &create_default_account(),
)], )],
&serialize(&StakeInstruction::Initialize( &serialize(&StakeInstruction::Initialize(
Authorized::default(), Authorized::default(),
@ -557,9 +557,9 @@ mod tests {
assert_eq!( assert_eq!(
super::process_instruction( super::process_instruction(
&Pubkey::default(), &Pubkey::default(),
&mut [ &[
KeyedAccount::new(&Pubkey::default(), false, &mut create_default_account(),), KeyedAccount::new(&Pubkey::default(), false, &create_default_account(),),
KeyedAccount::new(&sysvar::rent::id(), false, &mut create_default_account(),) KeyedAccount::new(&sysvar::rent::id(), false, &create_default_account(),)
], ],
&serialize(&StakeInstruction::Initialize( &serialize(&StakeInstruction::Initialize(
Authorized::default(), Authorized::default(),
@ -574,12 +574,12 @@ mod tests {
assert_eq!( assert_eq!(
super::process_instruction( super::process_instruction(
&Pubkey::default(), &Pubkey::default(),
&mut [ &[
KeyedAccount::new(&Pubkey::default(), false, &mut create_default_account()), KeyedAccount::new(&Pubkey::default(), false, &create_default_account()),
KeyedAccount::new( KeyedAccount::new(
&sysvar::rent::id(), &sysvar::rent::id(),
false, false,
&mut RefCell::new(sysvar::rent::create_account(0, &Rent::default())) &RefCell::new(sysvar::rent::create_account(0, &Rent::default()))
) )
], ],
&serialize(&StakeInstruction::Initialize( &serialize(&StakeInstruction::Initialize(
@ -595,10 +595,10 @@ mod tests {
assert_eq!( assert_eq!(
super::process_instruction( super::process_instruction(
&Pubkey::default(), &Pubkey::default(),
&mut [KeyedAccount::new( &[KeyedAccount::new(
&Pubkey::default(), &Pubkey::default(),
false, false,
&mut create_default_account() &create_default_account()
),], ),],
&serialize(&StakeInstruction::DelegateStake).unwrap(), &serialize(&StakeInstruction::DelegateStake).unwrap(),
), ),
@ -609,10 +609,10 @@ mod tests {
assert_eq!( assert_eq!(
super::process_instruction( super::process_instruction(
&Pubkey::default(), &Pubkey::default(),
&mut [KeyedAccount::new( &[KeyedAccount::new(
&Pubkey::default(), &Pubkey::default(),
false, false,
&mut create_default_account() &create_default_account()
)], )],
&serialize(&StakeInstruction::DelegateStake).unwrap(), &serialize(&StakeInstruction::DelegateStake).unwrap(),
), ),
@ -623,18 +623,18 @@ mod tests {
assert_eq!( assert_eq!(
super::process_instruction( super::process_instruction(
&Pubkey::default(), &Pubkey::default(),
&mut [ &[
KeyedAccount::new(&Pubkey::default(), true, &mut create_default_account()), KeyedAccount::new(&Pubkey::default(), true, &create_default_account()),
KeyedAccount::new(&Pubkey::default(), false, &mut create_default_account()), KeyedAccount::new(&Pubkey::default(), false, &create_default_account()),
KeyedAccount::new( KeyedAccount::new(
&sysvar::clock::id(), &sysvar::clock::id(),
false, false,
&mut RefCell::new(sysvar::clock::Clock::default().create_account(1)) &RefCell::new(sysvar::clock::Clock::default().create_account(1))
), ),
KeyedAccount::new( KeyedAccount::new(
&config::id(), &config::id(),
false, false,
&mut RefCell::new(config::create_account(0, &config::Config::default())) &RefCell::new(config::create_account(0, &config::Config::default()))
), ),
], ],
&serialize(&StakeInstruction::DelegateStake).unwrap(), &serialize(&StakeInstruction::DelegateStake).unwrap(),
@ -646,18 +646,18 @@ mod tests {
assert_eq!( assert_eq!(
super::process_instruction( super::process_instruction(
&Pubkey::default(), &Pubkey::default(),
&mut [ &[
KeyedAccount::new(&Pubkey::default(), false, &mut create_default_account()), KeyedAccount::new(&Pubkey::default(), false, &create_default_account()),
KeyedAccount::new(&Pubkey::default(), false, &mut create_default_account()), KeyedAccount::new(&Pubkey::default(), false, &create_default_account()),
KeyedAccount::new( KeyedAccount::new(
&sysvar::rewards::id(), &sysvar::rewards::id(),
false, false,
&mut RefCell::new(sysvar::rewards::create_account(1, 0.0, 0.0)) &RefCell::new(sysvar::rewards::create_account(1, 0.0, 0.0))
), ),
KeyedAccount::new( KeyedAccount::new(
&sysvar::stake_history::id(), &sysvar::stake_history::id(),
false, false,
&mut RefCell::new(sysvar::stake_history::create_account( &RefCell::new(sysvar::stake_history::create_account(
1, 1,
&StakeHistory::default() &StakeHistory::default()
)) ))
@ -672,10 +672,10 @@ mod tests {
assert_eq!( assert_eq!(
super::process_instruction( super::process_instruction(
&Pubkey::default(), &Pubkey::default(),
&mut [KeyedAccount::new( &[KeyedAccount::new(
&Pubkey::default(), &Pubkey::default(),
false, false,
&mut create_default_account() &create_default_account()
)], )],
&serialize(&StakeInstruction::Withdraw(42)).unwrap(), &serialize(&StakeInstruction::Withdraw(42)).unwrap(),
), ),
@ -686,12 +686,12 @@ mod tests {
assert_eq!( assert_eq!(
super::process_instruction( super::process_instruction(
&Pubkey::default(), &Pubkey::default(),
&mut [ &[
KeyedAccount::new(&Pubkey::default(), false, &mut create_default_account()), KeyedAccount::new(&Pubkey::default(), false, &create_default_account()),
KeyedAccount::new( KeyedAccount::new(
&sysvar::rewards::id(), &sysvar::rewards::id(),
false, false,
&mut RefCell::new(sysvar::rewards::create_account(1, 0.0, 0.0)) &RefCell::new(sysvar::rewards::create_account(1, 0.0, 0.0))
), ),
], ],
&serialize(&StakeInstruction::Deactivate).unwrap(), &serialize(&StakeInstruction::Deactivate).unwrap(),
@ -703,7 +703,7 @@ mod tests {
assert_eq!( assert_eq!(
super::process_instruction( super::process_instruction(
&Pubkey::default(), &Pubkey::default(),
&mut [], &[],
&serialize(&StakeInstruction::Deactivate).unwrap(), &serialize(&StakeInstruction::Deactivate).unwrap(),
), ),
Err(InstructionError::NotEnoughAccountKeys), Err(InstructionError::NotEnoughAccountKeys),

View File

@ -7,7 +7,7 @@ use crate::{config::Config, id, stake_instruction::StakeError};
use serde_derive::{Deserialize, Serialize}; use serde_derive::{Deserialize, Serialize};
use solana_sdk::{ use solana_sdk::{
account::{Account, KeyedAccount}, account::{Account, KeyedAccount},
account_utils::State, account_utils::{State, StateMut},
clock::{Clock, Epoch, Slot, UnixTimestamp}, clock::{Clock, Epoch, Slot, UnixTimestamp},
instruction::InstructionError, instruction::InstructionError,
pubkey::Pubkey, pubkey::Pubkey,
@ -513,40 +513,40 @@ impl Stake {
pub trait StakeAccount { pub trait StakeAccount {
fn initialize( fn initialize(
&mut self, &self,
authorized: &Authorized, authorized: &Authorized,
lockup: &Lockup, lockup: &Lockup,
rent: &Rent, rent: &Rent,
) -> Result<(), InstructionError>; ) -> Result<(), InstructionError>;
fn authorize( fn authorize(
&mut self, &self,
authority: &Pubkey, authority: &Pubkey,
stake_authorize: StakeAuthorize, stake_authorize: StakeAuthorize,
signers: &HashSet<Pubkey>, signers: &HashSet<Pubkey>,
clock: &Clock, clock: &Clock,
) -> Result<(), InstructionError>; ) -> Result<(), InstructionError>;
fn delegate_stake( fn delegate_stake(
&mut self, &self,
vote_account: &KeyedAccount, vote_account: &KeyedAccount,
clock: &sysvar::clock::Clock, clock: &sysvar::clock::Clock,
config: &Config, config: &Config,
signers: &HashSet<Pubkey>, signers: &HashSet<Pubkey>,
) -> Result<(), InstructionError>; ) -> Result<(), InstructionError>;
fn deactivate_stake( fn deactivate_stake(
&mut self, &self,
clock: &sysvar::clock::Clock, clock: &sysvar::clock::Clock,
signers: &HashSet<Pubkey>, signers: &HashSet<Pubkey>,
) -> Result<(), InstructionError>; ) -> Result<(), InstructionError>;
fn split( fn split(
&mut self, &self,
lamports: u64, lamports: u64,
split_stake: &mut KeyedAccount, split_stake: &KeyedAccount,
signers: &HashSet<Pubkey>, signers: &HashSet<Pubkey>,
) -> Result<(), InstructionError>; ) -> Result<(), InstructionError>;
fn withdraw( fn withdraw(
&mut self, &self,
lamports: u64, lamports: u64,
to: &mut KeyedAccount, to: &KeyedAccount,
clock: &sysvar::clock::Clock, clock: &sysvar::clock::Clock,
stake_history: &sysvar::stake_history::StakeHistory, stake_history: &sysvar::stake_history::StakeHistory,
signers: &HashSet<Pubkey>, signers: &HashSet<Pubkey>,
@ -555,7 +555,7 @@ pub trait StakeAccount {
impl<'a> StakeAccount for KeyedAccount<'a> { impl<'a> StakeAccount for KeyedAccount<'a> {
fn initialize( fn initialize(
&mut self, &self,
authorized: &Authorized, authorized: &Authorized,
lockup: &Lockup, lockup: &Lockup,
rent: &Rent, rent: &Rent,
@ -581,7 +581,7 @@ impl<'a> StakeAccount for KeyedAccount<'a> {
/// multiple times, but will implicitly withdraw authorization from the previously authorized /// multiple times, but will implicitly withdraw authorization from the previously authorized
/// staker. The default staker is the owner of the stake account's pubkey. /// staker. The default staker is the owner of the stake account's pubkey.
fn authorize( fn authorize(
&mut self, &self,
authority: &Pubkey, authority: &Pubkey,
stake_authorize: StakeAuthorize, stake_authorize: StakeAuthorize,
signers: &HashSet<Pubkey>, signers: &HashSet<Pubkey>,
@ -600,7 +600,7 @@ impl<'a> StakeAccount for KeyedAccount<'a> {
} }
} }
fn delegate_stake( fn delegate_stake(
&mut self, &self,
vote_account: &KeyedAccount, vote_account: &KeyedAccount,
clock: &sysvar::clock::Clock, clock: &sysvar::clock::Clock,
config: &Config, config: &Config,
@ -627,7 +627,7 @@ impl<'a> StakeAccount for KeyedAccount<'a> {
} }
} }
fn deactivate_stake( fn deactivate_stake(
&mut self, &self,
clock: &sysvar::clock::Clock, clock: &sysvar::clock::Clock,
signers: &HashSet<Pubkey>, signers: &HashSet<Pubkey>,
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
@ -642,9 +642,9 @@ impl<'a> StakeAccount for KeyedAccount<'a> {
} }
fn split( fn split(
&mut self, &self,
lamports: u64, lamports: u64,
split: &mut KeyedAccount, split: &KeyedAccount,
signers: &HashSet<Pubkey>, signers: &HashSet<Pubkey>,
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
if let StakeState::Uninitialized = split.state()? { if let StakeState::Uninitialized = split.state()? {
@ -706,9 +706,9 @@ impl<'a> StakeAccount for KeyedAccount<'a> {
} }
fn withdraw( fn withdraw(
&mut self, &self,
lamports: u64, lamports: u64,
to: &mut KeyedAccount, to: &KeyedAccount,
clock: &sysvar::clock::Clock, clock: &sysvar::clock::Clock,
stake_history: &sysvar::stake_history::StakeHistory, stake_history: &sysvar::stake_history::StakeHistory,
signers: &HashSet<Pubkey>, signers: &HashSet<Pubkey>,
@ -990,18 +990,18 @@ mod tests {
vote_state.process_slot_vote_unchecked(i); vote_state.process_slot_vote_unchecked(i);
} }
let mut vote_account = RefCell::new(vote_state::create_account( let vote_account = RefCell::new(vote_state::create_account(
&vote_pubkey, &vote_pubkey,
&Pubkey::new_rand(), &Pubkey::new_rand(),
0, 0,
100, 100,
)); ));
let mut vote_keyed_account = KeyedAccount::new(&vote_pubkey, false, &mut vote_account); let vote_keyed_account = KeyedAccount::new(&vote_pubkey, false, &vote_account);
vote_keyed_account.set_state(&vote_state).unwrap(); vote_keyed_account.set_state(&vote_state).unwrap();
let stake_pubkey = Pubkey::new_rand(); let stake_pubkey = Pubkey::new_rand();
let stake_lamports = 42; let stake_lamports = 42;
let mut stake_account = Account::new_ref_data_with_space( let stake_account = Account::new_ref_data_with_space(
stake_lamports, stake_lamports,
&StakeState::Initialized(Meta { &StakeState::Initialized(Meta {
authorized: Authorized { authorized: Authorized {
@ -1016,7 +1016,7 @@ mod tests {
.expect("stake_account"); .expect("stake_account");
// unsigned keyed account // unsigned keyed account
let mut stake_keyed_account = KeyedAccount::new(&stake_pubkey, false, &mut stake_account); let stake_keyed_account = KeyedAccount::new(&stake_pubkey, false, &stake_account);
{ {
let stake_state: StakeState = stake_keyed_account.state().unwrap(); let stake_state: StakeState = stake_keyed_account.state().unwrap();
@ -1044,7 +1044,7 @@ mod tests {
); );
// signed keyed account // signed keyed account
let mut stake_keyed_account = KeyedAccount::new(&stake_pubkey, true, &mut stake_account); let stake_keyed_account = KeyedAccount::new(&stake_pubkey, true, &stake_account);
signers.insert(stake_pubkey); signers.insert(stake_pubkey);
assert!(stake_keyed_account assert!(stake_keyed_account
.delegate_stake(&vote_keyed_account, &clock, &Config::default(), &signers,) .delegate_stake(&vote_keyed_account, &clock, &Config::default(), &signers,)
@ -1451,11 +1451,11 @@ mod tests {
fn test_stake_initialize() { fn test_stake_initialize() {
let stake_pubkey = Pubkey::new_rand(); let stake_pubkey = Pubkey::new_rand();
let stake_lamports = 42; let stake_lamports = 42;
let mut stake_account = let stake_account =
Account::new_ref(stake_lamports, std::mem::size_of::<StakeState>(), &id()); Account::new_ref(stake_lamports, std::mem::size_of::<StakeState>(), &id());
// unsigned keyed account // unsigned keyed account
let mut stake_keyed_account = KeyedAccount::new(&stake_pubkey, false, &mut stake_account); let stake_keyed_account = KeyedAccount::new(&stake_pubkey, false, &stake_account);
let custodian = Pubkey::new_rand(); let custodian = Pubkey::new_rand();
// not enough balance for rent... // not enough balance for rent...
@ -1515,7 +1515,7 @@ mod tests {
fn test_deactivate_stake() { fn test_deactivate_stake() {
let stake_pubkey = Pubkey::new_rand(); let stake_pubkey = Pubkey::new_rand();
let stake_lamports = 42; let stake_lamports = 42;
let mut stake_account = Account::new_ref_data_with_space( let stake_account = Account::new_ref_data_with_space(
stake_lamports, stake_lamports,
&StakeState::Initialized(Meta::auto(&stake_pubkey)), &StakeState::Initialized(Meta::auto(&stake_pubkey)),
std::mem::size_of::<StakeState>(), std::mem::size_of::<StakeState>(),
@ -1529,7 +1529,7 @@ mod tests {
}; };
// signed keyed account but not staked yet // signed keyed account but not staked yet
let mut stake_keyed_account = KeyedAccount::new(&stake_pubkey, true, &mut stake_account); let stake_keyed_account = KeyedAccount::new(&stake_pubkey, true, &stake_account);
let signers = vec![stake_pubkey].into_iter().collect(); let signers = vec![stake_pubkey].into_iter().collect();
assert_eq!( assert_eq!(
stake_keyed_account.deactivate_stake(&clock, &signers), stake_keyed_account.deactivate_stake(&clock, &signers),
@ -1538,13 +1538,13 @@ mod tests {
// Staking // Staking
let vote_pubkey = Pubkey::new_rand(); let vote_pubkey = Pubkey::new_rand();
let mut vote_account = RefCell::new(vote_state::create_account( let vote_account = RefCell::new(vote_state::create_account(
&vote_pubkey, &vote_pubkey,
&Pubkey::new_rand(), &Pubkey::new_rand(),
0, 0,
100, 100,
)); ));
let mut vote_keyed_account = KeyedAccount::new(&vote_pubkey, false, &mut vote_account); let vote_keyed_account = KeyedAccount::new(&vote_pubkey, false, &vote_account);
vote_keyed_account.set_state(&VoteState::default()).unwrap(); vote_keyed_account.set_state(&VoteState::default()).unwrap();
assert_eq!( assert_eq!(
stake_keyed_account.delegate_stake( stake_keyed_account.delegate_stake(
@ -1557,14 +1557,14 @@ mod tests {
); );
// no signers fails // no signers fails
let mut stake_keyed_account = KeyedAccount::new(&stake_pubkey, false, &mut stake_account); let stake_keyed_account = KeyedAccount::new(&stake_pubkey, false, &stake_account);
assert_eq!( assert_eq!(
stake_keyed_account.deactivate_stake(&clock, &HashSet::default()), stake_keyed_account.deactivate_stake(&clock, &HashSet::default()),
Err(InstructionError::MissingRequiredSignature) Err(InstructionError::MissingRequiredSignature)
); );
// Deactivate after staking // Deactivate after staking
let mut stake_keyed_account = KeyedAccount::new(&stake_pubkey, true, &mut stake_account); let stake_keyed_account = KeyedAccount::new(&stake_pubkey, true, &stake_account);
assert_eq!( assert_eq!(
stake_keyed_account.deactivate_stake(&clock, &signers), stake_keyed_account.deactivate_stake(&clock, &signers),
Ok(()) Ok(())
@ -1581,7 +1581,7 @@ mod tests {
fn test_withdraw_stake() { fn test_withdraw_stake() {
let stake_pubkey = Pubkey::new_rand(); let stake_pubkey = Pubkey::new_rand();
let stake_lamports = 42; let stake_lamports = 42;
let mut stake_account = Account::new_ref_data_with_space( let stake_account = Account::new_ref_data_with_space(
stake_lamports, stake_lamports,
&StakeState::Uninitialized, &StakeState::Uninitialized,
std::mem::size_of::<StakeState>(), std::mem::size_of::<StakeState>(),
@ -1592,15 +1592,15 @@ mod tests {
let mut clock = sysvar::clock::Clock::default(); let mut clock = sysvar::clock::Clock::default();
let to = Pubkey::new_rand(); let to = Pubkey::new_rand();
let mut to_account = Account::new_ref(1, 0, &system_program::id()); let to_account = Account::new_ref(1, 0, &system_program::id());
let mut to_keyed_account = KeyedAccount::new(&to, false, &mut to_account); let to_keyed_account = KeyedAccount::new(&to, false, &to_account);
// no signers, should fail // no signers, should fail
let mut stake_keyed_account = KeyedAccount::new(&stake_pubkey, false, &mut stake_account); let stake_keyed_account = KeyedAccount::new(&stake_pubkey, false, &stake_account);
assert_eq!( assert_eq!(
stake_keyed_account.withdraw( stake_keyed_account.withdraw(
stake_lamports, stake_lamports,
&mut to_keyed_account, &to_keyed_account,
&clock, &clock,
&StakeHistory::default(), &StakeHistory::default(),
&HashSet::default(), &HashSet::default(),
@ -1609,13 +1609,13 @@ mod tests {
); );
// signed keyed account and uninitialized should work // signed keyed account and uninitialized should work
let mut stake_keyed_account = KeyedAccount::new(&stake_pubkey, true, &mut stake_account); let stake_keyed_account = KeyedAccount::new(&stake_pubkey, true, &stake_account);
let mut to_keyed_account = KeyedAccount::new(&to, false, &mut to_account); let to_keyed_account = KeyedAccount::new(&to, false, &to_account);
let signers = vec![stake_pubkey].into_iter().collect(); let signers = vec![stake_pubkey].into_iter().collect();
assert_eq!( assert_eq!(
stake_keyed_account.withdraw( stake_keyed_account.withdraw(
stake_lamports, stake_lamports,
&mut to_keyed_account, &to_keyed_account,
&clock, &clock,
&StakeHistory::default(), &StakeHistory::default(),
&signers, &signers,
@ -1628,7 +1628,7 @@ mod tests {
stake_account.borrow_mut().lamports = stake_lamports; stake_account.borrow_mut().lamports = stake_lamports;
// lockup // lockup
let mut stake_keyed_account = KeyedAccount::new(&stake_pubkey, true, &mut stake_account); let stake_keyed_account = KeyedAccount::new(&stake_pubkey, true, &stake_account);
let custodian = Pubkey::new_rand(); let custodian = Pubkey::new_rand();
stake_keyed_account stake_keyed_account
.initialize( .initialize(
@ -1643,12 +1643,12 @@ mod tests {
.unwrap(); .unwrap();
// signed keyed account and locked up, more than available should fail // signed keyed account and locked up, more than available should fail
let mut stake_keyed_account = KeyedAccount::new(&stake_pubkey, true, &mut stake_account); let stake_keyed_account = KeyedAccount::new(&stake_pubkey, true, &stake_account);
let mut to_keyed_account = KeyedAccount::new(&to, false, &mut to_account); let to_keyed_account = KeyedAccount::new(&to, false, &to_account);
assert_eq!( assert_eq!(
stake_keyed_account.withdraw( stake_keyed_account.withdraw(
stake_lamports + 1, stake_lamports + 1,
&mut to_keyed_account, &to_keyed_account,
&clock, &clock,
&StakeHistory::default(), &StakeHistory::default(),
&signers, &signers,
@ -1658,13 +1658,13 @@ mod tests {
// Stake some lamports (available lamports for withdrawals will reduce to zero) // Stake some lamports (available lamports for withdrawals will reduce to zero)
let vote_pubkey = Pubkey::new_rand(); let vote_pubkey = Pubkey::new_rand();
let mut vote_account = RefCell::new(vote_state::create_account( let vote_account = RefCell::new(vote_state::create_account(
&vote_pubkey, &vote_pubkey,
&Pubkey::new_rand(), &Pubkey::new_rand(),
0, 0,
100, 100,
)); ));
let mut vote_keyed_account = KeyedAccount::new(&vote_pubkey, false, &mut vote_account); let vote_keyed_account = KeyedAccount::new(&vote_pubkey, false, &vote_account);
vote_keyed_account.set_state(&VoteState::default()).unwrap(); vote_keyed_account.set_state(&VoteState::default()).unwrap();
assert_eq!( assert_eq!(
stake_keyed_account.delegate_stake( stake_keyed_account.delegate_stake(
@ -1679,12 +1679,12 @@ mod tests {
// simulate rewards // simulate rewards
stake_account.borrow_mut().lamports += 10; stake_account.borrow_mut().lamports += 10;
// withdrawal before deactivate works for rewards amount // withdrawal before deactivate works for rewards amount
let mut stake_keyed_account = KeyedAccount::new(&stake_pubkey, true, &mut stake_account); let stake_keyed_account = KeyedAccount::new(&stake_pubkey, true, &stake_account);
let mut to_keyed_account = KeyedAccount::new(&to, false, &mut to_account); let to_keyed_account = KeyedAccount::new(&to, false, &to_account);
assert_eq!( assert_eq!(
stake_keyed_account.withdraw( stake_keyed_account.withdraw(
10, 10,
&mut to_keyed_account, &to_keyed_account,
&clock, &clock,
&StakeHistory::default(), &StakeHistory::default(),
&signers, &signers,
@ -1695,12 +1695,12 @@ mod tests {
// simulate rewards // simulate rewards
stake_account.borrow_mut().lamports += 10; stake_account.borrow_mut().lamports += 10;
// withdrawal of rewards fails if not in excess of stake // withdrawal of rewards fails if not in excess of stake
let mut stake_keyed_account = KeyedAccount::new(&stake_pubkey, true, &mut stake_account); let stake_keyed_account = KeyedAccount::new(&stake_pubkey, true, &stake_account);
let mut to_keyed_account = KeyedAccount::new(&to, false, &mut to_account); let to_keyed_account = KeyedAccount::new(&to, false, &to_account);
assert_eq!( assert_eq!(
stake_keyed_account.withdraw( stake_keyed_account.withdraw(
10 + 1, 10 + 1,
&mut to_keyed_account, &to_keyed_account,
&clock, &clock,
&StakeHistory::default(), &StakeHistory::default(),
&signers &signers
@ -1717,11 +1717,11 @@ mod tests {
clock.epoch += 100; clock.epoch += 100;
// Try to withdraw more than what's available // Try to withdraw more than what's available
let mut to_keyed_account = KeyedAccount::new(&to, false, &mut to_account); let to_keyed_account = KeyedAccount::new(&to, false, &to_account);
assert_eq!( assert_eq!(
stake_keyed_account.withdraw( stake_keyed_account.withdraw(
stake_lamports + 10 + 1, stake_lamports + 10 + 1,
&mut to_keyed_account, &to_keyed_account,
&clock, &clock,
&StakeHistory::default(), &StakeHistory::default(),
&signers &signers
@ -1730,11 +1730,11 @@ mod tests {
); );
// Try to withdraw all lamports // Try to withdraw all lamports
let mut to_keyed_account = KeyedAccount::new(&to, false, &mut to_account); let to_keyed_account = KeyedAccount::new(&to, false, &to_account);
assert_eq!( assert_eq!(
stake_keyed_account.withdraw( stake_keyed_account.withdraw(
stake_lamports + 10, stake_lamports + 10,
&mut to_keyed_account, &to_keyed_account,
&clock, &clock,
&StakeHistory::default(), &StakeHistory::default(),
&signers &signers
@ -1749,7 +1749,7 @@ mod tests {
let stake_pubkey = Pubkey::new_rand(); let stake_pubkey = Pubkey::new_rand();
let total_lamports = 100; let total_lamports = 100;
let stake_lamports = 42; let stake_lamports = 42;
let mut stake_account = Account::new_ref_data_with_space( let stake_account = Account::new_ref_data_with_space(
total_lamports, total_lamports,
&StakeState::Initialized(Meta::auto(&stake_pubkey)), &StakeState::Initialized(Meta::auto(&stake_pubkey)),
std::mem::size_of::<StakeState>(), std::mem::size_of::<StakeState>(),
@ -1762,20 +1762,20 @@ mod tests {
future.epoch += 16; future.epoch += 16;
let to = Pubkey::new_rand(); let to = Pubkey::new_rand();
let mut to_account = Account::new_ref(1, 0, &system_program::id()); let to_account = Account::new_ref(1, 0, &system_program::id());
let mut to_keyed_account = KeyedAccount::new(&to, false, &mut to_account); let to_keyed_account = KeyedAccount::new(&to, false, &to_account);
let mut stake_keyed_account = KeyedAccount::new(&stake_pubkey, true, &mut stake_account); let stake_keyed_account = KeyedAccount::new(&stake_pubkey, true, &stake_account);
// Stake some lamports (available lamports for withdrawals will reduce) // Stake some lamports (available lamports for withdrawals will reduce)
let vote_pubkey = Pubkey::new_rand(); let vote_pubkey = Pubkey::new_rand();
let mut vote_account = RefCell::new(vote_state::create_account( let vote_account = RefCell::new(vote_state::create_account(
&vote_pubkey, &vote_pubkey,
&Pubkey::new_rand(), &Pubkey::new_rand(),
0, 0,
100, 100,
)); ));
let mut vote_keyed_account = KeyedAccount::new(&vote_pubkey, false, &mut vote_account); let vote_keyed_account = KeyedAccount::new(&vote_pubkey, false, &vote_account);
vote_keyed_account.set_state(&VoteState::default()).unwrap(); vote_keyed_account.set_state(&VoteState::default()).unwrap();
let signers = vec![stake_pubkey].into_iter().collect(); let signers = vec![stake_pubkey].into_iter().collect();
assert_eq!( assert_eq!(
@ -1802,7 +1802,7 @@ mod tests {
assert_eq!( assert_eq!(
stake_keyed_account.withdraw( stake_keyed_account.withdraw(
total_lamports - stake_lamports + 1, total_lamports - stake_lamports + 1,
&mut to_keyed_account, &to_keyed_account,
&clock, &clock,
&stake_history, &stake_history,
&signers, &signers,
@ -1815,7 +1815,7 @@ mod tests {
fn test_withdraw_stake_invalid_state() { fn test_withdraw_stake_invalid_state() {
let stake_pubkey = Pubkey::new_rand(); let stake_pubkey = Pubkey::new_rand();
let total_lamports = 100; let total_lamports = 100;
let mut stake_account = Account::new_ref_data_with_space( let stake_account = Account::new_ref_data_with_space(
total_lamports, total_lamports,
&StakeState::RewardsPool, &StakeState::RewardsPool,
std::mem::size_of::<StakeState>(), std::mem::size_of::<StakeState>(),
@ -1824,14 +1824,14 @@ mod tests {
.expect("stake_account"); .expect("stake_account");
let to = Pubkey::new_rand(); let to = Pubkey::new_rand();
let mut to_account = Account::new_ref(1, 0, &system_program::id()); let to_account = Account::new_ref(1, 0, &system_program::id());
let mut to_keyed_account = KeyedAccount::new(&to, false, &mut to_account); let to_keyed_account = KeyedAccount::new(&to, false, &to_account);
let mut stake_keyed_account = KeyedAccount::new(&stake_pubkey, true, &mut stake_account); let stake_keyed_account = KeyedAccount::new(&stake_pubkey, true, &stake_account);
let signers = vec![stake_pubkey].into_iter().collect(); let signers = vec![stake_pubkey].into_iter().collect();
assert_eq!( assert_eq!(
stake_keyed_account.withdraw( stake_keyed_account.withdraw(
total_lamports, total_lamports,
&mut to_keyed_account, &to_keyed_account,
&sysvar::clock::Clock::default(), &sysvar::clock::Clock::default(),
&StakeHistory::default(), &StakeHistory::default(),
&signers, &signers,
@ -1845,7 +1845,7 @@ mod tests {
let stake_pubkey = Pubkey::new_rand(); let stake_pubkey = Pubkey::new_rand();
let custodian = Pubkey::new_rand(); let custodian = Pubkey::new_rand();
let total_lamports = 100; let total_lamports = 100;
let mut stake_account = Account::new_ref_data_with_space( let stake_account = Account::new_ref_data_with_space(
total_lamports, total_lamports,
&StakeState::Initialized(Meta { &StakeState::Initialized(Meta {
lockup: Lockup { lockup: Lockup {
@ -1861,10 +1861,10 @@ mod tests {
.expect("stake_account"); .expect("stake_account");
let to = Pubkey::new_rand(); let to = Pubkey::new_rand();
let mut to_account = Account::new_ref(1, 0, &system_program::id()); let to_account = Account::new_ref(1, 0, &system_program::id());
let mut to_keyed_account = KeyedAccount::new(&to, false, &mut to_account); let to_keyed_account = KeyedAccount::new(&to, false, &to_account);
let mut stake_keyed_account = KeyedAccount::new(&stake_pubkey, true, &mut stake_account); let stake_keyed_account = KeyedAccount::new(&stake_pubkey, true, &stake_account);
let mut clock = sysvar::clock::Clock::default(); let mut clock = sysvar::clock::Clock::default();
@ -1874,7 +1874,7 @@ mod tests {
assert_eq!( assert_eq!(
stake_keyed_account.withdraw( stake_keyed_account.withdraw(
total_lamports, total_lamports,
&mut to_keyed_account, &to_keyed_account,
&clock, &clock,
&StakeHistory::default(), &StakeHistory::default(),
&signers, &signers,
@ -1888,7 +1888,7 @@ mod tests {
assert_eq!( assert_eq!(
stake_keyed_account.withdraw( stake_keyed_account.withdraw(
total_lamports, total_lamports,
&mut to_keyed_account, &to_keyed_account,
&clock, &clock,
&StakeHistory::default(), &StakeHistory::default(),
&signers_with_custodian, &signers_with_custodian,
@ -1900,12 +1900,12 @@ mod tests {
stake_keyed_account.account.borrow_mut().lamports = total_lamports; stake_keyed_account.account.borrow_mut().lamports = total_lamports;
// lockup has expired // lockup has expired
let mut to_keyed_account = KeyedAccount::new(&to, false, &mut to_account); let to_keyed_account = KeyedAccount::new(&to, false, &to_account);
clock.epoch += 1; clock.epoch += 1;
assert_eq!( assert_eq!(
stake_keyed_account.withdraw( stake_keyed_account.withdraw(
total_lamports, total_lamports,
&mut to_keyed_account, &to_keyed_account,
&clock, &clock,
&StakeHistory::default(), &StakeHistory::default(),
&signers, &signers,
@ -2037,7 +2037,7 @@ mod tests {
fn test_authorize_uninit() { fn test_authorize_uninit() {
let stake_pubkey = Pubkey::new_rand(); let stake_pubkey = Pubkey::new_rand();
let stake_lamports = 42; let stake_lamports = 42;
let mut stake_account = Account::new_ref_data_with_space( let stake_account = Account::new_ref_data_with_space(
stake_lamports, stake_lamports,
&StakeState::default(), &StakeState::default(),
std::mem::size_of::<StakeState>(), std::mem::size_of::<StakeState>(),
@ -2045,7 +2045,7 @@ mod tests {
) )
.expect("stake_account"); .expect("stake_account");
let mut stake_keyed_account = KeyedAccount::new(&stake_pubkey, true, &mut stake_account); let stake_keyed_account = KeyedAccount::new(&stake_pubkey, true, &stake_account);
let signers = vec![stake_pubkey].into_iter().collect(); let signers = vec![stake_pubkey].into_iter().collect();
assert_eq!( assert_eq!(
stake_keyed_account.authorize( stake_keyed_account.authorize(
@ -2062,7 +2062,7 @@ mod tests {
fn test_authorize_lockup() { fn test_authorize_lockup() {
let stake_pubkey = Pubkey::new_rand(); let stake_pubkey = Pubkey::new_rand();
let stake_lamports = 42; let stake_lamports = 42;
let mut stake_account = Account::new_ref_data_with_space( let stake_account = Account::new_ref_data_with_space(
stake_lamports, stake_lamports,
&StakeState::Initialized(Meta::auto(&stake_pubkey)), &StakeState::Initialized(Meta::auto(&stake_pubkey)),
std::mem::size_of::<StakeState>(), std::mem::size_of::<StakeState>(),
@ -2071,11 +2071,11 @@ mod tests {
.expect("stake_account"); .expect("stake_account");
let to = Pubkey::new_rand(); let to = Pubkey::new_rand();
let mut to_account = Account::new_ref(1, 0, &system_program::id()); let to_account = Account::new_ref(1, 0, &system_program::id());
let mut to_keyed_account = KeyedAccount::new(&to, false, &mut to_account); let to_keyed_account = KeyedAccount::new(&to, false, &to_account);
let clock = sysvar::clock::Clock::default(); let clock = sysvar::clock::Clock::default();
let mut stake_keyed_account = KeyedAccount::new(&stake_pubkey, true, &mut stake_account); let stake_keyed_account = KeyedAccount::new(&stake_pubkey, true, &stake_account);
let stake_pubkey0 = Pubkey::new_rand(); let stake_pubkey0 = Pubkey::new_rand();
let signers = vec![stake_pubkey].into_iter().collect(); let signers = vec![stake_pubkey].into_iter().collect();
@ -2158,7 +2158,7 @@ mod tests {
assert_eq!( assert_eq!(
stake_keyed_account.withdraw( stake_keyed_account.withdraw(
stake_lamports, stake_lamports,
&mut to_keyed_account, &to_keyed_account,
&clock, &clock,
&StakeHistory::default(), &StakeHistory::default(),
&signers, // old signer &signers, // old signer
@ -2167,11 +2167,11 @@ mod tests {
); );
// Test a successful action by the currently authorized withdrawer // Test a successful action by the currently authorized withdrawer
let mut to_keyed_account = KeyedAccount::new(&to, false, &mut to_account); let to_keyed_account = KeyedAccount::new(&to, false, &to_account);
assert_eq!( assert_eq!(
stake_keyed_account.withdraw( stake_keyed_account.withdraw(
stake_lamports, stake_lamports,
&mut to_keyed_account, &to_keyed_account,
&clock, &clock,
&StakeHistory::default(), &StakeHistory::default(),
&signers2, &signers2,
@ -2184,7 +2184,7 @@ mod tests {
fn test_split_source_uninitialized() { fn test_split_source_uninitialized() {
let stake_pubkey = Pubkey::new_rand(); let stake_pubkey = Pubkey::new_rand();
let stake_lamports = 42; let stake_lamports = 42;
let mut stake_account = Account::new_ref_data_with_space( let stake_account = Account::new_ref_data_with_space(
stake_lamports, stake_lamports,
&StakeState::Uninitialized, &StakeState::Uninitialized,
std::mem::size_of::<StakeState>(), std::mem::size_of::<StakeState>(),
@ -2193,7 +2193,7 @@ mod tests {
.expect("stake_account"); .expect("stake_account");
let split_stake_pubkey = Pubkey::new_rand(); let split_stake_pubkey = Pubkey::new_rand();
let mut split_stake_account = Account::new_ref_data_with_space( let split_stake_account = Account::new_ref_data_with_space(
0, 0,
&StakeState::Uninitialized, &StakeState::Uninitialized,
std::mem::size_of::<StakeState>(), std::mem::size_of::<StakeState>(),
@ -2201,15 +2201,15 @@ mod tests {
) )
.expect("stake_account"); .expect("stake_account");
let mut stake_keyed_account = KeyedAccount::new(&stake_pubkey, false, &mut stake_account); let stake_keyed_account = KeyedAccount::new(&stake_pubkey, false, &stake_account);
let mut split_stake_keyed_account = let split_stake_keyed_account =
KeyedAccount::new(&split_stake_pubkey, false, &mut split_stake_account); KeyedAccount::new(&split_stake_pubkey, false, &split_stake_account);
// no signers should fail // no signers should fail
assert_eq!( assert_eq!(
stake_keyed_account.split( stake_keyed_account.split(
stake_lamports / 2, stake_lamports / 2,
&mut split_stake_keyed_account, &split_stake_keyed_account,
&HashSet::default() // no signers &HashSet::default() // no signers
), ),
Err(InstructionError::MissingRequiredSignature) Err(InstructionError::MissingRequiredSignature)
@ -2218,7 +2218,7 @@ mod tests {
// this should work // this should work
let signers = vec![stake_pubkey].into_iter().collect(); let signers = vec![stake_pubkey].into_iter().collect();
assert_eq!( assert_eq!(
stake_keyed_account.split(stake_lamports / 2, &mut split_stake_keyed_account, &signers), stake_keyed_account.split(stake_lamports / 2, &split_stake_keyed_account, &signers),
Ok(()) Ok(())
); );
assert_eq!( assert_eq!(
@ -2231,7 +2231,7 @@ mod tests {
fn test_split_split_not_uninitialized() { fn test_split_split_not_uninitialized() {
let stake_pubkey = Pubkey::new_rand(); let stake_pubkey = Pubkey::new_rand();
let stake_lamports = 42; let stake_lamports = 42;
let mut stake_account = Account::new_ref_data_with_space( let stake_account = Account::new_ref_data_with_space(
stake_lamports, stake_lamports,
&StakeState::Stake(Meta::auto(&stake_pubkey), Stake::just_stake(stake_lamports)), &StakeState::Stake(Meta::auto(&stake_pubkey), Stake::just_stake(stake_lamports)),
std::mem::size_of::<StakeState>(), std::mem::size_of::<StakeState>(),
@ -2240,7 +2240,7 @@ mod tests {
.expect("stake_account"); .expect("stake_account");
let split_stake_pubkey = Pubkey::new_rand(); let split_stake_pubkey = Pubkey::new_rand();
let mut split_stake_account = Account::new_ref_data_with_space( let split_stake_account = Account::new_ref_data_with_space(
0, 0,
&StakeState::Initialized(Meta::auto(&stake_pubkey)), &StakeState::Initialized(Meta::auto(&stake_pubkey)),
std::mem::size_of::<StakeState>(), std::mem::size_of::<StakeState>(),
@ -2249,11 +2249,11 @@ mod tests {
.expect("stake_account"); .expect("stake_account");
let signers = vec![stake_pubkey].into_iter().collect(); let signers = vec![stake_pubkey].into_iter().collect();
let mut stake_keyed_account = KeyedAccount::new(&stake_pubkey, true, &mut stake_account); let stake_keyed_account = KeyedAccount::new(&stake_pubkey, true, &stake_account);
let mut split_stake_keyed_account = let split_stake_keyed_account =
KeyedAccount::new(&split_stake_pubkey, true, &mut split_stake_account); KeyedAccount::new(&split_stake_pubkey, true, &split_stake_account);
assert_eq!( assert_eq!(
stake_keyed_account.split(stake_lamports / 2, &mut split_stake_keyed_account, &signers), stake_keyed_account.split(stake_lamports / 2, &split_stake_keyed_account, &signers),
Err(InstructionError::InvalidAccountData) Err(InstructionError::InvalidAccountData)
); );
} }
@ -2273,7 +2273,7 @@ mod tests {
fn test_split_more_than_staked() { fn test_split_more_than_staked() {
let stake_pubkey = Pubkey::new_rand(); let stake_pubkey = Pubkey::new_rand();
let stake_lamports = 42; let stake_lamports = 42;
let mut stake_account = Account::new_ref_data_with_space( let stake_account = Account::new_ref_data_with_space(
stake_lamports, stake_lamports,
&StakeState::Stake( &StakeState::Stake(
Meta::auto(&stake_pubkey), Meta::auto(&stake_pubkey),
@ -2285,7 +2285,7 @@ mod tests {
.expect("stake_account"); .expect("stake_account");
let split_stake_pubkey = Pubkey::new_rand(); let split_stake_pubkey = Pubkey::new_rand();
let mut split_stake_account = Account::new_ref_data_with_space( let split_stake_account = Account::new_ref_data_with_space(
0, 0,
&StakeState::Uninitialized, &StakeState::Uninitialized,
std::mem::size_of::<StakeState>(), std::mem::size_of::<StakeState>(),
@ -2294,11 +2294,11 @@ mod tests {
.expect("stake_account"); .expect("stake_account");
let signers = vec![stake_pubkey].into_iter().collect(); let signers = vec![stake_pubkey].into_iter().collect();
let mut stake_keyed_account = KeyedAccount::new(&stake_pubkey, true, &mut stake_account); let stake_keyed_account = KeyedAccount::new(&stake_pubkey, true, &stake_account);
let mut split_stake_keyed_account = let split_stake_keyed_account =
KeyedAccount::new(&split_stake_pubkey, true, &mut split_stake_account); KeyedAccount::new(&split_stake_pubkey, true, &split_stake_account);
assert_eq!( assert_eq!(
stake_keyed_account.split(stake_lamports / 2, &mut split_stake_keyed_account, &signers), stake_keyed_account.split(stake_lamports / 2, &split_stake_keyed_account, &signers),
Err(StakeError::InsufficientStake.into()) Err(StakeError::InsufficientStake.into())
); );
} }
@ -2325,7 +2325,7 @@ mod tests {
Stake::just_stake(stake_lamports - rent_exempt_reserve), Stake::just_stake(stake_lamports - rent_exempt_reserve),
), ),
] { ] {
let mut stake_account = Account::new_ref_data_with_space( let stake_account = Account::new_ref_data_with_space(
stake_lamports, stake_lamports,
state, state,
std::mem::size_of::<StakeState>(), std::mem::size_of::<StakeState>(),
@ -2333,10 +2333,9 @@ mod tests {
) )
.expect("stake_account"); .expect("stake_account");
let mut stake_keyed_account = let stake_keyed_account = KeyedAccount::new(&stake_pubkey, true, &stake_account);
KeyedAccount::new(&stake_pubkey, true, &mut stake_account);
let mut split_stake_account = Account::new_ref_data_with_space( let split_stake_account = Account::new_ref_data_with_space(
0, 0,
&StakeState::Uninitialized, &StakeState::Uninitialized,
std::mem::size_of::<StakeState>(), std::mem::size_of::<StakeState>(),
@ -2344,14 +2343,14 @@ mod tests {
) )
.expect("stake_account"); .expect("stake_account");
let mut split_stake_keyed_account = let split_stake_keyed_account =
KeyedAccount::new(&split_stake_pubkey, true, &mut split_stake_account); KeyedAccount::new(&split_stake_pubkey, true, &split_stake_account);
// not enough to make a stake account // not enough to make a stake account
assert_eq!( assert_eq!(
stake_keyed_account.split( stake_keyed_account.split(
rent_exempt_reserve - 1, rent_exempt_reserve - 1,
&mut split_stake_keyed_account, &split_stake_keyed_account,
&signers &signers
), ),
Err(InstructionError::InsufficientFunds) Err(InstructionError::InsufficientFunds)
@ -2361,7 +2360,7 @@ mod tests {
assert_eq!( assert_eq!(
stake_keyed_account.split( stake_keyed_account.split(
(stake_lamports - rent_exempt_reserve) + 1, (stake_lamports - rent_exempt_reserve) + 1,
&mut split_stake_keyed_account, &split_stake_keyed_account,
&signers &signers
), ),
Err(InstructionError::InsufficientFunds) Err(InstructionError::InsufficientFunds)
@ -2372,7 +2371,7 @@ mod tests {
assert_eq!( assert_eq!(
stake_keyed_account.split( stake_keyed_account.split(
stake_lamports - rent_exempt_reserve, stake_lamports - rent_exempt_reserve,
&mut split_stake_keyed_account, &split_stake_keyed_account,
&signers &signers
), ),
Ok(()) Ok(())
@ -2418,7 +2417,7 @@ mod tests {
StakeState::Initialized(Meta::auto(&stake_pubkey)), StakeState::Initialized(Meta::auto(&stake_pubkey)),
StakeState::Stake(Meta::auto(&stake_pubkey), Stake::just_stake(stake_lamports)), StakeState::Stake(Meta::auto(&stake_pubkey), Stake::just_stake(stake_lamports)),
] { ] {
let mut split_stake_account = Account::new_ref_data_with_space( let split_stake_account = Account::new_ref_data_with_space(
0, 0,
&StakeState::Uninitialized, &StakeState::Uninitialized,
std::mem::size_of::<StakeState>(), std::mem::size_of::<StakeState>(),
@ -2426,36 +2425,27 @@ mod tests {
) )
.expect("stake_account"); .expect("stake_account");
let mut split_stake_keyed_account = let split_stake_keyed_account =
KeyedAccount::new(&split_stake_pubkey, true, &mut split_stake_account); KeyedAccount::new(&split_stake_pubkey, true, &split_stake_account);
let mut stake_account = Account::new_ref_data_with_space( let stake_account = Account::new_ref_data_with_space(
stake_lamports, stake_lamports,
state, state,
std::mem::size_of::<StakeState>(), std::mem::size_of::<StakeState>(),
&id(), &id(),
) )
.expect("stake_account"); .expect("stake_account");
let mut stake_keyed_account = let stake_keyed_account = KeyedAccount::new(&stake_pubkey, true, &stake_account);
KeyedAccount::new(&stake_pubkey, true, &mut stake_account);
// split more than available fails // split more than available fails
assert_eq!( assert_eq!(
stake_keyed_account.split( stake_keyed_account.split(stake_lamports + 1, &split_stake_keyed_account, &signers),
stake_lamports + 1,
&mut split_stake_keyed_account,
&signers
),
Err(InstructionError::InsufficientFunds) Err(InstructionError::InsufficientFunds)
); );
// should work // should work
assert_eq!( assert_eq!(
stake_keyed_account.split( stake_keyed_account.split(stake_lamports / 2, &split_stake_keyed_account, &signers),
stake_lamports / 2,
&mut split_stake_keyed_account,
&signers
),
Ok(()) Ok(())
); );
// no lamport leakage // no lamport leakage
@ -2529,7 +2519,7 @@ mod tests {
Stake::just_stake(stake_lamports - rent_exempt_reserve), Stake::just_stake(stake_lamports - rent_exempt_reserve),
), ),
] { ] {
let mut split_stake_account = Account::new_ref_data_with_space( let split_stake_account = Account::new_ref_data_with_space(
0, 0,
&StakeState::Uninitialized, &StakeState::Uninitialized,
std::mem::size_of::<StakeState>(), std::mem::size_of::<StakeState>(),
@ -2537,22 +2527,21 @@ mod tests {
) )
.expect("stake_account"); .expect("stake_account");
let mut split_stake_keyed_account = let split_stake_keyed_account =
KeyedAccount::new(&split_stake_pubkey, true, &mut split_stake_account); KeyedAccount::new(&split_stake_pubkey, true, &split_stake_account);
let mut stake_account = Account::new_ref_data_with_space( let stake_account = Account::new_ref_data_with_space(
stake_lamports, stake_lamports,
state, state,
std::mem::size_of::<StakeState>(), std::mem::size_of::<StakeState>(),
&id(), &id(),
) )
.expect("stake_account"); .expect("stake_account");
let mut stake_keyed_account = let stake_keyed_account = KeyedAccount::new(&stake_pubkey, true, &stake_account);
KeyedAccount::new(&stake_pubkey, true, &mut stake_account);
// split 100% over to dest // split 100% over to dest
assert_eq!( assert_eq!(
stake_keyed_account.split(stake_lamports, &mut split_stake_keyed_account, &signers), stake_keyed_account.split(stake_lamports, &split_stake_keyed_account, &signers),
Ok(()) Ok(())
); );
@ -2691,7 +2680,7 @@ mod tests {
fn test_authorize_delegated_stake() { fn test_authorize_delegated_stake() {
let stake_pubkey = Pubkey::new_rand(); let stake_pubkey = Pubkey::new_rand();
let stake_lamports = 42; let stake_lamports = 42;
let mut stake_account = Account::new_ref_data_with_space( let stake_account = Account::new_ref_data_with_space(
stake_lamports, stake_lamports,
&StakeState::Initialized(Meta::auto(&stake_pubkey)), &StakeState::Initialized(Meta::auto(&stake_pubkey)),
std::mem::size_of::<StakeState>(), std::mem::size_of::<StakeState>(),
@ -2702,15 +2691,15 @@ mod tests {
let mut clock = Clock::default(); let mut clock = Clock::default();
let vote_pubkey = Pubkey::new_rand(); let vote_pubkey = Pubkey::new_rand();
let mut vote_account = RefCell::new(vote_state::create_account( let vote_account = RefCell::new(vote_state::create_account(
&vote_pubkey, &vote_pubkey,
&Pubkey::new_rand(), &Pubkey::new_rand(),
0, 0,
100, 100,
)); ));
let vote_keyed_account = KeyedAccount::new(&vote_pubkey, false, &mut vote_account); let vote_keyed_account = KeyedAccount::new(&vote_pubkey, false, &vote_account);
let mut stake_keyed_account = KeyedAccount::new(&stake_pubkey, true, &mut stake_account); let stake_keyed_account = KeyedAccount::new(&stake_pubkey, true, &stake_account);
let signers = vec![stake_pubkey].into_iter().collect(); let signers = vec![stake_pubkey].into_iter().collect();
stake_keyed_account stake_keyed_account
.delegate_stake(&vote_keyed_account, &clock, &Config::default(), &signers) .delegate_stake(&vote_keyed_account, &clock, &Config::default(), &signers)
@ -2734,18 +2723,17 @@ mod tests {
let other_signers = vec![other_pubkey].into_iter().collect(); let other_signers = vec![other_pubkey].into_iter().collect();
// Use unsigned stake_keyed_account to test other signers // Use unsigned stake_keyed_account to test other signers
let mut stake_keyed_account = KeyedAccount::new(&stake_pubkey, false, &mut stake_account); let stake_keyed_account = KeyedAccount::new(&stake_pubkey, false, &stake_account);
let new_voter_pubkey = Pubkey::new_rand(); let new_voter_pubkey = Pubkey::new_rand();
let vote_state = VoteState::default(); let vote_state = VoteState::default();
let mut new_vote_account = RefCell::new(vote_state::create_account( let new_vote_account = RefCell::new(vote_state::create_account(
&new_voter_pubkey, &new_voter_pubkey,
&Pubkey::new_rand(), &Pubkey::new_rand(),
0, 0,
100, 100,
)); ));
let mut new_vote_keyed_account = let new_vote_keyed_account = KeyedAccount::new(&new_voter_pubkey, false, &new_vote_account);
KeyedAccount::new(&new_voter_pubkey, false, &mut new_vote_account);
new_vote_keyed_account.set_state(&vote_state).unwrap(); new_vote_keyed_account.set_state(&vote_state).unwrap();
// time passes, so we can re-delegate // time passes, so we can re-delegate

View File

@ -4,7 +4,7 @@ use num_derive::FromPrimitive;
use serde_derive::{Deserialize, Serialize}; use serde_derive::{Deserialize, Serialize};
use solana_sdk::{ use solana_sdk::{
account::{Account, KeyedAccount}, account::{Account, KeyedAccount},
account_utils::State, account_utils::StateMut,
clock::Epoch, clock::Epoch,
hash::Hash, hash::Hash,
instruction::InstructionError, instruction::InstructionError,
@ -366,7 +366,7 @@ impl<'a> StorageAccount<'a> {
pub fn claim_storage_reward( pub fn claim_storage_reward(
&mut self, &mut self,
rewards_pool: &mut KeyedAccount, rewards_pool: &KeyedAccount,
clock: sysvar::clock::Clock, clock: sysvar::clock::Clock,
rewards: sysvar::rewards::Rewards, rewards: sysvar::rewards::Rewards,
owner: &mut StorageAccount, owner: &mut StorageAccount,
@ -417,7 +417,7 @@ impl<'a> StorageAccount<'a> {
fn check_redeemable( fn check_redeemable(
credits: &mut Credits, credits: &mut Credits,
storage_point_value: f64, storage_point_value: f64,
rewards_pool: &mut KeyedAccount, rewards_pool: &KeyedAccount,
owner: &mut StorageAccount, owner: &mut StorageAccount,
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
let rewards = (credits.redeemable as f64 * storage_point_value) as u64; let rewards = (credits.redeemable as f64 * storage_point_value) as u64;
@ -619,7 +619,7 @@ mod tests {
}; };
let mut rewards_pool = RefCell::new(create_rewards_pool()); let mut rewards_pool = RefCell::new(create_rewards_pool());
let pool_id = rewards_pools::id(); let pool_id = rewards_pools::id();
let mut keyed_pool_account = KeyedAccount::new(&pool_id, false, &mut rewards_pool); let keyed_pool_account = KeyedAccount::new(&pool_id, false, &mut rewards_pool);
let mut owner = StorageAccount { let mut owner = StorageAccount {
id: Pubkey::default(), id: Pubkey::default(),
account: &mut owner_account, account: &mut owner_account,
@ -628,7 +628,7 @@ mod tests {
// check that redeeming from depleted pools fails // check that redeeming from depleted pools fails
keyed_pool_account.account.borrow_mut().lamports = 0; keyed_pool_account.account.borrow_mut().lamports = 0;
assert_eq!( assert_eq!(
check_redeemable(&mut credits, 1.0, &mut keyed_pool_account, &mut owner), check_redeemable(&mut credits, 1.0, &keyed_pool_account, &mut owner),
Err(InstructionError::CustomError( Err(InstructionError::CustomError(
StorageError::RewardPoolDepleted as u32, StorageError::RewardPoolDepleted as u32,
)) ))
@ -637,7 +637,7 @@ mod tests {
keyed_pool_account.account.borrow_mut().lamports = 200; keyed_pool_account.account.borrow_mut().lamports = 200;
assert_eq!( assert_eq!(
check_redeemable(&mut credits, 1.0, &mut keyed_pool_account, &mut owner), check_redeemable(&mut credits, 1.0, &keyed_pool_account, &mut owner),
Ok(()) Ok(())
); );
// check that the owner's balance increases // check that the owner's balance increases

View File

@ -12,12 +12,12 @@ use solana_sdk::{
pub fn process_instruction( pub fn process_instruction(
_program_id: &Pubkey, _program_id: &Pubkey,
keyed_accounts: &mut [KeyedAccount], keyed_accounts: &[KeyedAccount],
data: &[u8], data: &[u8],
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
solana_logger::setup(); solana_logger::setup();
let (me, rest) = keyed_accounts.split_at_mut(1); let (me, rest) = keyed_accounts.split_at(1);
let me_unsigned = me[0].signer_key().is_none(); let me_unsigned = me[0].signer_key().is_none();
let mut me_account = me[0].try_account_ref_mut()?; let mut me_account = me[0].try_account_ref_mut()?;
let mut storage_account = StorageAccount::new(*me[0].unsigned_key(), &mut me_account); let mut storage_account = StorageAccount::new(*me[0].unsigned_key(), &mut me_account);
@ -63,23 +63,23 @@ pub fn process_instruction(
if rest.len() != 4 { if rest.len() != 4 {
return Err(InstructionError::InvalidArgument); return Err(InstructionError::InvalidArgument);
} }
let (clock, rest) = rest.split_at_mut(1); let (clock, rest) = rest.split_at(1);
let (rewards, rest) = rest.split_at_mut(1); let (rewards, rest) = rest.split_at(1);
let (rewards_pools, owner) = rest.split_at_mut(1); let (rewards_pools, owner) = rest.split_at(1);
let rewards = Rewards::from_keyed_account(&rewards[0])?; let rewards = Rewards::from_keyed_account(&rewards[0])?;
let clock = Clock::from_keyed_account(&clock[0])?; let clock = Clock::from_keyed_account(&clock[0])?;
let mut owner_account = owner[0].try_account_ref_mut()?; let mut owner_account = owner[0].try_account_ref_mut()?;
let mut owner = StorageAccount::new(*owner[0].unsigned_key(), &mut owner_account); let mut owner = StorageAccount::new(*owner[0].unsigned_key(), &mut owner_account);
storage_account.claim_storage_reward(&mut rewards_pools[0], clock, rewards, &mut owner) storage_account.claim_storage_reward(&rewards_pools[0], clock, rewards, &mut owner)
} }
StorageInstruction::ProofValidation { segment, proofs } => { StorageInstruction::ProofValidation { segment, proofs } => {
if rest.is_empty() { if rest.is_empty() {
return Err(InstructionError::InvalidArgument); return Err(InstructionError::InvalidArgument);
} }
let (clock, rest) = rest.split_at_mut(1); let (clock, rest) = rest.split_at(1);
if me_unsigned || rest.is_empty() { if me_unsigned || rest.is_empty() {
// This instruction must be signed by `me` and `rest` cannot be empty // This instruction must be signed by `me` and `rest` cannot be empty
return Err(InstructionError::InvalidArgument); return Err(InstructionError::InvalidArgument);
@ -127,13 +127,13 @@ mod tests {
fn test_instruction( fn test_instruction(
ix: &Instruction, ix: &Instruction,
program_accounts: &mut [Account], program_accounts: &[Account],
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
let program_accounts: Vec<_> = program_accounts let program_accounts: Vec<_> = program_accounts
.iter() .iter()
.map(|account| RefCell::new(account.clone())) .map(|account| RefCell::new(account.clone()))
.collect(); .collect();
let mut keyed_accounts: Vec<_> = ix let keyed_accounts: Vec<_> = ix
.accounts .accounts
.iter() .iter()
.zip(program_accounts.iter()) .zip(program_accounts.iter())
@ -142,7 +142,7 @@ mod tests {
}) })
.collect(); .collect();
let ret = process_instruction(&id(), &mut keyed_accounts, &ix.data); let ret = process_instruction(&id(), &keyed_accounts, &ix.data);
info!("ret: {:?}", ret); info!("ret: {:?}", ret);
ret ret
} }
@ -180,15 +180,15 @@ mod tests {
&mut clock_account, &mut clock_account,
); );
assert_eq!(test_instruction(&ix, &mut [account, clock_account]), Ok(())); assert_eq!(test_instruction(&ix, &[account, clock_account]), Ok(()));
} }
#[test] #[test]
fn test_storage_tx() { fn test_storage_tx() {
let pubkey = Pubkey::new_rand(); let pubkey = Pubkey::new_rand();
let mut accounts = [(&pubkey, &RefCell::new(Account::default()))]; let accounts = [(&pubkey, &RefCell::new(Account::default()))];
let mut keyed_accounts = create_keyed_accounts(&mut accounts); let keyed_accounts = create_keyed_accounts(&accounts);
assert!(process_instruction(&id(), &mut keyed_accounts, &[]).is_err()); assert!(process_instruction(&id(), &keyed_accounts, &[]).is_err());
} }
#[test] #[test]
@ -196,15 +196,15 @@ mod tests {
let pubkey = Pubkey::new_rand(); let pubkey = Pubkey::new_rand();
let clock_id = clock::id(); let clock_id = clock::id();
let mut keyed_accounts = Vec::new(); let mut keyed_accounts = Vec::new();
let mut user_account = RefCell::new(Account::default()); let user_account = RefCell::new(Account::default());
let mut clock_account = RefCell::new(Clock::default().create_account(1)); let clock_account = RefCell::new(Clock::default().create_account(1));
keyed_accounts.push(KeyedAccount::new(&pubkey, true, &mut user_account)); keyed_accounts.push(KeyedAccount::new(&pubkey, true, &user_account));
keyed_accounts.push(KeyedAccount::new(&clock_id, false, &mut clock_account)); keyed_accounts.push(KeyedAccount::new(&clock_id, false, &clock_account));
let ix = storage_instruction::advertise_recent_blockhash(&pubkey, Hash::default(), 1); let ix = storage_instruction::advertise_recent_blockhash(&pubkey, Hash::default(), 1);
assert_eq!( assert_eq!(
process_instruction(&id(), &mut keyed_accounts, &ix.data), process_instruction(&id(), &keyed_accounts, &ix.data),
Err(InstructionError::InvalidAccountData) Err(InstructionError::InvalidAccountData)
); );
} }
@ -212,7 +212,7 @@ mod tests {
#[test] #[test]
fn test_invalid_accounts_len() { fn test_invalid_accounts_len() {
let pubkey = Pubkey::new_rand(); let pubkey = Pubkey::new_rand();
let mut accounts = [Account::default()]; let accounts = [Account::default()];
let ix = storage_instruction::mining_proof( let ix = storage_instruction::mining_proof(
&pubkey, &pubkey,
@ -232,11 +232,11 @@ mod tests {
&mut clock_account, &mut clock_account,
); );
assert!(test_instruction(&ix, &mut accounts).is_err()); assert!(test_instruction(&ix, &accounts).is_err());
let mut accounts = [Account::default(), clock_account, Account::default()]; let accounts = [Account::default(), clock_account, Account::default()];
assert!(test_instruction(&ix, &mut accounts).is_err()); assert!(test_instruction(&ix, &accounts).is_err());
} }
#[test] #[test]
@ -256,7 +256,7 @@ mod tests {
); );
// submitting a proof for a slot in the past, so this should fail // submitting a proof for a slot in the past, so this should fail
assert!(test_instruction(&ix, &mut accounts).is_err()); assert!(test_instruction(&ix, &accounts).is_err());
} }
#[test] #[test]
@ -291,6 +291,6 @@ mod tests {
&mut clock_account, &mut clock_account,
); );
assert_matches!(test_instruction(&ix, &mut [account, clock_account]), Ok(_)); assert_matches!(test_instruction(&ix, &[account, clock_account]), Ok(_));
} }
} }

View File

@ -15,7 +15,7 @@ use solana_sdk::{
use std::cell::RefMut; use std::cell::RefMut;
fn verify_date_account( fn verify_date_account(
keyed_account: &mut KeyedAccount, keyed_account: &KeyedAccount,
expected_pubkey: &Pubkey, expected_pubkey: &Pubkey,
) -> Result<Date<Utc>, InstructionError> { ) -> Result<Date<Utc>, InstructionError> {
if keyed_account.owner()? != solana_config_program::id() { if keyed_account.owner()? != solana_config_program::id() {
@ -33,7 +33,7 @@ fn verify_date_account(
} }
fn verify_account<'a>( fn verify_account<'a>(
keyed_account: &'a mut KeyedAccount, keyed_account: &'a KeyedAccount,
expected_pubkey: &Pubkey, expected_pubkey: &Pubkey,
) -> Result<RefMut<'a, Account>, InstructionError> { ) -> Result<RefMut<'a, Account>, InstructionError> {
if keyed_account.unsigned_key() != expected_pubkey { if keyed_account.unsigned_key() != expected_pubkey {
@ -44,7 +44,7 @@ fn verify_account<'a>(
} }
fn verify_signed_account<'a>( fn verify_signed_account<'a>(
keyed_account: &'a mut KeyedAccount, keyed_account: &'a KeyedAccount,
expected_pubkey: &Pubkey, expected_pubkey: &Pubkey,
) -> Result<RefMut<'a, Account>, InstructionError> { ) -> Result<RefMut<'a, Account>, InstructionError> {
if keyed_account.signer_key().is_none() { if keyed_account.signer_key().is_none() {
@ -56,10 +56,10 @@ fn verify_signed_account<'a>(
pub fn process_instruction( pub fn process_instruction(
_program_id: &Pubkey, _program_id: &Pubkey,
keyed_accounts: &mut [KeyedAccount], keyed_accounts: &[KeyedAccount],
data: &[u8], data: &[u8],
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
let keyed_accounts_iter = &mut keyed_accounts.iter_mut(); let keyed_accounts_iter = &mut keyed_accounts.iter();
let contract_account = &mut next_keyed_account(keyed_accounts_iter)?.try_account_ref_mut()?; let contract_account = &mut next_keyed_account(keyed_accounts_iter)?.try_account_ref_mut()?;
let instruction = limited_deserialize(data)?; let instruction = limited_deserialize(data)?;
@ -265,12 +265,12 @@ mod tests {
fn test_verify_account_unauthorized() { fn test_verify_account_unauthorized() {
// Ensure client can't sneak in with an untrusted date account. // Ensure client can't sneak in with an untrusted date account.
let date_pubkey = Pubkey::new_rand(); let date_pubkey = Pubkey::new_rand();
let mut account = Account::new_ref(1, 0, &solana_config_program::id()); let account = Account::new_ref(1, 0, &solana_config_program::id());
let mut keyed_account = KeyedAccount::new(&date_pubkey, false, &mut account); let keyed_account = KeyedAccount::new(&date_pubkey, false, &account);
let mallory_pubkey = Pubkey::new_rand(); // <-- Attack! Not the expected account. let mallory_pubkey = Pubkey::new_rand(); // <-- Attack! Not the expected account.
assert_eq!( assert_eq!(
verify_account(&mut keyed_account, &mallory_pubkey).unwrap_err(), verify_account(&keyed_account, &mallory_pubkey).unwrap_err(),
VestError::Unauthorized.into() VestError::Unauthorized.into()
); );
} }
@ -279,11 +279,11 @@ mod tests {
fn test_verify_signed_account_missing_signature() { fn test_verify_signed_account_missing_signature() {
// Ensure client can't sneak in with an unsigned account. // Ensure client can't sneak in with an unsigned account.
let date_pubkey = Pubkey::new_rand(); let date_pubkey = Pubkey::new_rand();
let mut account = Account::new_ref(1, 0, &solana_config_program::id()); let account = Account::new_ref(1, 0, &solana_config_program::id());
let mut keyed_account = KeyedAccount::new(&date_pubkey, false, &mut account); // <-- Attack! Unsigned transaction. let keyed_account = KeyedAccount::new(&date_pubkey, false, &account); // <-- Attack! Unsigned transaction.
assert_eq!( assert_eq!(
verify_signed_account(&mut keyed_account, &date_pubkey).unwrap_err(), verify_signed_account(&keyed_account, &date_pubkey).unwrap_err(),
InstructionError::MissingRequiredSignature.into() InstructionError::MissingRequiredSignature.into()
); );
} }
@ -292,10 +292,10 @@ mod tests {
fn test_verify_date_account_incorrect_program_id() { fn test_verify_date_account_incorrect_program_id() {
// Ensure client can't sneak in with a non-Config account. // Ensure client can't sneak in with a non-Config account.
let date_pubkey = Pubkey::new_rand(); let date_pubkey = Pubkey::new_rand();
let mut account = Account::new_ref(1, 0, &id()); // <-- Attack! Pass Vest account where Config account is expected. let account = Account::new_ref(1, 0, &id()); // <-- Attack! Pass Vest account where Config account is expected.
let mut keyed_account = KeyedAccount::new(&date_pubkey, false, &mut account); let keyed_account = KeyedAccount::new(&date_pubkey, false, &account);
assert_eq!( assert_eq!(
verify_date_account(&mut keyed_account, &date_pubkey).unwrap_err(), verify_date_account(&keyed_account, &date_pubkey).unwrap_err(),
InstructionError::IncorrectProgramId InstructionError::IncorrectProgramId
); );
} }
@ -304,10 +304,10 @@ mod tests {
fn test_verify_date_account_uninitialized_config() { fn test_verify_date_account_uninitialized_config() {
// Ensure no panic when `get_config_data()` returns an error. // Ensure no panic when `get_config_data()` returns an error.
let date_pubkey = Pubkey::new_rand(); let date_pubkey = Pubkey::new_rand();
let mut account = Account::new_ref(1, 0, &solana_config_program::id()); // <-- Attack! Zero space. let account = Account::new_ref(1, 0, &solana_config_program::id()); // <-- Attack! Zero space.
let mut keyed_account = KeyedAccount::new(&date_pubkey, false, &mut account); let keyed_account = KeyedAccount::new(&date_pubkey, false, &account);
assert_eq!( assert_eq!(
verify_date_account(&mut keyed_account, &date_pubkey).unwrap_err(), verify_date_account(&keyed_account, &date_pubkey).unwrap_err(),
InstructionError::InvalidAccountData InstructionError::InvalidAccountData
); );
} }
@ -316,10 +316,10 @@ mod tests {
fn test_verify_date_account_invalid_date_config() { fn test_verify_date_account_invalid_date_config() {
// Ensure no panic when `deserialize::<DateConfig>()` returns an error. // Ensure no panic when `deserialize::<DateConfig>()` returns an error.
let date_pubkey = Pubkey::new_rand(); let date_pubkey = Pubkey::new_rand();
let mut account = Account::new_ref(1, 1, &solana_config_program::id()); // Attack! 1 byte, enough to sneak by `get_config_data()`, but not DateConfig deserialize. let account = Account::new_ref(1, 1, &solana_config_program::id()); // Attack! 1 byte, enough to sneak by `get_config_data()`, but not DateConfig deserialize.
let mut keyed_account = KeyedAccount::new(&date_pubkey, false, &mut account); let keyed_account = KeyedAccount::new(&date_pubkey, false, &account);
assert_eq!( assert_eq!(
verify_date_account(&mut keyed_account, &date_pubkey).unwrap_err(), verify_date_account(&keyed_account, &date_pubkey).unwrap_err(),
InstructionError::InvalidAccountData InstructionError::InvalidAccountData
); );
} }
@ -328,10 +328,10 @@ mod tests {
fn test_verify_date_account_deserialize() { fn test_verify_date_account_deserialize() {
// Ensure no panic when `deserialize::<DateConfig>()` returns an error. // Ensure no panic when `deserialize::<DateConfig>()` returns an error.
let date_pubkey = Pubkey::new_rand(); let date_pubkey = Pubkey::new_rand();
let mut account = Account::new_ref(1, 1, &solana_config_program::id()); // Attack! 1 byte, enough to sneak by `get_config_data()`, but not DateConfig deserialize. let account = Account::new_ref(1, 1, &solana_config_program::id()); // Attack! 1 byte, enough to sneak by `get_config_data()`, but not DateConfig deserialize.
let mut keyed_account = KeyedAccount::new(&date_pubkey, false, &mut account); let keyed_account = KeyedAccount::new(&date_pubkey, false, &account);
assert_eq!( assert_eq!(
verify_date_account(&mut keyed_account, &date_pubkey).unwrap_err(), verify_date_account(&keyed_account, &date_pubkey).unwrap_err(),
InstructionError::InvalidAccountData InstructionError::InvalidAccountData
); );
} }

View File

@ -176,7 +176,7 @@ pub fn withdraw(
pub fn process_instruction( pub fn process_instruction(
_program_id: &Pubkey, _program_id: &Pubkey,
keyed_accounts: &mut [KeyedAccount], keyed_accounts: &[KeyedAccount],
data: &[u8], data: &[u8],
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
solana_logger::setup_with_default("solana=info"); solana_logger::setup_with_default("solana=info");
@ -186,7 +186,7 @@ pub fn process_instruction(
let signers = get_signers(keyed_accounts); let signers = get_signers(keyed_accounts);
let keyed_accounts = &mut keyed_accounts.iter_mut(); let keyed_accounts = &mut keyed_accounts.iter();
let me = &mut next_keyed_account(keyed_accounts)?; let me = &mut next_keyed_account(keyed_accounts)?;
match limited_deserialize(data)? { match limited_deserialize(data)? {
@ -235,7 +235,7 @@ mod tests {
#[test] #[test]
fn test_vote_process_instruction_decode_bail() { fn test_vote_process_instruction_decode_bail() {
assert_eq!( assert_eq!(
super::process_instruction(&Pubkey::default(), &mut [], &[],), super::process_instruction(&Pubkey::default(), &[], &[],),
Err(InstructionError::NotEnoughAccountKeys), Err(InstructionError::NotEnoughAccountKeys),
); );
} }
@ -261,13 +261,13 @@ mod tests {
accounts.push(RefCell::new(Account::default())); accounts.push(RefCell::new(Account::default()));
} }
{ {
let mut keyed_accounts: Vec<_> = instruction let keyed_accounts: Vec<_> = instruction
.accounts .accounts
.iter() .iter()
.zip(accounts.iter_mut()) .zip(accounts.iter())
.map(|(meta, account)| KeyedAccount::new(&meta.pubkey, meta.is_signer, account)) .map(|(meta, account)| KeyedAccount::new(&meta.pubkey, meta.is_signer, account))
.collect(); .collect();
super::process_instruction(&Pubkey::default(), &mut keyed_accounts, &instruction.data) super::process_instruction(&Pubkey::default(), &keyed_accounts, &instruction.data)
} }
} }

View File

@ -428,7 +428,7 @@ impl VoteState {
/// but will implicitly withdraw authorization from the previously authorized /// but will implicitly withdraw authorization from the previously authorized
/// key /// key
pub fn authorize( pub fn authorize(
vote_account: &mut KeyedAccount, vote_account: &KeyedAccount,
authorized: &Pubkey, authorized: &Pubkey,
vote_authorize: VoteAuthorize, vote_authorize: VoteAuthorize,
signers: &HashSet<Pubkey>, signers: &HashSet<Pubkey>,
@ -465,7 +465,7 @@ pub fn authorize(
/// Update the node_pubkey, requires signature of the authorized voter /// Update the node_pubkey, requires signature of the authorized voter
pub fn update_node( pub fn update_node(
vote_account: &mut KeyedAccount, vote_account: &KeyedAccount,
node_pubkey: &Pubkey, node_pubkey: &Pubkey,
signers: &HashSet<Pubkey>, signers: &HashSet<Pubkey>,
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
@ -492,9 +492,9 @@ fn verify_authorized_signer(
/// Withdraw funds from the vote account /// Withdraw funds from the vote account
pub fn withdraw( pub fn withdraw(
vote_account: &mut KeyedAccount, vote_account: &KeyedAccount,
lamports: u64, lamports: u64,
to_account: &mut KeyedAccount, to_account: &KeyedAccount,
signers: &HashSet<Pubkey>, signers: &HashSet<Pubkey>,
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
let vote_state: VoteState = vote_account.state()?; let vote_state: VoteState = vote_account.state()?;
@ -513,7 +513,7 @@ pub fn withdraw(
/// Assumes that the account is being init as part of a account creation or balance transfer and /// Assumes that the account is being init as part of a account creation or balance transfer and
/// that the transaction must be signed by the staker's keys /// that the transaction must be signed by the staker's keys
pub fn initialize_account( pub fn initialize_account(
vote_account: &mut KeyedAccount, vote_account: &KeyedAccount,
vote_init: &VoteInit, vote_init: &VoteInit,
clock: &Clock, clock: &Clock,
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
@ -526,7 +526,7 @@ pub fn initialize_account(
} }
pub fn process_vote( pub fn process_vote(
vote_account: &mut KeyedAccount, vote_account: &KeyedAccount,
slot_hashes: &[SlotHash], slot_hashes: &[SlotHash],
clock: &Clock, clock: &Clock,
vote: &Vote, vote: &Vote,
@ -581,7 +581,7 @@ mod tests {
use crate::vote_state; use crate::vote_state;
use solana_sdk::{ use solana_sdk::{
account::{get_signers, Account}, account::{get_signers, Account},
account_utils::State, account_utils::StateMut,
hash::hash, hash::hash,
instruction_processor_utils::next_keyed_account, instruction_processor_utils::next_keyed_account,
}; };
@ -606,14 +606,14 @@ mod tests {
#[test] #[test]
fn test_initialize_vote_account() { fn test_initialize_vote_account() {
let vote_account_pubkey = Pubkey::new_rand(); let vote_account_pubkey = Pubkey::new_rand();
let mut vote_account = Account::new_ref(100, VoteState::size_of(), &id()); let vote_account = Account::new_ref(100, VoteState::size_of(), &id());
let node_pubkey = Pubkey::new_rand(); let node_pubkey = Pubkey::new_rand();
//init should pass //init should pass
let mut vote_account = KeyedAccount::new(&vote_account_pubkey, false, &mut vote_account); let vote_account = KeyedAccount::new(&vote_account_pubkey, false, &vote_account);
let res = initialize_account( let res = initialize_account(
&mut vote_account, &vote_account,
&VoteInit { &VoteInit {
node_pubkey, node_pubkey,
authorized_voter: vote_account_pubkey, authorized_voter: vote_account_pubkey,
@ -626,7 +626,7 @@ mod tests {
// reinit should fail // reinit should fail
let res = initialize_account( let res = initialize_account(
&mut vote_account, &vote_account,
&VoteInit { &VoteInit {
node_pubkey, node_pubkey,
authorized_voter: vote_account_pubkey, authorized_voter: vote_account_pubkey,
@ -653,15 +653,15 @@ mod tests {
fn simulate_process_vote( fn simulate_process_vote(
vote_pubkey: &Pubkey, vote_pubkey: &Pubkey,
vote_account: &mut RefCell<Account>, vote_account: &RefCell<Account>,
vote: &Vote, vote: &Vote,
slot_hashes: &[SlotHash], slot_hashes: &[SlotHash],
epoch: Epoch, epoch: Epoch,
) -> Result<VoteState, InstructionError> { ) -> Result<VoteState, InstructionError> {
let keyed_accounts = &mut [KeyedAccount::new(&vote_pubkey, true, vote_account)]; let keyed_accounts = &[KeyedAccount::new(&vote_pubkey, true, vote_account)];
let signers = get_signers(keyed_accounts); let signers = get_signers(keyed_accounts);
process_vote( process_vote(
&mut keyed_accounts[0], &keyed_accounts[0],
slot_hashes, slot_hashes,
&Clock { &Clock {
epoch, epoch,
@ -676,7 +676,7 @@ mod tests {
/// exercises all the keyed accounts stuff /// exercises all the keyed accounts stuff
fn simulate_process_vote_unchecked( fn simulate_process_vote_unchecked(
vote_pubkey: &Pubkey, vote_pubkey: &Pubkey,
vote_account: &mut RefCell<Account>, vote_account: &RefCell<Account>,
vote: &Vote, vote: &Vote,
) -> Result<VoteState, InstructionError> { ) -> Result<VoteState, InstructionError> {
simulate_process_vote( simulate_process_vote(
@ -711,11 +711,11 @@ mod tests {
#[test] #[test]
fn test_vote() { fn test_vote() {
let (vote_pubkey, mut vote_account) = create_test_account(); let (vote_pubkey, vote_account) = create_test_account();
let vote = Vote::new(vec![1], Hash::default()); let vote = Vote::new(vec![1], Hash::default());
let vote_state = let vote_state =
simulate_process_vote_unchecked(&vote_pubkey, &mut vote_account, &vote).unwrap(); simulate_process_vote_unchecked(&vote_pubkey, &vote_account, &vote).unwrap();
assert_eq!( assert_eq!(
vote_state.votes, vote_state.votes,
vec![Lockout::new(*vote.slots.last().unwrap())] vec![Lockout::new(*vote.slots.last().unwrap())]
@ -725,7 +725,7 @@ mod tests {
#[test] #[test]
fn test_vote_slot_hashes() { fn test_vote_slot_hashes() {
let (vote_pubkey, mut vote_account) = create_test_account(); let (vote_pubkey, vote_account) = create_test_account();
let hash = hash(&[0u8]); let hash = hash(&[0u8]);
let vote = Vote::new(vec![0], hash); let vote = Vote::new(vec![0], hash);
@ -734,7 +734,7 @@ mod tests {
assert_eq!( assert_eq!(
simulate_process_vote( simulate_process_vote(
&vote_pubkey, &vote_pubkey,
&mut vote_account, &vote_account,
&vote, &vote,
&[(0, Hash::default())], &[(0, Hash::default())],
0, 0,
@ -744,33 +744,33 @@ mod tests {
// wrong slot // wrong slot
assert_eq!( assert_eq!(
simulate_process_vote(&vote_pubkey, &mut vote_account, &vote, &[(1, hash)], 0), simulate_process_vote(&vote_pubkey, &vote_account, &vote, &[(1, hash)], 0),
Err(VoteError::SlotsMismatch.into()) Err(VoteError::SlotsMismatch.into())
); );
// empty slot_hashes // empty slot_hashes
assert_eq!( assert_eq!(
simulate_process_vote(&vote_pubkey, &mut vote_account, &vote, &[], 0), simulate_process_vote(&vote_pubkey, &vote_account, &vote, &[], 0),
Err(VoteError::VoteTooOld.into()) Err(VoteError::VoteTooOld.into())
); );
} }
#[test] #[test]
fn test_vote_update_node_id() { fn test_vote_update_node_id() {
let (vote_pubkey, mut vote_account) = create_test_account(); let (vote_pubkey, vote_account) = create_test_account();
let node_pubkey = Pubkey::new_rand(); let node_pubkey = Pubkey::new_rand();
let keyed_accounts = &mut [KeyedAccount::new(&vote_pubkey, false, &mut vote_account)]; let keyed_accounts = &[KeyedAccount::new(&vote_pubkey, false, &vote_account)];
let signers = get_signers(keyed_accounts); let signers = get_signers(keyed_accounts);
let res = update_node(&mut keyed_accounts[0], &node_pubkey, &signers); let res = update_node(&keyed_accounts[0], &node_pubkey, &signers);
assert_eq!(res, Err(InstructionError::MissingRequiredSignature)); assert_eq!(res, Err(InstructionError::MissingRequiredSignature));
let vote_state: VoteState = vote_account.borrow().state().unwrap(); let vote_state: VoteState = vote_account.borrow().state().unwrap();
assert!(vote_state.node_pubkey != node_pubkey); assert!(vote_state.node_pubkey != node_pubkey);
let keyed_accounts = &mut [KeyedAccount::new(&vote_pubkey, true, &mut vote_account)]; let keyed_accounts = &[KeyedAccount::new(&vote_pubkey, true, &vote_account)];
let signers = get_signers(keyed_accounts); let signers = get_signers(keyed_accounts);
let res = update_node(&mut keyed_accounts[0], &node_pubkey, &signers); let res = update_node(&keyed_accounts[0], &node_pubkey, &signers);
assert_eq!(res, Ok(())); assert_eq!(res, Ok(()));
let vote_state: VoteState = vote_account.borrow().state().unwrap(); let vote_state: VoteState = vote_account.borrow().state().unwrap();
assert_eq!(vote_state.node_pubkey, node_pubkey); assert_eq!(vote_state.node_pubkey, node_pubkey);
@ -778,14 +778,14 @@ mod tests {
#[test] #[test]
fn test_vote_signature() { fn test_vote_signature() {
let (vote_pubkey, mut vote_account) = create_test_account(); let (vote_pubkey, vote_account) = create_test_account();
let vote = Vote::new(vec![1], Hash::default()); let vote = Vote::new(vec![1], Hash::default());
// unsigned // unsigned
let keyed_accounts = &mut [KeyedAccount::new(&vote_pubkey, false, &mut vote_account)]; let keyed_accounts = &[KeyedAccount::new(&vote_pubkey, false, &vote_account)];
let signers = get_signers(keyed_accounts); let signers = get_signers(keyed_accounts);
let res = process_vote( let res = process_vote(
&mut keyed_accounts[0], &keyed_accounts[0],
&[(*vote.slots.last().unwrap(), vote.hash)], &[(*vote.slots.last().unwrap(), vote.hash)],
&Clock::default(), &Clock::default(),
&vote, &vote,
@ -794,10 +794,10 @@ mod tests {
assert_eq!(res, Err(InstructionError::MissingRequiredSignature)); assert_eq!(res, Err(InstructionError::MissingRequiredSignature));
// signed // signed
let keyed_accounts = &mut [KeyedAccount::new(&vote_pubkey, true, &mut vote_account)]; let keyed_accounts = &[KeyedAccount::new(&vote_pubkey, true, &vote_account)];
let signers = get_signers(keyed_accounts); let signers = get_signers(keyed_accounts);
let res = process_vote( let res = process_vote(
&mut keyed_accounts[0], &keyed_accounts[0],
&[(*vote.slots.last().unwrap(), vote.hash)], &[(*vote.slots.last().unwrap(), vote.hash)],
&Clock::default(), &Clock::default(),
&vote, &vote,
@ -806,11 +806,11 @@ mod tests {
assert_eq!(res, Ok(())); assert_eq!(res, Ok(()));
// another voter, unsigned // another voter, unsigned
let keyed_accounts = &mut [KeyedAccount::new(&vote_pubkey, false, &mut vote_account)]; let keyed_accounts = &[KeyedAccount::new(&vote_pubkey, false, &vote_account)];
let signers = get_signers(keyed_accounts); let signers = get_signers(keyed_accounts);
let authorized_voter_pubkey = Pubkey::new_rand(); let authorized_voter_pubkey = Pubkey::new_rand();
let res = authorize( let res = authorize(
&mut keyed_accounts[0], &keyed_accounts[0],
&authorized_voter_pubkey, &authorized_voter_pubkey,
VoteAuthorize::Voter, VoteAuthorize::Voter,
&signers, &signers,
@ -821,10 +821,10 @@ mod tests {
); );
assert_eq!(res, Err(InstructionError::MissingRequiredSignature)); assert_eq!(res, Err(InstructionError::MissingRequiredSignature));
let keyed_accounts = &mut [KeyedAccount::new(&vote_pubkey, true, &mut vote_account)]; let keyed_accounts = &[KeyedAccount::new(&vote_pubkey, true, &vote_account)];
let signers = get_signers(keyed_accounts); let signers = get_signers(keyed_accounts);
let res = authorize( let res = authorize(
&mut keyed_accounts[0], &keyed_accounts[0],
&authorized_voter_pubkey, &authorized_voter_pubkey,
VoteAuthorize::Voter, VoteAuthorize::Voter,
&signers, &signers,
@ -833,7 +833,7 @@ mod tests {
assert_eq!(res, Err(VoteError::TooSoonToReauthorize.into())); assert_eq!(res, Err(VoteError::TooSoonToReauthorize.into()));
let res = authorize( let res = authorize(
&mut keyed_accounts[0], &keyed_accounts[0],
&authorized_voter_pubkey, &authorized_voter_pubkey,
VoteAuthorize::Voter, VoteAuthorize::Voter,
&signers, &signers,
@ -845,18 +845,14 @@ mod tests {
assert_eq!(res, Ok(())); assert_eq!(res, Ok(()));
// verify authorized_voter_pubkey can authorize authorized_voter_pubkey ;) // verify authorized_voter_pubkey can authorize authorized_voter_pubkey ;)
let mut authorized_voter_account = RefCell::new(Account::default()); let authorized_voter_account = RefCell::new(Account::default());
let keyed_accounts = &mut [ let keyed_accounts = &[
KeyedAccount::new(&vote_pubkey, false, &mut vote_account), KeyedAccount::new(&vote_pubkey, false, &vote_account),
KeyedAccount::new( KeyedAccount::new(&authorized_voter_pubkey, true, &authorized_voter_account),
&authorized_voter_pubkey,
true,
&mut authorized_voter_account,
),
]; ];
let signers = get_signers(keyed_accounts); let signers = get_signers(keyed_accounts);
let res = authorize( let res = authorize(
&mut keyed_accounts[0], &keyed_accounts[0],
&authorized_voter_pubkey, &authorized_voter_pubkey,
VoteAuthorize::Voter, VoteAuthorize::Voter,
&signers, &signers,
@ -866,11 +862,11 @@ mod tests {
// authorize another withdrawer // authorize another withdrawer
// another voter // another voter
let keyed_accounts = &mut [KeyedAccount::new(&vote_pubkey, true, &mut vote_account)]; let keyed_accounts = &[KeyedAccount::new(&vote_pubkey, true, &vote_account)];
let signers = get_signers(keyed_accounts); let signers = get_signers(keyed_accounts);
let authorized_withdrawer_pubkey = Pubkey::new_rand(); let authorized_withdrawer_pubkey = Pubkey::new_rand();
let res = authorize( let res = authorize(
&mut keyed_accounts[0], &keyed_accounts[0],
&authorized_withdrawer_pubkey, &authorized_withdrawer_pubkey,
VoteAuthorize::Withdrawer, VoteAuthorize::Withdrawer,
&signers, &signers,
@ -879,14 +875,14 @@ mod tests {
assert_eq!(res, Ok(())); assert_eq!(res, Ok(()));
// verify authorized_withdrawer can authorize authorized_withdrawer ;) // verify authorized_withdrawer can authorize authorized_withdrawer ;)
let mut withdrawer_account = RefCell::new(Account::default()); let withdrawer_account = RefCell::new(Account::default());
let keyed_accounts = &mut [ let keyed_accounts = &[
KeyedAccount::new(&vote_pubkey, false, &mut vote_account), KeyedAccount::new(&vote_pubkey, false, &vote_account),
KeyedAccount::new(&authorized_withdrawer_pubkey, true, &mut withdrawer_account), KeyedAccount::new(&authorized_withdrawer_pubkey, true, &withdrawer_account),
]; ];
let signers = get_signers(keyed_accounts); let signers = get_signers(keyed_accounts);
let res = authorize( let res = authorize(
&mut keyed_accounts[0], &keyed_accounts[0],
&authorized_withdrawer_pubkey, &authorized_withdrawer_pubkey,
VoteAuthorize::Withdrawer, VoteAuthorize::Withdrawer,
&signers, &signers,
@ -895,11 +891,11 @@ mod tests {
assert_eq!(res, Ok(())); assert_eq!(res, Ok(()));
// not signed by authorized voter // not signed by authorized voter
let keyed_accounts = &mut [KeyedAccount::new(&vote_pubkey, true, &mut vote_account)]; let keyed_accounts = &[KeyedAccount::new(&vote_pubkey, true, &vote_account)];
let signers = get_signers(keyed_accounts); let signers = get_signers(keyed_accounts);
let vote = Vote::new(vec![2], Hash::default()); let vote = Vote::new(vec![2], Hash::default());
let res = process_vote( let res = process_vote(
&mut keyed_accounts[0], &keyed_accounts[0],
&[(*vote.slots.last().unwrap(), vote.hash)], &[(*vote.slots.last().unwrap(), vote.hash)],
&Clock::default(), &Clock::default(),
&vote, &vote,
@ -908,19 +904,15 @@ mod tests {
assert_eq!(res, Err(InstructionError::MissingRequiredSignature)); assert_eq!(res, Err(InstructionError::MissingRequiredSignature));
// signed by authorized voter // signed by authorized voter
let mut authorized_voter_account = RefCell::new(Account::default()); let authorized_voter_account = RefCell::new(Account::default());
let keyed_accounts = &mut [ let keyed_accounts = &[
KeyedAccount::new(&vote_pubkey, false, &mut vote_account), KeyedAccount::new(&vote_pubkey, false, &vote_account),
KeyedAccount::new( KeyedAccount::new(&authorized_voter_pubkey, true, &authorized_voter_account),
&authorized_voter_pubkey,
true,
&mut authorized_voter_account,
),
]; ];
let signers = get_signers(keyed_accounts); let signers = get_signers(keyed_accounts);
let vote = Vote::new(vec![2], Hash::default()); let vote = Vote::new(vec![2], Hash::default());
let res = process_vote( let res = process_vote(
&mut keyed_accounts[0], &keyed_accounts[0],
&[(*vote.slots.last().unwrap(), vote.hash)], &[(*vote.slots.last().unwrap(), vote.hash)],
&Clock::default(), &Clock::default(),
&vote, &vote,
@ -932,11 +924,11 @@ mod tests {
#[test] #[test]
fn test_vote_without_initialization() { fn test_vote_without_initialization() {
let vote_pubkey = Pubkey::new_rand(); let vote_pubkey = Pubkey::new_rand();
let mut vote_account = RefCell::new(Account::new(100, VoteState::size_of(), &id())); let vote_account = RefCell::new(Account::new(100, VoteState::size_of(), &id()));
let res = simulate_process_vote_unchecked( let res = simulate_process_vote_unchecked(
&vote_pubkey, &vote_pubkey,
&mut vote_account, &vote_account,
&Vote::new(vec![1], Hash::default()), &Vote::new(vec![1], Hash::default()),
); );
assert_eq!(res, Err(InstructionError::UninitializedAccount)); assert_eq!(res, Err(InstructionError::UninitializedAccount));
@ -1252,47 +1244,47 @@ mod tests {
#[test] #[test]
fn test_vote_state_withdraw() { fn test_vote_state_withdraw() {
let (vote_pubkey, mut vote_account) = create_test_account(); let (vote_pubkey, vote_account) = create_test_account();
// unsigned request // unsigned request
let keyed_accounts = &mut [KeyedAccount::new(&vote_pubkey, false, &mut vote_account)]; let keyed_accounts = &[KeyedAccount::new(&vote_pubkey, false, &vote_account)];
let signers = get_signers(keyed_accounts); let signers = get_signers(keyed_accounts);
let res = withdraw( let res = withdraw(
&mut keyed_accounts[0], &keyed_accounts[0],
0, 0,
&mut KeyedAccount::new( &KeyedAccount::new(
&Pubkey::new_rand(), &Pubkey::new_rand(),
false, false,
&mut RefCell::new(Account::default()), &RefCell::new(Account::default()),
), ),
&signers, &signers,
); );
assert_eq!(res, Err(InstructionError::MissingRequiredSignature)); assert_eq!(res, Err(InstructionError::MissingRequiredSignature));
// insufficient funds // insufficient funds
let keyed_accounts = &mut [KeyedAccount::new(&vote_pubkey, true, &mut vote_account)]; let keyed_accounts = &[KeyedAccount::new(&vote_pubkey, true, &vote_account)];
let signers = get_signers(keyed_accounts); let signers = get_signers(keyed_accounts);
let res = withdraw( let res = withdraw(
&mut keyed_accounts[0], &keyed_accounts[0],
101, 101,
&mut KeyedAccount::new( &KeyedAccount::new(
&Pubkey::new_rand(), &Pubkey::new_rand(),
false, false,
&mut RefCell::new(Account::default()), &RefCell::new(Account::default()),
), ),
&signers, &signers,
); );
assert_eq!(res, Err(InstructionError::InsufficientFunds)); assert_eq!(res, Err(InstructionError::InsufficientFunds));
// all good // all good
let mut to_account = RefCell::new(Account::default()); let to_account = RefCell::new(Account::default());
let lamports = vote_account.borrow().lamports; let lamports = vote_account.borrow().lamports;
let keyed_accounts = &mut [KeyedAccount::new(&vote_pubkey, true, &mut vote_account)]; let keyed_accounts = &[KeyedAccount::new(&vote_pubkey, true, &vote_account)];
let signers = get_signers(keyed_accounts); let signers = get_signers(keyed_accounts);
let res = withdraw( let res = withdraw(
&mut keyed_accounts[0], &keyed_accounts[0],
lamports, lamports,
&mut KeyedAccount::new(&Pubkey::new_rand(), false, &mut to_account), &KeyedAccount::new(&Pubkey::new_rand(), false, &to_account),
&signers, &signers,
); );
assert_eq!(res, Ok(())); assert_eq!(res, Ok(()));
@ -1304,10 +1296,10 @@ mod tests {
// authorize authorized_withdrawer // authorize authorized_withdrawer
let authorized_withdrawer_pubkey = Pubkey::new_rand(); let authorized_withdrawer_pubkey = Pubkey::new_rand();
let keyed_accounts = &mut [KeyedAccount::new(&vote_pubkey, true, &mut vote_account)]; let keyed_accounts = &[KeyedAccount::new(&vote_pubkey, true, &vote_account)];
let signers = get_signers(keyed_accounts); let signers = get_signers(keyed_accounts);
let res = authorize( let res = authorize(
&mut keyed_accounts[0], &keyed_accounts[0],
&authorized_withdrawer_pubkey, &authorized_withdrawer_pubkey,
VoteAuthorize::Withdrawer, VoteAuthorize::Withdrawer,
&signers, &signers,
@ -1316,13 +1308,13 @@ mod tests {
assert_eq!(res, Ok(())); assert_eq!(res, Ok(()));
// withdraw using authorized_withdrawer to authorized_withdrawer's account // withdraw using authorized_withdrawer to authorized_withdrawer's account
let mut withdrawer_account = RefCell::new(Account::default()); let withdrawer_account = RefCell::new(Account::default());
let keyed_accounts = &mut [ let keyed_accounts = &[
KeyedAccount::new(&vote_pubkey, false, &mut vote_account), KeyedAccount::new(&vote_pubkey, false, &vote_account),
KeyedAccount::new(&authorized_withdrawer_pubkey, true, &mut withdrawer_account), KeyedAccount::new(&authorized_withdrawer_pubkey, true, &withdrawer_account),
]; ];
let signers = get_signers(keyed_accounts); let signers = get_signers(keyed_accounts);
let keyed_accounts = &mut keyed_accounts.iter_mut(); let keyed_accounts = &mut keyed_accounts.iter();
let vote_keyed_account = next_keyed_account(keyed_accounts).unwrap(); let vote_keyed_account = next_keyed_account(keyed_accounts).unwrap();
let withdrawer_keyed_account = next_keyed_account(keyed_accounts).unwrap(); let withdrawer_keyed_account = next_keyed_account(keyed_accounts).unwrap();
let res = withdraw( let res = withdraw(

View File

@ -32,7 +32,7 @@ const NOOP_PROGRAM_ID: [u8; 32] = [
fn process_instruction( fn process_instruction(
_program_id: &Pubkey, _program_id: &Pubkey,
_keyed_accounts: &mut [KeyedAccount], _keyed_accounts: &[KeyedAccount],
_data: &[u8], _data: &[u8],
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
Ok(()) Ok(())

View File

@ -1307,13 +1307,13 @@ impl Bank {
(Ok((accounts, loaders, _rents)), hash_age_kind) => { (Ok((accounts, loaders, _rents)), hash_age_kind) => {
signature_count += u64::from(tx.message().header.num_required_signatures); signature_count += u64::from(tx.message().header.num_required_signatures);
let (mut account_refcells, mut loader_refcells) = let (account_refcells, loader_refcells) =
Self::into_refcells(accounts, loaders); Self::into_refcells(accounts, loaders);
let process_result = self.message_processor.process_message( let process_result = self.message_processor.process_message(
tx.message(), tx.message(),
&mut loader_refcells, &loader_refcells,
&mut account_refcells, &account_refcells,
); );
Self::from_refcells(accounts, loaders, account_refcells, loader_refcells); Self::from_refcells(accounts, loaders, account_refcells, loader_refcells);
@ -2174,7 +2174,7 @@ mod tests {
use solana_sdk::system_program::solana_system_program; use solana_sdk::system_program::solana_system_program;
use solana_sdk::{ use solana_sdk::{
account::KeyedAccount, account::KeyedAccount,
account_utils::State, account_utils::StateMut,
clock::DEFAULT_TICKS_PER_SLOT, clock::DEFAULT_TICKS_PER_SLOT,
epoch_schedule::MINIMUM_SLOTS_PER_EPOCH, epoch_schedule::MINIMUM_SLOTS_PER_EPOCH,
genesis_config::create_genesis_config, genesis_config::create_genesis_config,
@ -2487,7 +2487,7 @@ mod tests {
fn mock_process_instruction( fn mock_process_instruction(
_program_id: &Pubkey, _program_id: &Pubkey,
keyed_accounts: &mut [KeyedAccount], keyed_accounts: &[KeyedAccount],
data: &[u8], data: &[u8],
) -> result::Result<(), InstructionError> { ) -> result::Result<(), InstructionError> {
if let Ok(instruction) = bincode::deserialize(data) { if let Ok(instruction) = bincode::deserialize(data) {
@ -4734,7 +4734,7 @@ mod tests {
fn mock_vote_processor( fn mock_vote_processor(
_pubkey: &Pubkey, _pubkey: &Pubkey,
_ka: &mut [KeyedAccount], _ka: &[KeyedAccount],
_data: &[u8], _data: &[u8],
) -> std::result::Result<(), InstructionError> { ) -> std::result::Result<(), InstructionError> {
Err(InstructionError::CustomError(42)) Err(InstructionError::CustomError(42))
@ -4779,7 +4779,7 @@ mod tests {
fn mock_vote_processor( fn mock_vote_processor(
_pubkey: &Pubkey, _pubkey: &Pubkey,
_ka: &mut [KeyedAccount], _ka: &[KeyedAccount],
_data: &[u8], _data: &[u8],
) -> std::result::Result<(), InstructionError> { ) -> std::result::Result<(), InstructionError> {
Err(InstructionError::CustomError(42)) Err(InstructionError::CustomError(42))
@ -4821,7 +4821,7 @@ mod tests {
fn mock_ix_processor( fn mock_ix_processor(
_pubkey: &Pubkey, _pubkey: &Pubkey,
_ka: &mut [KeyedAccount], _ka: &[KeyedAccount],
_data: &[u8], _data: &[u8],
) -> std::result::Result<(), InstructionError> { ) -> std::result::Result<(), InstructionError> {
Err(InstructionError::CustomError(42)) Err(InstructionError::CustomError(42))
@ -5362,7 +5362,7 @@ mod tests {
fn mock_process_instruction( fn mock_process_instruction(
_program_id: &Pubkey, _program_id: &Pubkey,
keyed_accounts: &mut [KeyedAccount], keyed_accounts: &[KeyedAccount],
data: &[u8], data: &[u8],
) -> result::Result<(), InstructionError> { ) -> result::Result<(), InstructionError> {
let lamports = data[0] as u64; let lamports = data[0] as u64;

View File

@ -124,8 +124,7 @@ pub fn verify_account_changes(
Ok(()) Ok(())
} }
pub type ProcessInstruction = pub type ProcessInstruction = fn(&Pubkey, &[KeyedAccount], &[u8]) -> Result<(), InstructionError>;
fn(&Pubkey, &mut [KeyedAccount], &[u8]) -> Result<(), InstructionError>;
pub type SymbolCache = RwLock<HashMap<Vec<u8>, Symbol<instruction_processor_utils::Entrypoint>>>; pub type SymbolCache = RwLock<HashMap<Vec<u8>, Symbol<instruction_processor_utils::Entrypoint>>>;
@ -168,8 +167,8 @@ impl MessageProcessor {
&self, &self,
message: &Message, message: &Message,
instruction: &CompiledInstruction, instruction: &CompiledInstruction,
executable_accounts: &mut [(Pubkey, RefCell<Account>)], executable_accounts: &[(Pubkey, RefCell<Account>)],
program_accounts: &mut [Rc<RefCell<Account>>], program_accounts: &[Rc<RefCell<Account>>],
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
let program_id = instruction.program_id(&message.account_keys); let program_id = instruction.program_id(&message.account_keys);
let mut keyed_accounts = create_keyed_readonly_accounts(executable_accounts); let mut keyed_accounts = create_keyed_readonly_accounts(executable_accounts);
@ -186,7 +185,7 @@ impl MessageProcessor {
is_writable, is_writable,
) )
}) })
.zip(program_accounts.iter_mut()) .zip(program_accounts.iter())
.map(|((key, is_signer, is_writable), account)| { .map(|((key, is_signer, is_writable), account)| {
if is_writable { if is_writable {
KeyedAccount::new(key, is_signer, account) KeyedAccount::new(key, is_signer, account)
@ -205,25 +204,21 @@ impl MessageProcessor {
let loader_id = keyed_accounts[0].unsigned_key(); let loader_id = keyed_accounts[0].unsigned_key();
for (id, process_instruction) in &self.instruction_processors { for (id, process_instruction) in &self.instruction_processors {
if id == loader_id { if id == loader_id {
return process_instruction( return process_instruction(&program_id, &keyed_accounts[1..], &instruction.data);
&program_id,
&mut keyed_accounts[1..],
&instruction.data,
);
} }
} }
native_loader::invoke_entrypoint( native_loader::invoke_entrypoint(
&program_id, &program_id,
&mut keyed_accounts, &keyed_accounts,
&instruction.data, &instruction.data,
&self.symbol_cache, &self.symbol_cache,
) )
} }
pub fn verify_account_references( pub fn verify_account_references(
executable_accounts: &mut [(Pubkey, RefCell<Account>)], executable_accounts: &[(Pubkey, RefCell<Account>)],
program_accounts: &mut [Rc<RefCell<Account>>], program_accounts: &[Rc<RefCell<Account>>],
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
for account in program_accounts.iter() { for account in program_accounts.iter() {
account account
@ -263,14 +258,14 @@ impl MessageProcessor {
&self, &self,
message: &Message, message: &Message,
instruction: &CompiledInstruction, instruction: &CompiledInstruction,
executable_accounts: &mut [(Pubkey, RefCell<Account>)], executable_accounts: &[(Pubkey, RefCell<Account>)],
program_accounts: &mut [Rc<RefCell<Account>>], program_accounts: &[Rc<RefCell<Account>>],
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
assert_eq!(instruction.accounts.len(), program_accounts.len()); assert_eq!(instruction.accounts.len(), program_accounts.len());
let program_id = instruction.program_id(&message.account_keys); let program_id = instruction.program_id(&message.account_keys);
// Copy only what we need to verify after instruction processing // Copy only what we need to verify after instruction processing
let pre_accounts: Vec<_> = program_accounts let pre_accounts: Vec<_> = program_accounts
.iter_mut() .iter()
.enumerate() .enumerate()
.map(|(i, account)| { .map(|(i, account)| {
let is_writable = message.is_writable(instruction.accounts[i] as usize); let is_writable = message.is_writable(instruction.accounts[i] as usize);
@ -310,30 +305,25 @@ impl MessageProcessor {
pub fn process_message( pub fn process_message(
&self, &self,
message: &Message, message: &Message,
loaders: &mut [Vec<(Pubkey, RefCell<Account>)>], loaders: &[Vec<(Pubkey, RefCell<Account>)>],
accounts: &mut [Rc<RefCell<Account>>], accounts: &[Rc<RefCell<Account>>],
) -> Result<(), TransactionError> { ) -> Result<(), TransactionError> {
for (instruction_index, instruction) in message.instructions.iter().enumerate() { for (instruction_index, instruction) in message.instructions.iter().enumerate() {
let executable_index = message let executable_index = message
.program_position(instruction.program_id_index as usize) .program_position(instruction.program_id_index as usize)
.ok_or(TransactionError::InvalidAccountIndex)?; .ok_or(TransactionError::InvalidAccountIndex)?;
let executable_accounts = &mut loaders[executable_index]; let executable_accounts = &loaders[executable_index];
// TODO: panics on an index out of bounds if an executable // TODO: panics on an index out of bounds if an executable
// account is also included as a regular account for an instruction, because the // account is also included as a regular account for an instruction, because the
// executable account is not passed in as part of the accounts slice // executable account is not passed in as part of the accounts slice
let mut program_accounts: Vec<_> = instruction let program_accounts: Vec<_> = instruction
.accounts .accounts
.iter() .iter()
.map(|i| accounts[*i as usize].clone()) .map(|i| accounts[*i as usize].clone())
.collect(); .collect();
self.execute_instruction( self.execute_instruction(message, instruction, executable_accounts, &program_accounts)
message,
instruction,
executable_accounts,
&mut program_accounts,
)
.map_err(|err| TransactionError::InstructionError(instruction_index as u8, err))?; .map_err(|err| TransactionError::InstructionError(instruction_index as u8, err))?;
} }
Ok(()) Ok(())
@ -379,26 +369,28 @@ mod tests {
#[test] #[test]
fn test_verify_account_references() { fn test_verify_account_references() {
let mut executable_accounts = vec![(Pubkey::new_rand(), RefCell::new(Account::default()))]; let executable_accounts = vec![(Pubkey::new_rand(), RefCell::new(Account::default()))];
let mut program_accounts = vec![Rc::new(RefCell::new(Account::default()))]; let program_accounts = vec![Rc::new(RefCell::new(Account::default()))];
assert!(MessageProcessor::verify_account_references( assert!(MessageProcessor::verify_account_references(
&mut executable_accounts, &executable_accounts,
&mut program_accounts, &program_accounts,
) )
.is_ok()); .is_ok());
let cloned = program_accounts[0].clone(); let cloned = program_accounts[0].clone();
let _borrowed = cloned.borrow(); let _borrowed = cloned.borrow();
assert_eq!( assert_eq!(
MessageProcessor::verify_account_references( MessageProcessor::verify_account_references(&executable_accounts, &program_accounts,),
&mut executable_accounts,
&mut program_accounts,
),
Err(InstructionError::AccountBorrowOutstanding) Err(InstructionError::AccountBorrowOutstanding)
); );
// TODO when the `&mut`s go away test outstanding executable_account refs let cloned = executable_accounts[0].1.clone();
let _borrowed = cloned.borrow();
assert_eq!(
MessageProcessor::verify_account_references(&executable_accounts, &program_accounts,),
Err(InstructionError::AccountBorrowOutstanding)
);
} }
#[test] #[test]
@ -408,10 +400,10 @@ mod tests {
let account2 = Rc::new(RefCell::new(Account::new(2, 1, &owner_pubkey))); let account2 = Rc::new(RefCell::new(Account::new(2, 1, &owner_pubkey)));
let account3 = Rc::new(RefCell::new(Account::new(3, 1, &owner_pubkey))); let account3 = Rc::new(RefCell::new(Account::new(3, 1, &owner_pubkey)));
assert_eq!(0, MessageProcessor::sum_account_lamports(&mut vec![])); assert_eq!(0, MessageProcessor::sum_account_lamports(&vec![]));
assert_eq!( assert_eq!(
6, 6,
MessageProcessor::sum_account_lamports(&mut vec![ MessageProcessor::sum_account_lamports(&vec![
account1.clone(), account1.clone(),
account2.clone(), account2.clone(),
account3.clone() account3.clone()
@ -419,7 +411,7 @@ mod tests {
); );
assert_eq!( assert_eq!(
3, 3,
MessageProcessor::sum_account_lamports(&mut vec![ MessageProcessor::sum_account_lamports(&vec![
account1.clone(), account1.clone(),
account2.clone(), account2.clone(),
account1.clone() account1.clone()
@ -427,7 +419,7 @@ mod tests {
); );
assert_eq!( assert_eq!(
1, 1,
MessageProcessor::sum_account_lamports(&mut vec![ MessageProcessor::sum_account_lamports(&vec![
account1.clone(), account1.clone(),
account1.clone(), account1.clone(),
account1.clone() account1.clone()
@ -435,7 +427,7 @@ mod tests {
); );
assert_eq!( assert_eq!(
6, 6,
MessageProcessor::sum_account_lamports(&mut vec![ MessageProcessor::sum_account_lamports(&vec![
account1.clone(), account1.clone(),
account2.clone(), account2.clone(),
account3.clone(), account3.clone(),
@ -805,7 +797,7 @@ mod tests {
fn mock_system_process_instruction( fn mock_system_process_instruction(
_program_id: &Pubkey, _program_id: &Pubkey,
keyed_accounts: &mut [KeyedAccount], keyed_accounts: &[KeyedAccount],
data: &[u8], data: &[u8],
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
if let Ok(instruction) = bincode::deserialize(data) { if let Ok(instruction) = bincode::deserialize(data) {
@ -854,7 +846,7 @@ mod tests {
account_metas.clone(), account_metas.clone(),
)]); )]);
let result = message_processor.process_message(&message, &mut loaders, &mut accounts); let result = message_processor.process_message(&message, &loaders, &accounts);
assert_eq!(result, Ok(())); assert_eq!(result, Ok(()));
assert_eq!(accounts[0].borrow().lamports, 100); assert_eq!(accounts[0].borrow().lamports, 100);
assert_eq!(accounts[1].borrow().lamports, 0); assert_eq!(accounts[1].borrow().lamports, 0);
@ -865,7 +857,7 @@ mod tests {
account_metas.clone(), account_metas.clone(),
)]); )]);
let result = message_processor.process_message(&message, &mut loaders, &mut accounts); let result = message_processor.process_message(&message, &loaders, &accounts);
assert_eq!( assert_eq!(
result, result,
Err(TransactionError::InstructionError( Err(TransactionError::InstructionError(
@ -880,7 +872,7 @@ mod tests {
account_metas, account_metas,
)]); )]);
let result = message_processor.process_message(&message, &mut loaders, &mut accounts); let result = message_processor.process_message(&message, &loaders, &accounts);
assert_eq!( assert_eq!(
result, result,
Err(TransactionError::InstructionError( Err(TransactionError::InstructionError(
@ -901,7 +893,7 @@ mod tests {
fn mock_system_process_instruction( fn mock_system_process_instruction(
_program_id: &Pubkey, _program_id: &Pubkey,
keyed_accounts: &mut [KeyedAccount], keyed_accounts: &[KeyedAccount],
data: &[u8], data: &[u8],
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
if let Ok(instruction) = bincode::deserialize(data) { if let Ok(instruction) = bincode::deserialize(data) {
@ -976,7 +968,7 @@ mod tests {
&MockSystemInstruction::BorrowFail, &MockSystemInstruction::BorrowFail,
account_metas.clone(), account_metas.clone(),
)]); )]);
let result = message_processor.process_message(&message, &mut loaders, &mut accounts); let result = message_processor.process_message(&message, &loaders, &accounts);
assert_eq!( assert_eq!(
result, result,
Err(TransactionError::InstructionError( Err(TransactionError::InstructionError(
@ -991,7 +983,7 @@ mod tests {
&MockSystemInstruction::MultiBorrowMut, &MockSystemInstruction::MultiBorrowMut,
account_metas.clone(), account_metas.clone(),
)]); )]);
let result = message_processor.process_message(&message, &mut loaders, &mut accounts); let result = message_processor.process_message(&message, &loaders, &accounts);
assert_eq!(result, Ok(())); assert_eq!(result, Ok(()));
// Do work on the same account but at different location in keyed_accounts[] // Do work on the same account but at different location in keyed_accounts[]
@ -1003,7 +995,7 @@ mod tests {
}, },
account_metas, account_metas,
)]); )]);
let result = message_processor.process_message(&message, &mut loaders, &mut accounts); let result = message_processor.process_message(&message, &loaders, &accounts);
assert_eq!(result, Ok(())); assert_eq!(result, Ok(()));
assert_eq!(accounts[0].borrow().lamports, 80); assert_eq!(accounts[0].borrow().lamports, 80);
assert_eq!(accounts[1].borrow().lamports, 20); assert_eq!(accounts[1].borrow().lamports, 20);

View File

@ -66,12 +66,12 @@ fn library_open(path: &PathBuf) -> std::io::Result<Library> {
pub fn invoke_entrypoint( pub fn invoke_entrypoint(
program_id: &Pubkey, program_id: &Pubkey,
keyed_accounts: &mut [KeyedAccount], keyed_accounts: &[KeyedAccount],
instruction_data: &[u8], instruction_data: &[u8],
symbol_cache: &SymbolCache, symbol_cache: &SymbolCache,
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
// dispatch it // dispatch it
let (names, params) = keyed_accounts.split_at_mut(1); let (names, params) = keyed_accounts.split_at(1);
let name_vec = &names[0].try_account_ref()?.data; let name_vec = &names[0].try_account_ref()?.data;
if let Some(entrypoint) = symbol_cache.read().unwrap().get(name_vec) { if let Some(entrypoint) = symbol_cache.read().unwrap().get(name_vec) {
unsafe { unsafe {

View File

@ -1,6 +1,6 @@
use solana_sdk::{ use solana_sdk::{
account::Account, account::Account,
account_utils::State, account_utils::StateMut,
hash::Hash, hash::Hash,
instruction::CompiledInstruction, instruction::CompiledInstruction,
instruction_processor_utils::limited_deserialize, instruction_processor_utils::limited_deserialize,
@ -75,6 +75,7 @@ mod tests {
use super::*; use super::*;
use solana_sdk::{ use solana_sdk::{
account::Account, account::Account,
account_utils::State,
hash::Hash, hash::Hash,
instruction::InstructionError, instruction::InstructionError,
nonce_state::{with_test_keyed_account, Meta, NonceAccount}, nonce_state::{with_test_keyed_account, Meta, NonceAccount},

View File

@ -1,6 +1,6 @@
use crate::bank::Bank; use crate::bank::Bank;
use solana_sdk::account::Account; use solana_sdk::account::Account;
use solana_sdk::account_utils::State; use solana_sdk::account_utils::StateMut;
use solana_sdk::pubkey::Pubkey; use solana_sdk::pubkey::Pubkey;
use solana_storage_program::storage_contract::StorageContract; use solana_storage_program::storage_contract::StorageContract;
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};

View File

@ -2,7 +2,7 @@ use log::*;
use solana_sdk::{ use solana_sdk::{
account::{get_signers, Account, KeyedAccount}, account::{get_signers, Account, KeyedAccount},
account_utils::State, account_utils::StateMut,
instruction::InstructionError, instruction::InstructionError,
instruction_processor_utils::{limited_deserialize, next_keyed_account}, instruction_processor_utils::{limited_deserialize, next_keyed_account},
nonce_state::{NonceAccount, NonceState}, nonce_state::{NonceAccount, NonceState},
@ -125,7 +125,7 @@ fn allocate_and_assign(
} }
fn create_account( fn create_account(
from: &mut KeyedAccount, from: &KeyedAccount,
to: &mut Account, to: &mut Account,
to_address: &Address, to_address: &Address,
lamports: u64, lamports: u64,
@ -137,11 +137,7 @@ fn create_account(
transfer(from, to, lamports) transfer(from, to, lamports)
} }
fn transfer( fn transfer(from: &KeyedAccount, to: &mut Account, lamports: u64) -> Result<(), InstructionError> {
from: &mut KeyedAccount,
to: &mut Account,
lamports: u64,
) -> Result<(), InstructionError> {
if lamports == 0 { if lamports == 0 {
return Ok(()); return Ok(());
} }
@ -171,7 +167,7 @@ fn transfer(
pub fn process_instruction( pub fn process_instruction(
_program_id: &Pubkey, _program_id: &Pubkey,
keyed_accounts: &mut [KeyedAccount], keyed_accounts: &[KeyedAccount],
instruction_data: &[u8], instruction_data: &[u8],
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
let instruction = limited_deserialize(instruction_data)?; let instruction = limited_deserialize(instruction_data)?;
@ -180,7 +176,7 @@ pub fn process_instruction(
trace!("keyed_accounts: {:?}", keyed_accounts); trace!("keyed_accounts: {:?}", keyed_accounts);
let signers = get_signers(keyed_accounts); let signers = get_signers(keyed_accounts);
let keyed_accounts_iter = &mut keyed_accounts.iter_mut(); let keyed_accounts_iter = &mut keyed_accounts.iter();
match instruction { match instruction {
SystemInstruction::CreateAccount { SystemInstruction::CreateAccount {
@ -371,15 +367,15 @@ mod tests {
let new_program_owner = Pubkey::new(&[9; 32]); let new_program_owner = Pubkey::new(&[9; 32]);
let from = Pubkey::new_rand(); let from = Pubkey::new_rand();
let to = Pubkey::new_rand(); let to = Pubkey::new_rand();
let mut from_account = Account::new_ref(100, 0, &system_program::id()); let from_account = Account::new_ref(100, 0, &system_program::id());
let mut to_account = Account::new_ref(0, 0, &Pubkey::default()); let to_account = Account::new_ref(0, 0, &Pubkey::default());
assert_eq!( assert_eq!(
process_instruction( process_instruction(
&Pubkey::default(), &Pubkey::default(),
&mut [ &[
KeyedAccount::new(&from, true, &mut from_account), KeyedAccount::new(&from, true, &from_account),
KeyedAccount::new(&to, true, &mut to_account) KeyedAccount::new(&to, true, &to_account)
], ],
&bincode::serialize(&SystemInstruction::CreateAccount { &bincode::serialize(&SystemInstruction::CreateAccount {
lamports: 50, lamports: 50,
@ -403,15 +399,15 @@ mod tests {
let seed = "shiny pepper"; let seed = "shiny pepper";
let to = create_address_with_seed(&from, seed, &new_program_owner).unwrap(); let to = create_address_with_seed(&from, seed, &new_program_owner).unwrap();
let mut from_account = Account::new_ref(100, 0, &system_program::id()); let from_account = Account::new_ref(100, 0, &system_program::id());
let mut to_account = Account::new_ref(0, 0, &Pubkey::default()); let to_account = Account::new_ref(0, 0, &Pubkey::default());
assert_eq!( assert_eq!(
process_instruction( process_instruction(
&Pubkey::default(), &Pubkey::default(),
&mut [ &[
KeyedAccount::new(&from, true, &mut from_account), KeyedAccount::new(&from, true, &from_account),
KeyedAccount::new(&to, false, &mut to_account) KeyedAccount::new(&to, false, &to_account)
], ],
&bincode::serialize(&SystemInstruction::CreateAccountWithSeed { &bincode::serialize(&SystemInstruction::CreateAccountWithSeed {
base: from, base: from,
@ -456,7 +452,7 @@ mod tests {
assert_eq!( assert_eq!(
create_account( create_account(
&mut KeyedAccount::new(&from, false, &from_account), &KeyedAccount::new(&from, false, &from_account),
&mut to_account, &mut to_account,
&to_address, &to_address,
50, 50,
@ -482,7 +478,7 @@ mod tests {
assert_eq!( assert_eq!(
create_account( create_account(
&mut KeyedAccount::new(&from, false, &from_account), // no signer &KeyedAccount::new(&from, false, &from_account), // no signer
&mut to_account, &mut to_account,
&to.into(), &to.into(),
0, 0,
@ -508,13 +504,13 @@ mod tests {
// Attempt to create account with more lamports than remaining in from_account // Attempt to create account with more lamports than remaining in from_account
let new_program_owner = Pubkey::new(&[9; 32]); let new_program_owner = Pubkey::new(&[9; 32]);
let from = Pubkey::new_rand(); let from = Pubkey::new_rand();
let mut from_account = Account::new_ref(100, 0, &system_program::id()); let from_account = Account::new_ref(100, 0, &system_program::id());
let to = Pubkey::new_rand(); let to = Pubkey::new_rand();
let mut to_account = Account::new(0, 0, &Pubkey::default()); let mut to_account = Account::new(0, 0, &Pubkey::default());
let result = create_account( let result = create_account(
&mut KeyedAccount::new(&from, true, &mut from_account), &KeyedAccount::new(&from, true, &from_account),
&mut to_account, &mut to_account,
&to.into(), &to.into(),
150, 150,
@ -527,7 +523,7 @@ mod tests {
#[test] #[test]
fn test_request_more_than_allowed_data_length() { fn test_request_more_than_allowed_data_length() {
let mut from_account = Account::new_ref(100, 0, &system_program::id()); let from_account = Account::new_ref(100, 0, &system_program::id());
let from = Pubkey::new_rand(); let from = Pubkey::new_rand();
let mut to_account = Account::default(); let mut to_account = Account::default();
let to = Pubkey::new_rand(); let to = Pubkey::new_rand();
@ -537,7 +533,7 @@ mod tests {
// Trying to request more data length than permitted will result in failure // Trying to request more data length than permitted will result in failure
let result = create_account( let result = create_account(
&mut KeyedAccount::new(&from, true, &mut from_account), &KeyedAccount::new(&from, true, &from_account),
&mut to_account, &mut to_account,
&address, &address,
50, 50,
@ -553,7 +549,7 @@ mod tests {
// Trying to request equal or less data length than permitted will be successful // Trying to request equal or less data length than permitted will be successful
let result = create_account( let result = create_account(
&mut KeyedAccount::new(&from, true, &mut from_account), &KeyedAccount::new(&from, true, &from_account),
&mut to_account, &mut to_account,
&address, &address,
50, 50,
@ -582,7 +578,7 @@ mod tests {
let owned_address = owned_key.into(); let owned_address = owned_key.into();
let result = create_account( let result = create_account(
&mut KeyedAccount::new(&from, true, &from_account), &KeyedAccount::new(&from, true, &from_account),
&mut owned_account, &mut owned_account,
&owned_address, &owned_address,
50, 50,
@ -600,7 +596,7 @@ mod tests {
let mut owned_account = Account::new(0, 1, &Pubkey::default()); let mut owned_account = Account::new(0, 1, &Pubkey::default());
let unchanged_account = owned_account.clone(); let unchanged_account = owned_account.clone();
let result = create_account( let result = create_account(
&mut KeyedAccount::new(&from, true, &from_account), &KeyedAccount::new(&from, true, &from_account),
&mut owned_account, &mut owned_account,
&owned_address, &owned_address,
50, 50,
@ -616,7 +612,7 @@ mod tests {
// Verify that create_account works even if `to` has a non-zero balance // Verify that create_account works even if `to` has a non-zero balance
let mut owned_account = Account::new(1, 0, &Pubkey::default()); let mut owned_account = Account::new(1, 0, &Pubkey::default());
let result = create_account( let result = create_account(
&mut KeyedAccount::new(&from, true, &from_account), &KeyedAccount::new(&from, true, &from_account),
&mut owned_account, &mut owned_account,
&owned_address, &owned_address,
50, 50,
@ -634,7 +630,7 @@ mod tests {
// Attempt to create an account without signing the transfer // Attempt to create an account without signing the transfer
let new_program_owner = Pubkey::new(&[9; 32]); let new_program_owner = Pubkey::new(&[9; 32]);
let from = Pubkey::new_rand(); let from = Pubkey::new_rand();
let mut from_account = Account::new_ref(100, 0, &system_program::id()); let from_account = Account::new_ref(100, 0, &system_program::id());
let owned_key = Pubkey::new_rand(); let owned_key = Pubkey::new_rand();
let mut owned_account = Account::new(0, 0, &Pubkey::default()); let mut owned_account = Account::new(0, 0, &Pubkey::default());
@ -643,7 +639,7 @@ mod tests {
// Haven't signed from account // Haven't signed from account
let result = create_account( let result = create_account(
&mut KeyedAccount::new(&from, false, &mut from_account), &KeyedAccount::new(&from, false, &from_account),
&mut owned_account, &mut owned_account,
&owned_address, &owned_address,
50, 50,
@ -656,7 +652,7 @@ mod tests {
// Haven't signed to account // Haven't signed to account
let mut owned_account = Account::new(0, 0, &Pubkey::default()); let mut owned_account = Account::new(0, 0, &Pubkey::default());
let result = create_account( let result = create_account(
&mut KeyedAccount::new(&from, true, &mut from_account), &KeyedAccount::new(&from, true, &from_account),
&mut owned_account, &mut owned_account,
&owned_address, &owned_address,
50, 50,
@ -669,7 +665,7 @@ mod tests {
// support creation/assignment with zero lamports (ephemeral account) // support creation/assignment with zero lamports (ephemeral account)
let mut owned_account = Account::new(0, 0, &Pubkey::default()); let mut owned_account = Account::new(0, 0, &Pubkey::default());
let result = create_account( let result = create_account(
&mut KeyedAccount::new(&from, false, &mut from_account), &KeyedAccount::new(&from, false, &from_account),
&mut owned_account, &mut owned_account,
&owned_address, &owned_address,
0, 0,
@ -684,7 +680,7 @@ mod tests {
fn test_create_sysvar_invalid_id() { fn test_create_sysvar_invalid_id() {
// Attempt to create system account in account already owned by another program // Attempt to create system account in account already owned by another program
let from = Pubkey::new_rand(); let from = Pubkey::new_rand();
let mut from_account = Account::new_ref(100, 0, &system_program::id()); let from_account = Account::new_ref(100, 0, &system_program::id());
let to = Pubkey::new_rand(); let to = Pubkey::new_rand();
let mut to_account = Account::default(); let mut to_account = Account::default();
@ -694,7 +690,7 @@ mod tests {
// fail to create a sysvar::id() owned account // fail to create a sysvar::id() owned account
let result = create_account( let result = create_account(
&mut KeyedAccount::new(&from, true, &mut from_account), &KeyedAccount::new(&from, true, &from_account),
&mut to_account, &mut to_account,
&to_address, &to_address,
50, 50,
@ -711,7 +707,7 @@ mod tests {
// Attempt to create system account in account with populated data // Attempt to create system account in account with populated data
let new_program_owner = Pubkey::new(&[9; 32]); let new_program_owner = Pubkey::new(&[9; 32]);
let from = Pubkey::new_rand(); let from = Pubkey::new_rand();
let mut from_account = Account::new_ref(100, 0, &system_program::id()); let from_account = Account::new_ref(100, 0, &system_program::id());
let populated_key = Pubkey::new_rand(); let populated_key = Pubkey::new_rand();
let mut populated_account = Account { let mut populated_account = Account {
@ -726,7 +722,7 @@ mod tests {
let populated_address = populated_key.into(); let populated_address = populated_key.into();
let result = create_account( let result = create_account(
&mut KeyedAccount::new(&from, true, &mut from_account), &KeyedAccount::new(&from, true, &from_account),
&mut populated_account, &mut populated_account,
&populated_address, &populated_address,
50, 50,
@ -740,7 +736,7 @@ mod tests {
#[test] #[test]
fn test_create_from_account_is_nonce_fail() { fn test_create_from_account_is_nonce_fail() {
let nonce = Pubkey::new_rand(); let nonce = Pubkey::new_rand();
let mut nonce_account = Account::new_ref_data( let nonce_account = Account::new_ref_data(
42, 42,
&nonce_state::NonceState::Initialized( &nonce_state::NonceState::Initialized(
nonce_state::Meta::new(&Pubkey::default()), nonce_state::Meta::new(&Pubkey::default()),
@ -749,7 +745,7 @@ mod tests {
&system_program::id(), &system_program::id(),
) )
.unwrap(); .unwrap();
let mut from = KeyedAccount::new(&nonce, true, &mut nonce_account); let from = KeyedAccount::new(&nonce, true, &nonce_account);
let new = Pubkey::new_rand(); let new = Pubkey::new_rand();
let mut new_account = Account::default(); let mut new_account = Account::default();
@ -759,7 +755,7 @@ mod tests {
assert_eq!( assert_eq!(
create_account( create_account(
&mut from, &from,
&mut new_account, &mut new_account,
&new_address, &new_address,
42, 42,
@ -798,11 +794,11 @@ mod tests {
Ok(()) Ok(())
); );
let mut account = RefCell::new(account); let account = RefCell::new(account);
assert_eq!( assert_eq!(
process_instruction( process_instruction(
&Pubkey::default(), &Pubkey::default(),
&mut [KeyedAccount::new(&pubkey, true, &mut account)], &[KeyedAccount::new(&pubkey, true, &account)],
&bincode::serialize(&SystemInstruction::Assign { &bincode::serialize(&SystemInstruction::Assign {
program_id: new_program_owner program_id: new_program_owner
}) })
@ -837,17 +833,17 @@ mod tests {
program_id: Pubkey::new_rand(), program_id: Pubkey::new_rand(),
}; };
let data = serialize(&instruction).unwrap(); let data = serialize(&instruction).unwrap();
let result = process_instruction(&system_program::id(), &mut [], &data); let result = process_instruction(&system_program::id(), &[], &data);
assert_eq!(result, Err(InstructionError::NotEnoughAccountKeys)); assert_eq!(result, Err(InstructionError::NotEnoughAccountKeys));
let from = Pubkey::new_rand(); let from = Pubkey::new_rand();
let mut from_account = Account::new_ref(100, 0, &system_program::id()); let from_account = Account::new_ref(100, 0, &system_program::id());
// Attempt to transfer with no destination // Attempt to transfer with no destination
let instruction = SystemInstruction::Transfer { lamports: 0 }; let instruction = SystemInstruction::Transfer { lamports: 0 };
let data = serialize(&instruction).unwrap(); let data = serialize(&instruction).unwrap();
let result = process_instruction( let result = process_instruction(
&system_program::id(), &system_program::id(),
&mut [KeyedAccount::new(&from, true, &mut from_account)], &[KeyedAccount::new(&from, true, &from_account)],
&data, &data,
); );
assert_eq!(result, Err(InstructionError::NotEnoughAccountKeys)); assert_eq!(result, Err(InstructionError::NotEnoughAccountKeys));
@ -858,23 +854,23 @@ mod tests {
let from = Pubkey::new_rand(); let from = Pubkey::new_rand();
let from_account = Account::new_ref(100, 0, &Pubkey::new(&[2; 32])); // account owner should not matter let from_account = Account::new_ref(100, 0, &Pubkey::new(&[2; 32])); // account owner should not matter
let mut to_account = Account::new(1, 0, &Pubkey::new(&[3; 32])); // account owner should not matter let mut to_account = Account::new(1, 0, &Pubkey::new(&[3; 32])); // account owner should not matter
let mut from_keyed_account = KeyedAccount::new(&from, true, &from_account); let from_keyed_account = KeyedAccount::new(&from, true, &from_account);
transfer(&mut from_keyed_account, &mut to_account, 50).unwrap(); transfer(&from_keyed_account, &mut to_account, 50).unwrap();
let from_lamports = from_keyed_account.account.borrow().lamports; let from_lamports = from_keyed_account.account.borrow().lamports;
let to_lamports = to_account.lamports; let to_lamports = to_account.lamports;
assert_eq!(from_lamports, 50); assert_eq!(from_lamports, 50);
assert_eq!(to_lamports, 51); assert_eq!(to_lamports, 51);
// Attempt to move more lamports than remaining in from_account // Attempt to move more lamports than remaining in from_account
let mut from_keyed_account = KeyedAccount::new(&from, true, &from_account); let from_keyed_account = KeyedAccount::new(&from, true, &from_account);
let result = transfer(&mut from_keyed_account, &mut to_account, 100); let result = transfer(&from_keyed_account, &mut to_account, 100);
assert_eq!(result, Err(SystemError::ResultWithNegativeLamports.into())); assert_eq!(result, Err(SystemError::ResultWithNegativeLamports.into()));
assert_eq!(from_keyed_account.account.borrow().lamports, 50); assert_eq!(from_keyed_account.account.borrow().lamports, 50);
assert_eq!(to_account.lamports, 51); assert_eq!(to_account.lamports, 51);
// test unsigned transfer of zero // test unsigned transfer of zero
let mut from_keyed_account = KeyedAccount::new(&from, false, &from_account); let from_keyed_account = KeyedAccount::new(&from, false, &from_account);
assert!(transfer(&mut from_keyed_account, &mut to_account, 0,).is_ok(),); assert!(transfer(&from_keyed_account, &mut to_account, 0,).is_ok(),);
assert_eq!(from_keyed_account.account.borrow().lamports, 50); assert_eq!(from_keyed_account.account.borrow().lamports, 50);
assert_eq!(to_account.lamports, 51); assert_eq!(to_account.lamports, 51);
} }
@ -882,7 +878,7 @@ mod tests {
#[test] #[test]
fn test_transfer_lamports_from_nonce_account_fail() { fn test_transfer_lamports_from_nonce_account_fail() {
let from = Pubkey::new_rand(); let from = Pubkey::new_rand();
let mut from_account = Account::new_ref_data( let from_account = Account::new_ref_data(
100, 100,
&nonce_state::NonceState::Initialized(nonce_state::Meta::new(&from), Hash::default()), &nonce_state::NonceState::Initialized(nonce_state::Meta::new(&from), Hash::default()),
&system_program::id(), &system_program::id(),
@ -896,7 +892,7 @@ mod tests {
let mut to_account = Account::new(1, 0, &Pubkey::new(&[3; 32])); // account owner should not matter let mut to_account = Account::new(1, 0, &Pubkey::new(&[3; 32])); // account owner should not matter
assert_eq!( assert_eq!(
transfer( transfer(
&mut KeyedAccount::new(&from, true, &mut from_account), &KeyedAccount::new(&from, true, &from_account),
&mut to_account, &mut to_account,
50, 50,
), ),
@ -1010,7 +1006,7 @@ mod tests {
} }
fn process_nonce_instruction(instruction: &Instruction) -> Result<(), InstructionError> { fn process_nonce_instruction(instruction: &Instruction) -> Result<(), InstructionError> {
let mut accounts: Vec<_> = instruction let accounts: Vec<_> = instruction
.accounts .accounts
.iter() .iter()
.map(|meta| { .map(|meta| {
@ -1028,17 +1024,13 @@ mod tests {
.collect(); .collect();
{ {
let mut keyed_accounts_iter: Vec<_> = instruction let keyed_accounts: Vec<_> = instruction
.accounts .accounts
.iter() .iter()
.zip(accounts.iter_mut()) .zip(accounts.iter())
.map(|(meta, account)| KeyedAccount::new(&meta.pubkey, meta.is_signer, account)) .map(|(meta, account)| KeyedAccount::new(&meta.pubkey, meta.is_signer, account))
.collect(); .collect();
super::process_instruction( super::process_instruction(&Pubkey::default(), &keyed_accounts, &instruction.data)
&Pubkey::default(),
&mut keyed_accounts_iter,
&instruction.data,
)
} }
} }
@ -1058,7 +1050,7 @@ mod tests {
assert_eq!( assert_eq!(
super::process_instruction( super::process_instruction(
&Pubkey::default(), &Pubkey::default(),
&mut [], &[],
&serialize(&SystemInstruction::AdvanceNonceAccount).unwrap() &serialize(&SystemInstruction::AdvanceNonceAccount).unwrap()
), ),
Err(InstructionError::NotEnoughAccountKeys), Err(InstructionError::NotEnoughAccountKeys),
@ -1070,7 +1062,7 @@ mod tests {
assert_eq!( assert_eq!(
super::process_instruction( super::process_instruction(
&Pubkey::default(), &Pubkey::default(),
&mut [KeyedAccount::new( &[KeyedAccount::new(
&Pubkey::default(), &Pubkey::default(),
true, true,
&create_default_account(), &create_default_account(),
@ -1086,7 +1078,7 @@ mod tests {
assert_eq!( assert_eq!(
super::process_instruction( super::process_instruction(
&Pubkey::default(), &Pubkey::default(),
&mut [ &[
KeyedAccount::new(&Pubkey::default(), true, &create_default_account()), KeyedAccount::new(&Pubkey::default(), true, &create_default_account()),
KeyedAccount::new( KeyedAccount::new(
&sysvar::recent_blockhashes::id(), &sysvar::recent_blockhashes::id(),
@ -1102,11 +1094,11 @@ mod tests {
#[test] #[test]
fn test_process_nonce_ix_ok() { fn test_process_nonce_ix_ok() {
let mut nonce_acc = nonce_state::create_account(1_000_000); let nonce_acc = nonce_state::create_account(1_000_000);
super::process_instruction( super::process_instruction(
&Pubkey::default(), &Pubkey::default(),
&mut [ &[
KeyedAccount::new(&Pubkey::default(), true, &mut nonce_acc), KeyedAccount::new(&Pubkey::default(), true, &nonce_acc),
KeyedAccount::new( KeyedAccount::new(
&sysvar::recent_blockhashes::id(), &sysvar::recent_blockhashes::id(),
false, false,
@ -1125,8 +1117,8 @@ mod tests {
assert_eq!( assert_eq!(
super::process_instruction( super::process_instruction(
&Pubkey::default(), &Pubkey::default(),
&mut [ &[
KeyedAccount::new(&Pubkey::default(), true, &mut nonce_acc,), KeyedAccount::new(&Pubkey::default(), true, &nonce_acc,),
KeyedAccount::new( KeyedAccount::new(
&sysvar::recent_blockhashes::id(), &sysvar::recent_blockhashes::id(),
false, false,
@ -1157,7 +1149,7 @@ mod tests {
assert_eq!( assert_eq!(
super::process_instruction( super::process_instruction(
&Pubkey::default(), &Pubkey::default(),
&mut [], &[],
&serialize(&SystemInstruction::WithdrawNonceAccount(42)).unwrap(), &serialize(&SystemInstruction::WithdrawNonceAccount(42)).unwrap(),
), ),
Err(InstructionError::NotEnoughAccountKeys), Err(InstructionError::NotEnoughAccountKeys),
@ -1169,7 +1161,7 @@ mod tests {
assert_eq!( assert_eq!(
super::process_instruction( super::process_instruction(
&Pubkey::default(), &Pubkey::default(),
&mut [KeyedAccount::new( &[KeyedAccount::new(
&Pubkey::default(), &Pubkey::default(),
true, true,
&create_default_account() &create_default_account()
@ -1185,7 +1177,7 @@ mod tests {
assert_eq!( assert_eq!(
super::process_instruction( super::process_instruction(
&Pubkey::default(), &Pubkey::default(),
&mut [ &[
KeyedAccount::new(&Pubkey::default(), true, &create_default_account()), KeyedAccount::new(&Pubkey::default(), true, &create_default_account()),
KeyedAccount::new(&Pubkey::default(), false, &create_default_account()), KeyedAccount::new(&Pubkey::default(), false, &create_default_account()),
KeyedAccount::new( KeyedAccount::new(
@ -1205,11 +1197,11 @@ mod tests {
assert_eq!( assert_eq!(
super::process_instruction( super::process_instruction(
&Pubkey::default(), &Pubkey::default(),
&mut [ &[
KeyedAccount::new( KeyedAccount::new(
&Pubkey::default(), &Pubkey::default(),
true, true,
&mut nonce_state::create_account(1_000_000), &nonce_state::create_account(1_000_000),
), ),
KeyedAccount::new(&Pubkey::default(), true, &create_default_account()), KeyedAccount::new(&Pubkey::default(), true, &create_default_account()),
KeyedAccount::new( KeyedAccount::new(
@ -1230,13 +1222,13 @@ mod tests {
assert_eq!( assert_eq!(
super::process_instruction( super::process_instruction(
&Pubkey::default(), &Pubkey::default(),
&mut [ &[
KeyedAccount::new( KeyedAccount::new(
&Pubkey::default(), &Pubkey::default(),
true, true,
&mut nonce_state::create_account(1_000_000), &nonce_state::create_account(1_000_000),
), ),
KeyedAccount::new(&Pubkey::default(), true, &mut create_default_account()), KeyedAccount::new(&Pubkey::default(), true, &create_default_account()),
KeyedAccount::new( KeyedAccount::new(
&sysvar::recent_blockhashes::id(), &sysvar::recent_blockhashes::id(),
false, false,
@ -1255,7 +1247,7 @@ mod tests {
assert_eq!( assert_eq!(
super::process_instruction( super::process_instruction(
&Pubkey::default(), &Pubkey::default(),
&mut [], &[],
&serialize(&SystemInstruction::InitializeNonceAccount(Pubkey::default())).unwrap(), &serialize(&SystemInstruction::InitializeNonceAccount(Pubkey::default())).unwrap(),
), ),
Err(InstructionError::NotEnoughAccountKeys), Err(InstructionError::NotEnoughAccountKeys),
@ -1267,10 +1259,10 @@ mod tests {
assert_eq!( assert_eq!(
super::process_instruction( super::process_instruction(
&Pubkey::default(), &Pubkey::default(),
&mut [KeyedAccount::new( &[KeyedAccount::new(
&Pubkey::default(), &Pubkey::default(),
true, true,
&mut nonce_state::create_account(1_000_000), &nonce_state::create_account(1_000_000),
),], ),],
&serialize(&SystemInstruction::InitializeNonceAccount(Pubkey::default())).unwrap(), &serialize(&SystemInstruction::InitializeNonceAccount(Pubkey::default())).unwrap(),
), ),
@ -1283,11 +1275,11 @@ mod tests {
assert_eq!( assert_eq!(
super::process_instruction( super::process_instruction(
&Pubkey::default(), &Pubkey::default(),
&mut [ &[
KeyedAccount::new( KeyedAccount::new(
&Pubkey::default(), &Pubkey::default(),
true, true,
&mut nonce_state::create_account(1_000_000), &nonce_state::create_account(1_000_000),
), ),
KeyedAccount::new( KeyedAccount::new(
&sysvar::recent_blockhashes::id(), &sysvar::recent_blockhashes::id(),
@ -1306,11 +1298,11 @@ mod tests {
assert_eq!( assert_eq!(
super::process_instruction( super::process_instruction(
&Pubkey::default(), &Pubkey::default(),
&mut [ &[
KeyedAccount::new( KeyedAccount::new(
&Pubkey::default(), &Pubkey::default(),
true, true,
&mut nonce_state::create_account(1_000_000), &nonce_state::create_account(1_000_000),
), ),
KeyedAccount::new( KeyedAccount::new(
&sysvar::recent_blockhashes::id(), &sysvar::recent_blockhashes::id(),
@ -1330,11 +1322,11 @@ mod tests {
assert_eq!( assert_eq!(
super::process_instruction( super::process_instruction(
&Pubkey::default(), &Pubkey::default(),
&mut [ &[
KeyedAccount::new( KeyedAccount::new(
&Pubkey::default(), &Pubkey::default(),
true, true,
&mut nonce_state::create_account(1_000_000), &nonce_state::create_account(1_000_000),
), ),
KeyedAccount::new( KeyedAccount::new(
&sysvar::recent_blockhashes::id(), &sysvar::recent_blockhashes::id(),
@ -1351,11 +1343,11 @@ mod tests {
#[test] #[test]
fn test_process_authorize_ix_ok() { fn test_process_authorize_ix_ok() {
let mut nonce_acc = nonce_state::create_account(1_000_000); let nonce_acc = nonce_state::create_account(1_000_000);
super::process_instruction( super::process_instruction(
&Pubkey::default(), &Pubkey::default(),
&mut [ &[
KeyedAccount::new(&Pubkey::default(), true, &mut nonce_acc), KeyedAccount::new(&Pubkey::default(), true, &nonce_acc),
KeyedAccount::new( KeyedAccount::new(
&sysvar::recent_blockhashes::id(), &sysvar::recent_blockhashes::id(),
false, false,
@ -1369,7 +1361,7 @@ mod tests {
assert_eq!( assert_eq!(
super::process_instruction( super::process_instruction(
&Pubkey::default(), &Pubkey::default(),
&mut [KeyedAccount::new(&Pubkey::default(), true, &mut nonce_acc,),], &[KeyedAccount::new(&Pubkey::default(), true, &nonce_acc,),],
&serialize(&SystemInstruction::AuthorizeNonceAccount(Pubkey::default(),)).unwrap(), &serialize(&SystemInstruction::AuthorizeNonceAccount(Pubkey::default(),)).unwrap(),
), ),
Ok(()), Ok(()),

View File

@ -4,7 +4,7 @@ use solana_runtime::{
genesis_utils::{create_genesis_config_with_leader, GenesisConfigInfo}, genesis_utils::{create_genesis_config_with_leader, GenesisConfigInfo},
}; };
use solana_sdk::{ use solana_sdk::{
account_utils::State, account_utils::StateMut,
client::SyncClient, client::SyncClient,
message::Message, message::Message,
pubkey::Pubkey, pubkey::Pubkey,

View File

@ -7,7 +7,7 @@ use solana_runtime::{
genesis_utils::{create_genesis_config, GenesisConfigInfo}, genesis_utils::{create_genesis_config, GenesisConfigInfo},
}; };
use solana_sdk::{ use solana_sdk::{
account_utils::State, account_utils::StateMut,
client::SyncClient, client::SyncClient,
clock::{get_segment_from_slot, DEFAULT_SLOTS_PER_SEGMENT, DEFAULT_TICKS_PER_SLOT}, clock::{get_segment_from_slot, DEFAULT_SLOTS_PER_SEGMENT, DEFAULT_TICKS_PER_SLOT},
hash::{hash, Hash}, hash::{hash, Hash},

View File

@ -247,8 +247,8 @@ impl<'a> From<(&'a Pubkey, bool, &'a RefCell<Account>)> for KeyedAccount<'a> {
} }
} }
impl<'a> From<&'a mut (&'a Pubkey, &'a RefCell<Account>)> for KeyedAccount<'a> { impl<'a> From<&'a (&'a Pubkey, &'a RefCell<Account>)> for KeyedAccount<'a> {
fn from((key, account): &'a mut (&'a Pubkey, &'a RefCell<Account>)) -> Self { fn from((key, account): &'a (&'a Pubkey, &'a RefCell<Account>)) -> Self {
Self { Self {
is_signer: false, is_signer: false,
is_writable: true, is_writable: true,
@ -259,16 +259,16 @@ impl<'a> From<&'a mut (&'a Pubkey, &'a RefCell<Account>)> for KeyedAccount<'a> {
} }
pub fn create_keyed_accounts<'a>( pub fn create_keyed_accounts<'a>(
accounts: &'a mut [(&'a Pubkey, &'a RefCell<Account>)], accounts: &'a [(&'a Pubkey, &'a RefCell<Account>)],
) -> Vec<KeyedAccount<'a>> { ) -> Vec<KeyedAccount<'a>> {
accounts.iter_mut().map(Into::into).collect() accounts.iter().map(Into::into).collect()
} }
pub fn create_keyed_is_signer_accounts<'a>( pub fn create_keyed_is_signer_accounts<'a>(
accounts: &'a mut [(&'a Pubkey, bool, &'a mut RefCell<Account>)], accounts: &'a [(&'a Pubkey, bool, &'a RefCell<Account>)],
) -> Vec<KeyedAccount<'a>> { ) -> Vec<KeyedAccount<'a>> {
accounts accounts
.iter_mut() .iter()
.map(|(key, is_signer, account)| KeyedAccount { .map(|(key, is_signer, account)| KeyedAccount {
is_signer: *is_signer, is_signer: *is_signer,
is_writable: false, is_writable: false,
@ -279,10 +279,10 @@ pub fn create_keyed_is_signer_accounts<'a>(
} }
pub fn create_keyed_readonly_accounts( pub fn create_keyed_readonly_accounts(
accounts: &mut [(Pubkey, RefCell<Account>)], accounts: &[(Pubkey, RefCell<Account>)],
) -> Vec<KeyedAccount> { ) -> Vec<KeyedAccount> {
accounts accounts
.iter_mut() .iter()
.map(|(key, account)| KeyedAccount { .map(|(key, account)| KeyedAccount {
is_signer: false, is_signer: false,
is_writable: false, is_writable: false,

View File

@ -6,12 +6,16 @@ use crate::{
use bincode::ErrorKind; use bincode::ErrorKind;
/// Convenience trait to covert bincode errors to instruction errors. /// Convenience trait to covert bincode errors to instruction errors.
pub trait State<T> { pub trait StateMut<T> {
fn state(&self) -> Result<T, InstructionError>; fn state(&self) -> Result<T, InstructionError>;
fn set_state(&mut self, state: &T) -> Result<(), InstructionError>; fn set_state(&mut self, state: &T) -> Result<(), InstructionError>;
} }
pub trait State<T> {
fn state(&self) -> Result<T, InstructionError>;
fn set_state(&self, state: &T) -> Result<(), InstructionError>;
}
impl<T> State<T> for Account impl<T> StateMut<T> for Account
where where
T: serde::Serialize + serde::de::DeserializeOwned, T: serde::Serialize + serde::de::DeserializeOwned,
{ {
@ -34,7 +38,7 @@ where
fn state(&self) -> Result<T, InstructionError> { fn state(&self) -> Result<T, InstructionError> {
self.try_account_ref()?.state() self.try_account_ref()?.state()
} }
fn set_state(&mut self, state: &T) -> Result<(), InstructionError> { fn set_state(&self, state: &T) -> Result<(), InstructionError> {
self.try_account_ref_mut()?.set_state(state) self.try_account_ref_mut()?.set_state(state)
} }
} }

View File

@ -4,7 +4,7 @@ use num_traits::{FromPrimitive, ToPrimitive};
// Native program ENTRYPOINT prototype // Native program ENTRYPOINT prototype
pub type Entrypoint = unsafe extern "C" fn( pub type Entrypoint = unsafe extern "C" fn(
program_id: &Pubkey, program_id: &Pubkey,
keyed_accounts: &mut [KeyedAccount], keyed_accounts: &[KeyedAccount],
instruction_data: &[u8], instruction_data: &[u8],
) -> Result<(), InstructionError>; ) -> Result<(), InstructionError>;
@ -28,7 +28,7 @@ pub type Entrypoint = unsafe extern "C" fn(
/// ///
/// fn my_process_instruction( /// fn my_process_instruction(
/// program_id: &Pubkey, /// program_id: &Pubkey,
/// keyed_accounts: &mut [KeyedAccount], /// keyed_accounts: &[KeyedAccount],
/// instruction_data: &[u8], /// instruction_data: &[u8],
/// ) -> Result<(), InstructionError> { /// ) -> Result<(), InstructionError> {
/// // Process an instruction /// // Process an instruction
@ -59,7 +59,7 @@ pub type Entrypoint = unsafe extern "C" fn(
/// ///
/// fn my_process_instruction( /// fn my_process_instruction(
/// program_id: &Pubkey, /// program_id: &Pubkey,
/// keyed_accounts: &mut [KeyedAccount], /// keyed_accounts: &[KeyedAccount],
/// instruction_data: &[u8], /// instruction_data: &[u8],
/// ) -> Result<(), InstructionError> { /// ) -> Result<(), InstructionError> {
/// // Process an instruction /// // Process an instruction
@ -91,7 +91,7 @@ macro_rules! declare_program(
#[no_mangle] #[no_mangle]
pub extern "C" fn $name( pub extern "C" fn $name(
program_id: &$crate::pubkey::Pubkey, program_id: &$crate::pubkey::Pubkey,
keyed_accounts: &mut [$crate::account::KeyedAccount], keyed_accounts: &[$crate::account::KeyedAccount],
instruction_data: &[u8], instruction_data: &[u8],
) -> Result<(), $crate::instruction::InstructionError> { ) -> Result<(), $crate::instruction::InstructionError> {
$entrypoint(program_id, keyed_accounts, instruction_data) $entrypoint(program_id, keyed_accounts, instruction_data)

View File

@ -46,26 +46,26 @@ impl NonceState {
pub trait NonceAccount { pub trait NonceAccount {
fn advance_nonce_account( fn advance_nonce_account(
&mut self, &self,
recent_blockhashes: &RecentBlockhashes, recent_blockhashes: &RecentBlockhashes,
signers: &HashSet<Pubkey>, signers: &HashSet<Pubkey>,
) -> Result<(), InstructionError>; ) -> Result<(), InstructionError>;
fn withdraw_nonce_account( fn withdraw_nonce_account(
&mut self, &self,
lamports: u64, lamports: u64,
to: &mut KeyedAccount, to: &KeyedAccount,
recent_blockhashes: &RecentBlockhashes, recent_blockhashes: &RecentBlockhashes,
rent: &Rent, rent: &Rent,
signers: &HashSet<Pubkey>, signers: &HashSet<Pubkey>,
) -> Result<(), InstructionError>; ) -> Result<(), InstructionError>;
fn initialize_nonce_account( fn initialize_nonce_account(
&mut self, &self,
nonce_authority: &Pubkey, nonce_authority: &Pubkey,
recent_blockhashes: &RecentBlockhashes, recent_blockhashes: &RecentBlockhashes,
rent: &Rent, rent: &Rent,
) -> Result<(), InstructionError>; ) -> Result<(), InstructionError>;
fn authorize_nonce_account( fn authorize_nonce_account(
&mut self, &self,
nonce_authority: &Pubkey, nonce_authority: &Pubkey,
signers: &HashSet<Pubkey>, signers: &HashSet<Pubkey>,
) -> Result<(), InstructionError>; ) -> Result<(), InstructionError>;
@ -73,7 +73,7 @@ pub trait NonceAccount {
impl<'a> NonceAccount for KeyedAccount<'a> { impl<'a> NonceAccount for KeyedAccount<'a> {
fn advance_nonce_account( fn advance_nonce_account(
&mut self, &self,
recent_blockhashes: &RecentBlockhashes, recent_blockhashes: &RecentBlockhashes,
signers: &HashSet<Pubkey>, signers: &HashSet<Pubkey>,
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
@ -98,9 +98,9 @@ impl<'a> NonceAccount for KeyedAccount<'a> {
} }
fn withdraw_nonce_account( fn withdraw_nonce_account(
&mut self, &self,
lamports: u64, lamports: u64,
to: &mut KeyedAccount, to: &KeyedAccount,
recent_blockhashes: &RecentBlockhashes, recent_blockhashes: &RecentBlockhashes,
rent: &Rent, rent: &Rent,
signers: &HashSet<Pubkey>, signers: &HashSet<Pubkey>,
@ -138,7 +138,7 @@ impl<'a> NonceAccount for KeyedAccount<'a> {
} }
fn initialize_nonce_account( fn initialize_nonce_account(
&mut self, &self,
nonce_authority: &Pubkey, nonce_authority: &Pubkey,
recent_blockhashes: &RecentBlockhashes, recent_blockhashes: &RecentBlockhashes,
rent: &Rent, rent: &Rent,
@ -162,7 +162,7 @@ impl<'a> NonceAccount for KeyedAccount<'a> {
} }
fn authorize_nonce_account( fn authorize_nonce_account(
&mut self, &self,
nonce_authority: &Pubkey, nonce_authority: &Pubkey,
signers: &HashSet<Pubkey>, signers: &HashSet<Pubkey>,
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
@ -192,14 +192,14 @@ pub fn create_account(lamports: u64) -> RefCell<Account> {
/// Convenience function for working with keyed accounts in tests /// Convenience function for working with keyed accounts in tests
#[cfg(not(feature = "program"))] #[cfg(not(feature = "program"))]
pub fn with_test_keyed_account<F>(lamports: u64, signer: bool, mut f: F) pub fn with_test_keyed_account<F>(lamports: u64, signer: bool, f: F)
where where
F: FnMut(&mut KeyedAccount), F: Fn(&KeyedAccount),
{ {
let pubkey = Pubkey::new_rand(); let pubkey = Pubkey::new_rand();
let account = create_account(lamports); let account = create_account(lamports);
let mut keyed_account = KeyedAccount::new(&pubkey, signer, &account); let keyed_account = KeyedAccount::new(&pubkey, signer, &account);
f(&mut keyed_account) f(&keyed_account)
} }
#[cfg(test)] #[cfg(test)]
@ -262,7 +262,7 @@ mod test {
let stored = recent_blockhashes[0]; let stored = recent_blockhashes[0];
// Third nonce instruction for fun and profit // Third nonce instruction for fun and profit
assert_eq!(state, NonceState::Initialized(meta, stored)); assert_eq!(state, NonceState::Initialized(meta, stored));
with_test_keyed_account(42, false, |mut to_keyed| { with_test_keyed_account(42, false, |to_keyed| {
let recent_blockhashes = create_test_recent_blockhashes(0); let recent_blockhashes = create_test_recent_blockhashes(0);
let withdraw_lamports = keyed_account.account.borrow().lamports; let withdraw_lamports = keyed_account.account.borrow().lamports;
let expect_nonce_lamports = let expect_nonce_lamports =
@ -271,7 +271,7 @@ mod test {
keyed_account keyed_account
.withdraw_nonce_account( .withdraw_nonce_account(
withdraw_lamports, withdraw_lamports,
&mut to_keyed, &to_keyed,
&recent_blockhashes, &recent_blockhashes,
&rent, &rent,
&signers, &signers,
@ -304,7 +304,7 @@ mod test {
.initialize_nonce_account(&authorized, &recent_blockhashes, &rent) .initialize_nonce_account(&authorized, &recent_blockhashes, &rent)
.unwrap(); .unwrap();
let pubkey = nonce_account.account.borrow().owner.clone(); let pubkey = nonce_account.account.borrow().owner.clone();
let mut nonce_account = KeyedAccount::new(&pubkey, false, nonce_account.account); let nonce_account = KeyedAccount::new(&pubkey, false, nonce_account.account);
let state: NonceState = nonce_account.state().unwrap(); let state: NonceState = nonce_account.state().unwrap();
assert_eq!(state, NonceState::Initialized(meta, stored)); assert_eq!(state, NonceState::Initialized(meta, stored));
let signers = HashSet::new(); let signers = HashSet::new();
@ -428,7 +428,7 @@ mod test {
with_test_keyed_account(min_lamports + 42, true, |nonce_keyed| { with_test_keyed_account(min_lamports + 42, true, |nonce_keyed| {
let state: NonceState = nonce_keyed.state().unwrap(); let state: NonceState = nonce_keyed.state().unwrap();
assert_eq!(state, NonceState::Uninitialized); assert_eq!(state, NonceState::Uninitialized);
with_test_keyed_account(42, false, |mut to_keyed| { with_test_keyed_account(42, false, |to_keyed| {
let mut signers = HashSet::new(); let mut signers = HashSet::new();
signers.insert(nonce_keyed.signer_key().unwrap().clone()); signers.insert(nonce_keyed.signer_key().unwrap().clone());
let recent_blockhashes = create_test_recent_blockhashes(0); let recent_blockhashes = create_test_recent_blockhashes(0);
@ -439,7 +439,7 @@ mod test {
nonce_keyed nonce_keyed
.withdraw_nonce_account( .withdraw_nonce_account(
withdraw_lamports, withdraw_lamports,
&mut to_keyed, &to_keyed,
&recent_blockhashes, &recent_blockhashes,
&rent, &rent,
&signers, &signers,
@ -467,13 +467,13 @@ mod test {
with_test_keyed_account(min_lamports + 42, false, |nonce_keyed| { with_test_keyed_account(min_lamports + 42, false, |nonce_keyed| {
let state: NonceState = nonce_keyed.state().unwrap(); let state: NonceState = nonce_keyed.state().unwrap();
assert_eq!(state, NonceState::Uninitialized); assert_eq!(state, NonceState::Uninitialized);
with_test_keyed_account(42, false, |mut to_keyed| { with_test_keyed_account(42, false, |to_keyed| {
let signers = HashSet::new(); let signers = HashSet::new();
let recent_blockhashes = create_test_recent_blockhashes(0); let recent_blockhashes = create_test_recent_blockhashes(0);
let lamports = nonce_keyed.account.borrow().lamports; let lamports = nonce_keyed.account.borrow().lamports;
let result = nonce_keyed.withdraw_nonce_account( let result = nonce_keyed.withdraw_nonce_account(
lamports, lamports,
&mut to_keyed, &to_keyed,
&recent_blockhashes, &recent_blockhashes,
&rent, &rent,
&signers, &signers,
@ -493,14 +493,14 @@ mod test {
with_test_keyed_account(min_lamports + 42, true, |nonce_keyed| { with_test_keyed_account(min_lamports + 42, true, |nonce_keyed| {
let state: NonceState = nonce_keyed.state().unwrap(); let state: NonceState = nonce_keyed.state().unwrap();
assert_eq!(state, NonceState::Uninitialized); assert_eq!(state, NonceState::Uninitialized);
with_test_keyed_account(42, false, |mut to_keyed| { with_test_keyed_account(42, false, |to_keyed| {
let mut signers = HashSet::new(); let mut signers = HashSet::new();
signers.insert(nonce_keyed.signer_key().unwrap().clone()); signers.insert(nonce_keyed.signer_key().unwrap().clone());
let recent_blockhashes = create_test_recent_blockhashes(0); let recent_blockhashes = create_test_recent_blockhashes(0);
let lamports = nonce_keyed.account.borrow().lamports + 1; let lamports = nonce_keyed.account.borrow().lamports + 1;
let result = nonce_keyed.withdraw_nonce_account( let result = nonce_keyed.withdraw_nonce_account(
lamports, lamports,
&mut to_keyed, &to_keyed,
&recent_blockhashes, &recent_blockhashes,
&rent, &rent,
&signers, &signers,
@ -518,7 +518,7 @@ mod test {
}; };
let min_lamports = rent.minimum_balance(NonceState::size()); let min_lamports = rent.minimum_balance(NonceState::size());
with_test_keyed_account(min_lamports + 42, true, |nonce_keyed| { with_test_keyed_account(min_lamports + 42, true, |nonce_keyed| {
with_test_keyed_account(42, false, |mut to_keyed| { with_test_keyed_account(42, false, |to_keyed| {
let mut signers = HashSet::new(); let mut signers = HashSet::new();
signers.insert(nonce_keyed.signer_key().unwrap().clone()); signers.insert(nonce_keyed.signer_key().unwrap().clone());
let recent_blockhashes = create_test_recent_blockhashes(0); let recent_blockhashes = create_test_recent_blockhashes(0);
@ -529,7 +529,7 @@ mod test {
nonce_keyed nonce_keyed
.withdraw_nonce_account( .withdraw_nonce_account(
withdraw_lamports, withdraw_lamports,
&mut to_keyed, &to_keyed,
&recent_blockhashes, &recent_blockhashes,
&rent, &rent,
&signers, &signers,
@ -546,7 +546,7 @@ mod test {
nonce_keyed nonce_keyed
.withdraw_nonce_account( .withdraw_nonce_account(
withdraw_lamports, withdraw_lamports,
&mut to_keyed, &to_keyed,
&recent_blockhashes, &recent_blockhashes,
&rent, &rent,
&signers, &signers,
@ -579,7 +579,7 @@ mod test {
let state: NonceState = nonce_keyed.state().unwrap(); let state: NonceState = nonce_keyed.state().unwrap();
let stored = recent_blockhashes[0]; let stored = recent_blockhashes[0];
assert_eq!(state, NonceState::Initialized(meta, stored)); assert_eq!(state, NonceState::Initialized(meta, stored));
with_test_keyed_account(42, false, |mut to_keyed| { with_test_keyed_account(42, false, |to_keyed| {
let withdraw_lamports = nonce_keyed.account.borrow().lamports - min_lamports; let withdraw_lamports = nonce_keyed.account.borrow().lamports - min_lamports;
let nonce_expect_lamports = let nonce_expect_lamports =
nonce_keyed.account.borrow().lamports - withdraw_lamports; nonce_keyed.account.borrow().lamports - withdraw_lamports;
@ -587,7 +587,7 @@ mod test {
nonce_keyed nonce_keyed
.withdraw_nonce_account( .withdraw_nonce_account(
withdraw_lamports, withdraw_lamports,
&mut to_keyed, &to_keyed,
&recent_blockhashes, &recent_blockhashes,
&rent, &rent,
&signers, &signers,
@ -606,7 +606,7 @@ mod test {
nonce_keyed nonce_keyed
.withdraw_nonce_account( .withdraw_nonce_account(
withdraw_lamports, withdraw_lamports,
&mut to_keyed, &to_keyed,
&recent_blockhashes, &recent_blockhashes,
&rent, &rent,
&signers, &signers,
@ -631,13 +631,13 @@ mod test {
nonce_keyed nonce_keyed
.initialize_nonce_account(&authorized, &recent_blockhashes, &rent) .initialize_nonce_account(&authorized, &recent_blockhashes, &rent)
.unwrap(); .unwrap();
with_test_keyed_account(42, false, |mut to_keyed| { with_test_keyed_account(42, false, |to_keyed| {
let mut signers = HashSet::new(); let mut signers = HashSet::new();
signers.insert(nonce_keyed.signer_key().unwrap().clone()); signers.insert(nonce_keyed.signer_key().unwrap().clone());
let withdraw_lamports = nonce_keyed.account.borrow().lamports; let withdraw_lamports = nonce_keyed.account.borrow().lamports;
let result = nonce_keyed.withdraw_nonce_account( let result = nonce_keyed.withdraw_nonce_account(
withdraw_lamports, withdraw_lamports,
&mut to_keyed, &to_keyed,
&recent_blockhashes, &recent_blockhashes,
&rent, &rent,
&signers, &signers,
@ -660,14 +660,14 @@ mod test {
nonce_keyed nonce_keyed
.initialize_nonce_account(&authorized, &recent_blockhashes, &rent) .initialize_nonce_account(&authorized, &recent_blockhashes, &rent)
.unwrap(); .unwrap();
with_test_keyed_account(42, false, |mut to_keyed| { with_test_keyed_account(42, false, |to_keyed| {
let recent_blockhashes = create_test_recent_blockhashes(63); let recent_blockhashes = create_test_recent_blockhashes(63);
let mut signers = HashSet::new(); let mut signers = HashSet::new();
signers.insert(nonce_keyed.signer_key().unwrap().clone()); signers.insert(nonce_keyed.signer_key().unwrap().clone());
let withdraw_lamports = nonce_keyed.account.borrow().lamports + 1; let withdraw_lamports = nonce_keyed.account.borrow().lamports + 1;
let result = nonce_keyed.withdraw_nonce_account( let result = nonce_keyed.withdraw_nonce_account(
withdraw_lamports, withdraw_lamports,
&mut to_keyed, &to_keyed,
&recent_blockhashes, &recent_blockhashes,
&rent, &rent,
&signers, &signers,
@ -690,14 +690,14 @@ mod test {
nonce_keyed nonce_keyed
.initialize_nonce_account(&authorized, &recent_blockhashes, &rent) .initialize_nonce_account(&authorized, &recent_blockhashes, &rent)
.unwrap(); .unwrap();
with_test_keyed_account(42, false, |mut to_keyed| { with_test_keyed_account(42, false, |to_keyed| {
let recent_blockhashes = create_test_recent_blockhashes(63); let recent_blockhashes = create_test_recent_blockhashes(63);
let mut signers = HashSet::new(); let mut signers = HashSet::new();
signers.insert(nonce_keyed.signer_key().unwrap().clone()); signers.insert(nonce_keyed.signer_key().unwrap().clone());
let withdraw_lamports = nonce_keyed.account.borrow().lamports - min_lamports + 1; let withdraw_lamports = nonce_keyed.account.borrow().lamports - min_lamports + 1;
let result = nonce_keyed.withdraw_nonce_account( let result = nonce_keyed.withdraw_nonce_account(
withdraw_lamports, withdraw_lamports,
&mut to_keyed, &to_keyed,
&recent_blockhashes, &recent_blockhashes,
&rent, &rent,
&signers, &signers,