Merge InstructionError and ProgramError

From the user's perspective, it's just an instruction error.
For program-specific errors, we still have
InstructionError::CustomError.
This commit is contained in:
Greg Fitzgerald 2019-03-18 10:05:03 -06:00
parent 607b368fe3
commit 8d032aba9d
21 changed files with 170 additions and 187 deletions

View File

@ -697,7 +697,7 @@ mod tests {
let (_, entries) = entry_receiver.recv().unwrap();
assert_eq!(entries[0].0.transactions.len(), transactions.len());
// ProgramErrors should still be recorded
// InstructionErrors should still be recorded
results[0] = Err(TransactionError::InstructionError(
1,
InstructionError::new_result_with_negative_lamports(),

View File

@ -459,7 +459,7 @@ mod tests {
entries.push(entry);
// Add a second Transaction that will produce a
// ProgramError<0, ResultWithNegativeLamports> error when processed
// InstructionError<0, ResultWithNegativeLamports> error when processed
let keypair2 = Keypair::new();
let tx = SystemTransaction::new_account(&keypair, &keypair2.pubkey(), 42, blockhash, 0);
let entry = Entry::new(&last_entry_hash, 1, vec![tx]);

View File

@ -6,9 +6,9 @@ use log::*;
use solana_rbpf::{EbpfVmRaw, MemoryRegion};
use solana_sdk::account::KeyedAccount;
use solana_sdk::loader_instruction::LoaderInstruction;
use solana_sdk::native_program::ProgramError;
use solana_sdk::pubkey::Pubkey;
use solana_sdk::solana_entrypoint;
use solana_sdk::transaction::InstructionError;
use std::ffi::CStr;
use std::io::prelude::*;
use std::io::{Error, ErrorKind};
@ -185,7 +185,7 @@ fn entrypoint(
keyed_accounts: &mut [KeyedAccount],
tx_data: &[u8],
tick_height: u64,
) -> Result<(), ProgramError> {
) -> Result<(), InstructionError> {
solana_logger::setup();
if keyed_accounts[0].account.executable {
@ -197,7 +197,7 @@ fn entrypoint(
Ok(vm) => vm,
Err(e) => {
warn!("Failed to create BPF VM: {}", e);
return Err(ProgramError::GenericError);
return Err(InstructionError::GenericError);
}
};
let mut v = serialize_parameters(program_id, params, &tx_data, tick_height);
@ -205,12 +205,12 @@ fn entrypoint(
Ok(status) => {
if 0 == status {
warn!("BPF program failed: {}", status);
return Err(ProgramError::GenericError);
return Err(InstructionError::GenericError);
}
}
Err(e) => {
warn!("BPF VM failed to run program: {}", e);
return Err(ProgramError::GenericError);
return Err(InstructionError::GenericError);
}
}
deserialize_parameters(params, &v);
@ -221,7 +221,7 @@ fn entrypoint(
} else if let Ok(instruction) = bincode::deserialize(tx_data) {
if keyed_accounts[0].signer_key().is_none() {
warn!("key[0] did not sign the transaction");
return Err(ProgramError::GenericError);
return Err(InstructionError::GenericError);
}
match instruction {
LoaderInstruction::Write { offset, bytes } => {
@ -234,7 +234,7 @@ fn entrypoint(
keyed_accounts[0].account.data.len(),
offset + len
);
return Err(ProgramError::GenericError);
return Err(InstructionError::GenericError);
}
keyed_accounts[0].account.data[offset..offset + len].copy_from_slice(&bytes);
}
@ -248,7 +248,7 @@ fn entrypoint(
}
} else {
warn!("Invalid program transaction: {:?}", tx_data);
return Err(ProgramError::GenericError);
return Err(InstructionError::GenericError);
}
Ok(())
}

View File

@ -6,8 +6,8 @@ use solana_budget_api::budget_instruction::BudgetInstruction;
use solana_budget_api::budget_state::{BudgetError, BudgetState};
use solana_budget_api::payment_plan::Witness;
use solana_sdk::account::KeyedAccount;
use solana_sdk::native_program::ProgramError;
use solana_sdk::pubkey::Pubkey;
use solana_sdk::transaction::InstructionError;
/// Process a Witness Signature. Any payment plans waiting on this signature
/// will progress one step.
@ -75,10 +75,10 @@ pub fn process_instruction(
keyed_accounts: &mut [KeyedAccount],
data: &[u8],
_tick_height: u64,
) -> Result<(), ProgramError> {
) -> Result<(), InstructionError> {
let instruction = deserialize(data).map_err(|err| {
info!("Invalid transaction data: {:?} {:?}", data, err);
ProgramError::InvalidInstructionData
InstructionError::InvalidInstructionData
})?;
trace!("process_instruction: {:?}", instruction);
@ -94,7 +94,7 @@ pub fn process_instruction(
let existing = BudgetState::deserialize(&keyed_accounts[0].account.data).ok();
if Some(true) == existing.map(|x| x.initialized) {
trace!("contract already exists");
return Err(ProgramError::AccountAlreadyInitialized);
return Err(InstructionError::AccountAlreadyInitialized);
}
let mut budget_state = BudgetState::default();
budget_state.pending_budget = Some(expr);
@ -108,14 +108,14 @@ pub fn process_instruction(
}
if !budget_state.initialized {
trace!("contract is uninitialized");
return Err(ProgramError::UninitializedAccount);
return Err(InstructionError::UninitializedAccount);
}
if keyed_accounts[0].signer_key().is_none() {
return Err(ProgramError::MissingRequiredSignature);
return Err(InstructionError::MissingRequiredSignature);
}
trace!("apply timestamp");
apply_timestamp(&mut budget_state, keyed_accounts, dt)
.map_err(|e| ProgramError::CustomError(serialize(&e).unwrap()))?;
.map_err(|e| InstructionError::CustomError(serialize(&e).unwrap()))?;
trace!("apply timestamp committed");
budget_state.serialize(&mut keyed_accounts[1].account.data)
}
@ -126,14 +126,14 @@ pub fn process_instruction(
}
if !budget_state.initialized {
trace!("contract is uninitialized");
return Err(ProgramError::UninitializedAccount);
return Err(InstructionError::UninitializedAccount);
}
if keyed_accounts[0].signer_key().is_none() {
return Err(ProgramError::MissingRequiredSignature);
return Err(InstructionError::MissingRequiredSignature);
}
trace!("apply signature");
apply_signature(&mut budget_state, keyed_accounts)
.map_err(|e| ProgramError::CustomError(serialize(&e).unwrap()))?;
.map_err(|e| InstructionError::CustomError(serialize(&e).unwrap()))?;
trace!("apply signature committed");
budget_state.serialize(&mut keyed_accounts[1].account.data)
}
@ -207,7 +207,7 @@ mod test {
mallory_client.process_transaction(transaction),
Err(TransactionError::InstructionError(
0,
InstructionError::ProgramError(ProgramError::MissingRequiredSignature)
InstructionError::MissingRequiredSignature
))
);
}
@ -254,7 +254,7 @@ mod test {
mallory_client.process_transaction(transaction),
Err(TransactionError::InstructionError(
0,
InstructionError::ProgramError(ProgramError::MissingRequiredSignature)
InstructionError::MissingRequiredSignature
))
);
}
@ -296,9 +296,7 @@ mod test {
alice_client.process_instruction(instruction).unwrap_err(),
TransactionError::InstructionError(
0,
InstructionError::ProgramError(ProgramError::CustomError(
serialize(&BudgetError::DestinationMissing).unwrap()
))
InstructionError::CustomError(serialize(&BudgetError::DestinationMissing).unwrap())
)
);
assert_eq!(bank.get_balance(&alice_pubkey), 1);

View File

@ -3,9 +3,9 @@ mod budget_processor;
use crate::budget_processor::process_instruction;
use log::*;
use solana_sdk::account::KeyedAccount;
use solana_sdk::native_program::ProgramError;
use solana_sdk::pubkey::Pubkey;
use solana_sdk::solana_entrypoint;
use solana_sdk::transaction::InstructionError;
solana_entrypoint!(entrypoint);
fn entrypoint(
@ -13,7 +13,7 @@ fn entrypoint(
keyed_accounts: &mut [KeyedAccount],
data: &[u8],
tick_height: u64,
) -> Result<(), ProgramError> {
) -> Result<(), InstructionError> {
solana_logger::setup();
trace!("process_instruction: {:?}", data);

View File

@ -2,7 +2,7 @@
use crate::budget_expr::BudgetExpr;
use bincode::{self, deserialize, serialize_into};
use serde_derive::{Deserialize, Serialize};
use solana_sdk::native_program::ProgramError;
use solana_sdk::transaction::InstructionError;
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub enum BudgetError {
@ -27,12 +27,12 @@ impl BudgetState {
self.pending_budget.is_some()
}
pub fn serialize(&self, output: &mut [u8]) -> Result<(), ProgramError> {
serialize_into(output, self).map_err(|_| ProgramError::AccountDataTooSmall)
pub fn serialize(&self, output: &mut [u8]) -> Result<(), InstructionError> {
serialize_into(output, self).map_err(|_| InstructionError::AccountDataTooSmall)
}
pub fn deserialize(input: &[u8]) -> Result<Self, ProgramError> {
deserialize(input).map_err(|_| ProgramError::InvalidAccountData)
pub fn deserialize(input: &[u8]) -> Result<Self, InstructionError> {
deserialize(input).map_err(|_| InstructionError::InvalidAccountData)
}
}
@ -57,7 +57,7 @@ mod test {
let b = BudgetState::default();
assert_eq!(
b.serialize(&mut a.data),
Err(ProgramError::AccountDataTooSmall)
Err(InstructionError::AccountDataTooSmall)
);
}
}

View File

@ -3,29 +3,29 @@
use log::*;
use solana_config_api::check_id;
use solana_sdk::account::KeyedAccount;
use solana_sdk::native_program::ProgramError;
use solana_sdk::pubkey::Pubkey;
use solana_sdk::solana_entrypoint;
use solana_sdk::transaction::InstructionError;
fn process_instruction(
_program_id: &Pubkey,
keyed_accounts: &mut [KeyedAccount],
data: &[u8],
_tick_height: u64,
) -> Result<(), ProgramError> {
) -> Result<(), InstructionError> {
if !check_id(&keyed_accounts[0].account.owner) {
error!("account[0] is not assigned to the config program");
Err(ProgramError::IncorrectProgramId)?;
Err(InstructionError::IncorrectProgramId)?;
}
if keyed_accounts[0].signer_key().is_none() {
error!("account[0] should sign the transaction");
Err(ProgramError::MissingRequiredSignature)?;
Err(InstructionError::MissingRequiredSignature)?;
}
if keyed_accounts[0].account.data.len() < data.len() {
error!("instruction data too large");
Err(ProgramError::InvalidInstructionData)?;
Err(InstructionError::InvalidInstructionData)?;
}
keyed_accounts[0].account.data[0..data.len()].copy_from_slice(data);
@ -38,7 +38,7 @@ fn entrypoint(
keyed_accounts: &mut [KeyedAccount],
data: &[u8],
tick_height: u64,
) -> Result<(), ProgramError> {
) -> Result<(), InstructionError> {
solana_logger::setup();
trace!("process_instruction: {:?}", data);
@ -163,7 +163,7 @@ mod tests {
config_client.process_instruction(instruction),
Err(TransactionError::InstructionError(
0,
InstructionError::ProgramError(ProgramError::IncorrectProgramId)
InstructionError::IncorrectProgramId
))
);
}

View File

@ -1,7 +1,7 @@
use solana_sdk::account::KeyedAccount;
use solana_sdk::native_program::ProgramError;
use solana_sdk::pubkey::Pubkey;
use solana_sdk::solana_entrypoint;
use solana_sdk::transaction::InstructionError;
solana_entrypoint!(entrypoint);
fn entrypoint(
@ -9,6 +9,6 @@ fn entrypoint(
_keyed_accounts: &mut [KeyedAccount],
_data: &[u8],
_tick_height: u64,
) -> Result<(), ProgramError> {
Err(ProgramError::GenericError)
) -> Result<(), InstructionError> {
Err(InstructionError::GenericError)
}

View File

@ -2,7 +2,6 @@ use solana_runtime::bank::Bank;
use solana_runtime::loader_utils::load_program;
use solana_sdk::genesis_block::GenesisBlock;
use solana_sdk::native_loader;
use solana_sdk::native_program::ProgramError;
use solana_sdk::transaction::{InstructionError, Transaction, TransactionError};
#[test]
@ -26,7 +25,7 @@ fn test_program_native_failure() {
bank.process_transaction(&tx),
Err(TransactionError::InstructionError(
0,
InstructionError::ProgramError(ProgramError::GenericError)
InstructionError::GenericError
))
);
}

View File

@ -1,8 +1,8 @@
use log::*;
use solana_sdk::account::KeyedAccount;
use solana_sdk::native_program::ProgramError;
use solana_sdk::pubkey::Pubkey;
use solana_sdk::solana_entrypoint;
use solana_sdk::transaction::InstructionError;
solana_entrypoint!(entrypoint);
fn entrypoint(
@ -10,7 +10,7 @@ fn entrypoint(
keyed_accounts: &mut [KeyedAccount],
data: &[u8],
tick_height: u64,
) -> Result<(), ProgramError> {
) -> Result<(), InstructionError> {
solana_logger::setup();
info!("noop: program_id: {:?}", program_id);
info!("noop: keyed_accounts: {:#?}", keyed_accounts);

View File

@ -5,9 +5,9 @@ use bincode::deserialize;
use log::*;
use solana_rewards_api::rewards_instruction::RewardsInstruction;
use solana_sdk::account::KeyedAccount;
use solana_sdk::native_program::ProgramError;
use solana_sdk::pubkey::Pubkey;
use solana_sdk::solana_entrypoint;
use solana_sdk::transaction::InstructionError;
use solana_vote_api::vote_state::VoteState;
const INTEREST_PER_CREDIT_DIVISOR: u64 = 100; // Staker earns 1/INTEREST_PER_CREDIT_DIVISOR of interest per credit
@ -20,24 +20,24 @@ const MINIMUM_CREDITS_PER_REDEMPTION: u64 = 1; // Raise this to either minimize
// TODO: Migrate to reward mechanism described by the book:
// https://github.com/solana-labs/solana/blob/master/book/src/ed_vce_state_validation_protocol_based_rewards.md
// https://github.com/solana-labs/solana/blob/master/book/src/staking-rewards.md
fn calc_vote_reward(credits: u64, stake: u64) -> Result<u64, ProgramError> {
fn calc_vote_reward(credits: u64, stake: u64) -> Result<u64, InstructionError> {
if credits < MINIMUM_CREDITS_PER_REDEMPTION {
error!("Credit redemption too early");
Err(ProgramError::GenericError)?;
Err(InstructionError::GenericError)?;
}
Ok(credits * (stake / INTEREST_PER_CREDIT_DIVISOR))
}
fn redeem_vote_credits(keyed_accounts: &mut [KeyedAccount]) -> Result<(), ProgramError> {
fn redeem_vote_credits(keyed_accounts: &mut [KeyedAccount]) -> Result<(), InstructionError> {
// The owner of the vote account needs to authorize having its credits cleared.
if keyed_accounts[0].signer_key().is_none() {
error!("account[0] is unsigned");
Err(ProgramError::InvalidArgument)?;
Err(InstructionError::InvalidArgument)?;
}
if !solana_vote_api::check_id(&keyed_accounts[0].account.owner) {
error!("account[0] is not assigned to the VOTE_PROGRAM");
Err(ProgramError::InvalidArgument)?;
Err(InstructionError::InvalidArgument)?;
}
// TODO: Verify the next instruction in the transaction being processed is
@ -51,7 +51,7 @@ fn redeem_vote_credits(keyed_accounts: &mut [KeyedAccount]) -> Result<(), Progra
let stake = keyed_accounts[0].account.lamports;
if stake == 0 {
error!("staking account has no stake");
Err(ProgramError::InvalidArgument)?;
Err(InstructionError::InvalidArgument)?;
}
let lamports = calc_vote_reward(vote_state.credits(), stake)?;
@ -69,13 +69,13 @@ fn entrypoint(
keyed_accounts: &mut [KeyedAccount],
data: &[u8],
_tick_height: u64,
) -> Result<(), ProgramError> {
) -> Result<(), InstructionError> {
solana_logger::setup();
trace!("process_instruction: {:?}", data);
trace!("keyed_accounts: {:?}", keyed_accounts);
match deserialize(data).map_err(|_| ProgramError::InvalidInstructionData)? {
match deserialize(data).map_err(|_| InstructionError::InvalidInstructionData)? {
RewardsInstruction::RedeemVoteCredits => redeem_vote_credits(keyed_accounts),
}
}
@ -100,7 +100,7 @@ mod tests {
rewards_account: &mut Account,
vote_id: &Pubkey,
vote_account: &mut Account,
) -> Result<(), ProgramError> {
) -> Result<(), InstructionError> {
let mut keyed_accounts = [
KeyedAccount::new(vote_id, true, vote_account),
KeyedAccount::new(rewards_id, false, rewards_account),

View File

@ -6,9 +6,9 @@ use log::*;
extern crate solana_sdk;
use solana_sdk::account::KeyedAccount;
use solana_sdk::native_program::ProgramError;
use solana_sdk::pubkey::Pubkey;
use solana_sdk::solana_entrypoint;
use solana_sdk::transaction::InstructionError;
use solana_storage_api::*;
pub const TOTAL_VALIDATOR_REWARDS: u64 = 1000;
@ -30,19 +30,19 @@ fn entrypoint(
keyed_accounts: &mut [KeyedAccount],
data: &[u8],
_tick_height: u64,
) -> Result<(), ProgramError> {
) -> Result<(), InstructionError> {
solana_logger::setup();
if keyed_accounts.len() != 1 {
// keyed_accounts[1] should be the main storage key
// to access its data
Err(ProgramError::InvalidArgument)?;
Err(InstructionError::InvalidArgument)?;
}
// accounts_keys[0] must be signed
if keyed_accounts[0].signer_key().is_none() {
info!("account[0] is unsigned");
Err(ProgramError::GenericError)?;
Err(InstructionError::GenericError)?;
}
if let Ok(syscall) = bincode::deserialize(data) {
@ -68,7 +68,7 @@ fn entrypoint(
let current_segment_index =
get_segment_from_entry(storage_account_state.entry_height);
if segment_index >= current_segment_index {
return Err(ProgramError::InvalidArgument);
return Err(InstructionError::InvalidArgument);
}
debug!(
@ -91,7 +91,7 @@ fn entrypoint(
segments, original_segments
);
if segments <= original_segments {
return Err(ProgramError::InvalidArgument);
return Err(InstructionError::InvalidArgument);
}
storage_account_state.entry_height = entry_height;
@ -117,18 +117,18 @@ fn entrypoint(
proof_mask,
} => {
if entry_height >= storage_account_state.entry_height {
return Err(ProgramError::InvalidArgument);
return Err(InstructionError::InvalidArgument);
}
let segment_index = get_segment_from_entry(entry_height);
if storage_account_state.previous_proofs[segment_index].len() != proof_mask.len() {
return Err(ProgramError::InvalidArgument);
return Err(InstructionError::InvalidArgument);
}
// TODO: Check that each proof mask matches the signature
/*for (i, entry) in proof_mask.iter().enumerate() {
if storage_account_state.previous_proofs[segment_index][i] != signature.as_ref[0] {
return Err(ProgramError::InvalidArgument);
return Err(InstructionError::InvalidArgument);
}
}*/
@ -164,13 +164,13 @@ fn entrypoint(
)
.is_err()
{
return Err(ProgramError::AccountDataTooSmall);
return Err(InstructionError::AccountDataTooSmall);
}
Ok(())
} else {
info!("Invalid instruction data: {:?}", data);
Err(ProgramError::InvalidInstructionData)
Err(InstructionError::InvalidInstructionData)
}
}
@ -186,7 +186,7 @@ mod test {
fn test_transaction(
tx: &Transaction,
program_accounts: &mut [Account],
) -> Result<(), ProgramError> {
) -> Result<(), InstructionError> {
assert_eq!(tx.instructions.len(), 1);
let CompiledInstruction {
ref accounts,
@ -237,7 +237,7 @@ mod test {
assert_eq!(
entrypoint(&id(), &mut keyed_accounts, &tx.instructions[0].data, 42),
Err(ProgramError::AccountDataTooSmall)
Err(InstructionError::AccountDataTooSmall)
);
}

View File

@ -1,9 +1,9 @@
use bincode::serialize;
use log::*;
use solana_sdk::account::KeyedAccount;
use solana_sdk::native_program::ProgramError;
use solana_sdk::pubkey::Pubkey;
use solana_sdk::solana_entrypoint;
use solana_sdk::transaction::InstructionError;
mod token_program;
@ -13,11 +13,11 @@ fn entrypoint(
info: &mut [KeyedAccount],
input: &[u8],
_tick_height: u64,
) -> Result<(), ProgramError> {
) -> Result<(), InstructionError> {
solana_logger::setup();
token_program::TokenProgram::process(program_id, info, input).map_err(|e| {
error!("error: {:?}", e);
ProgramError::CustomError(serialize(&e).unwrap())
InstructionError::CustomError(serialize(&e).unwrap())
})
}

View File

@ -4,9 +4,9 @@
use bincode::deserialize;
use log::*;
use solana_sdk::account::KeyedAccount;
use solana_sdk::native_program::ProgramError;
use solana_sdk::pubkey::Pubkey;
use solana_sdk::solana_entrypoint;
use solana_sdk::transaction::InstructionError;
use solana_vote_api::vote_instruction::VoteInstruction;
use solana_vote_api::vote_state;
@ -16,13 +16,13 @@ fn entrypoint(
keyed_accounts: &mut [KeyedAccount],
data: &[u8],
_tick_height: u64,
) -> Result<(), ProgramError> {
) -> Result<(), InstructionError> {
solana_logger::setup();
trace!("process_instruction: {:?}", data);
trace!("keyed_accounts: {:?}", keyed_accounts);
match deserialize(data).map_err(|_| ProgramError::InvalidInstructionData)? {
match deserialize(data).map_err(|_| InstructionError::InvalidInstructionData)? {
VoteInstruction::InitializeAccount => vote_state::initialize_account(keyed_accounts),
VoteInstruction::DelegateStake(delegate_id) => {
vote_state::delegate_stake(keyed_accounts, &delegate_id)

View File

@ -1,7 +1,6 @@
use solana_runtime::bank::{Bank, Result};
use solana_sdk::genesis_block::GenesisBlock;
use solana_sdk::hash::hash;
use solana_sdk::native_program::ProgramError;
use solana_sdk::pubkey::Pubkey;
use solana_sdk::signature::{Keypair, KeypairUtil};
use solana_sdk::system_instruction::SystemInstruction;
@ -134,7 +133,7 @@ fn test_vote_via_bank_with_no_signature() {
result,
Err(TransactionError::InstructionError(
1,
InstructionError::ProgramError(ProgramError::InvalidArgument)
InstructionError::InvalidArgument
))
);
}

View File

@ -7,8 +7,8 @@ use bincode::{deserialize, serialize_into, serialized_size, ErrorKind};
use log::*;
use serde_derive::{Deserialize, Serialize};
use solana_sdk::account::{Account, KeyedAccount};
use solana_sdk::native_program::ProgramError;
use solana_sdk::pubkey::Pubkey;
use solana_sdk::transaction::InstructionError;
use std::collections::VecDeque;
// Maximum number of votes to keep around
@ -73,14 +73,14 @@ impl VoteState {
serialized_size(&vote_state).unwrap() as usize
}
pub fn deserialize(input: &[u8]) -> Result<Self, ProgramError> {
deserialize(input).map_err(|_| ProgramError::InvalidAccountData)
pub fn deserialize(input: &[u8]) -> Result<Self, InstructionError> {
deserialize(input).map_err(|_| InstructionError::InvalidAccountData)
}
pub fn serialize(&self, output: &mut [u8]) -> Result<(), ProgramError> {
pub fn serialize(&self, output: &mut [u8]) -> Result<(), InstructionError> {
serialize_into(output, self).map_err(|err| match *err {
ErrorKind::SizeLimit => ProgramError::AccountDataTooSmall,
_ => ProgramError::GenericError,
ErrorKind::SizeLimit => InstructionError::AccountDataTooSmall,
_ => InstructionError::GenericError,
})
}
@ -152,15 +152,15 @@ impl VoteState {
pub fn delegate_stake(
keyed_accounts: &mut [KeyedAccount],
node_id: &Pubkey,
) -> Result<(), ProgramError> {
) -> Result<(), InstructionError> {
if !check_id(&keyed_accounts[0].account.owner) {
error!("account[0] is not assigned to the VOTE_PROGRAM");
Err(ProgramError::InvalidArgument)?;
Err(InstructionError::InvalidArgument)?;
}
if keyed_accounts[0].signer_key().is_none() {
error!("account[0] should sign the transaction");
Err(ProgramError::InvalidArgument)?;
Err(InstructionError::InvalidArgument)?;
}
let vote_state = VoteState::deserialize(&keyed_accounts[0].account.data);
@ -169,7 +169,7 @@ pub fn delegate_stake(
vote_state.serialize(&mut keyed_accounts[0].account.data)?;
} else {
error!("account[0] does not valid data");
Err(ProgramError::InvalidAccountData)?;
Err(InstructionError::InvalidAccountData)?;
}
Ok(())
@ -181,15 +181,15 @@ pub fn delegate_stake(
pub fn authorize_voter(
keyed_accounts: &mut [KeyedAccount],
voter_id: &Pubkey,
) -> Result<(), ProgramError> {
) -> Result<(), InstructionError> {
if !check_id(&keyed_accounts[0].account.owner) {
error!("account[0] is not assigned to the VOTE_PROGRAM");
Err(ProgramError::InvalidArgument)?;
Err(InstructionError::InvalidArgument)?;
}
if keyed_accounts[0].signer_key().is_none() {
error!("account[0] should sign the transaction");
Err(ProgramError::InvalidArgument)?;
Err(InstructionError::InvalidArgument)?;
}
let vote_state = VoteState::deserialize(&keyed_accounts[0].account.data);
@ -198,7 +198,7 @@ pub fn authorize_voter(
vote_state.serialize(&mut keyed_accounts[0].account.data)?;
} else {
error!("account[0] does not valid data");
Err(ProgramError::InvalidAccountData)?;
Err(InstructionError::InvalidAccountData)?;
}
Ok(())
@ -207,10 +207,10 @@ pub fn authorize_voter(
/// Initialize the vote_state for a vote account
/// 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
pub fn initialize_account(keyed_accounts: &mut [KeyedAccount]) -> Result<(), ProgramError> {
pub fn initialize_account(keyed_accounts: &mut [KeyedAccount]) -> Result<(), InstructionError> {
if !check_id(&keyed_accounts[0].account.owner) {
error!("account[0] is not assigned to the VOTE_PROGRAM");
Err(ProgramError::InvalidArgument)?;
Err(InstructionError::InvalidArgument)?;
}
let staker_id = keyed_accounts[0].unsigned_key();
@ -221,20 +221,23 @@ pub fn initialize_account(keyed_accounts: &mut [KeyedAccount]) -> Result<(), Pro
vote_state.serialize(&mut keyed_accounts[0].account.data)?;
} else {
error!("account[0] data already initialized");
Err(ProgramError::InvalidAccountData)?;
Err(InstructionError::InvalidAccountData)?;
}
} else {
error!("account[0] does not have valid data");
Err(ProgramError::InvalidAccountData)?;
Err(InstructionError::InvalidAccountData)?;
}
Ok(())
}
pub fn process_vote(keyed_accounts: &mut [KeyedAccount], vote: Vote) -> Result<(), ProgramError> {
pub fn process_vote(
keyed_accounts: &mut [KeyedAccount],
vote: Vote,
) -> Result<(), InstructionError> {
if !check_id(&keyed_accounts[0].account.owner) {
error!("account[0] is not assigned to the VOTE_PROGRAM");
Err(ProgramError::InvalidArgument)?;
Err(InstructionError::InvalidArgument)?;
}
let mut vote_state = VoteState::deserialize(&keyed_accounts[0].account.data)?;
@ -248,11 +251,11 @@ pub fn process_vote(keyed_accounts: &mut [KeyedAccount], vote: Vote) -> Result<(
if keyed_accounts.get(signer_index).is_none() {
error!("account[{}] not provided", signer_index);
Err(ProgramError::InvalidArgument)?;
Err(InstructionError::InvalidArgument)?;
}
if keyed_accounts[signer_index].signer_key().is_none() {
error!("account[{}] should sign the transaction", signer_index);
Err(ProgramError::InvalidArgument)?;
Err(InstructionError::InvalidArgument)?;
}
vote_state.process_vote(vote);
@ -260,10 +263,10 @@ pub fn process_vote(keyed_accounts: &mut [KeyedAccount], vote: Vote) -> Result<(
Ok(())
}
pub fn clear_credits(keyed_accounts: &mut [KeyedAccount]) -> Result<(), ProgramError> {
pub fn clear_credits(keyed_accounts: &mut [KeyedAccount]) -> Result<(), InstructionError> {
if !check_id(&keyed_accounts[0].account.owner) {
error!("account[0] is not assigned to the VOTE_PROGRAM");
Err(ProgramError::InvalidArgument)?;
Err(InstructionError::InvalidArgument)?;
}
let mut vote_state = VoteState::deserialize(&keyed_accounts[0].account.data)?;
@ -280,7 +283,7 @@ pub fn create_vote_account(lamports: u64) -> Account {
pub fn initialize_and_deserialize(
vote_id: &Pubkey,
vote_account: &mut Account,
) -> Result<VoteState, ProgramError> {
) -> Result<VoteState, InstructionError> {
let mut keyed_accounts = [KeyedAccount::new(vote_id, false, vote_account)];
initialize_account(&mut keyed_accounts)?;
let vote_state = VoteState::deserialize(&vote_account.data).unwrap();
@ -291,7 +294,7 @@ pub fn vote_and_deserialize(
vote_id: &Pubkey,
vote_account: &mut Account,
vote: Vote,
) -> Result<VoteState, ProgramError> {
) -> Result<VoteState, InstructionError> {
let mut keyed_accounts = [KeyedAccount::new(vote_id, true, vote_account)];
process_vote(&mut keyed_accounts, vote)?;
let vote_state = VoteState::deserialize(&vote_account.data).unwrap();
@ -324,7 +327,7 @@ mod tests {
// reinit should fail
let res = initialize_account(&mut keyed_accounts);
assert_eq!(res, Err(ProgramError::InvalidAccountData));
assert_eq!(res, Err(InstructionError::InvalidAccountData));
}
#[test]
@ -369,7 +372,7 @@ mod tests {
let vote = Vote::new(1);
let mut keyed_accounts = [KeyedAccount::new(&vote_id, false, &mut vote_account)];
let res = process_vote(&mut keyed_accounts, vote);
assert_eq!(res, Err(ProgramError::InvalidArgument));
assert_eq!(res, Err(InstructionError::InvalidArgument));
}
#[test]
@ -379,7 +382,7 @@ mod tests {
let vote = Vote::new(1);
let res = vote_and_deserialize(&vote_id, &mut vote_account, vote.clone());
assert_eq!(res, Err(ProgramError::InvalidArgument));
assert_eq!(res, Err(InstructionError::InvalidArgument));
}
#[test]

View File

@ -7,8 +7,9 @@ use libloading::os::windows::*;
use log::*;
use solana_sdk::account::KeyedAccount;
use solana_sdk::loader_instruction::LoaderInstruction;
use solana_sdk::native_program::{self, ProgramError};
use solana_sdk::native_program;
use solana_sdk::pubkey::Pubkey;
use solana_sdk::transaction::InstructionError;
use std::env;
use std::path::PathBuf;
use std::str;
@ -51,7 +52,7 @@ pub fn entrypoint(
keyed_accounts: &mut [KeyedAccount],
ix_data: &[u8],
tick_height: u64,
) -> Result<(), ProgramError> {
) -> Result<(), InstructionError> {
if keyed_accounts[0].account.executable {
// dispatch it
let (names, params) = keyed_accounts.split_at_mut(1);
@ -60,7 +61,7 @@ pub fn entrypoint(
Ok(v) => v,
Err(e) => {
warn!("Invalid UTF-8 sequence: {}", e);
return Err(ProgramError::GenericError);
return Err(InstructionError::GenericError);
}
};
trace!("Call native {:?}", name);
@ -77,20 +78,20 @@ pub fn entrypoint(
e,
native_program::ENTRYPOINT
);
return Err(ProgramError::GenericError);
return Err(InstructionError::GenericError);
}
};
return entrypoint(program_id, params, ix_data, tick_height);
},
Err(e) => {
warn!("Unable to load: {:?}", e);
return Err(ProgramError::GenericError);
return Err(InstructionError::GenericError);
}
}
} else if let Ok(instruction) = deserialize(ix_data) {
if keyed_accounts[0].signer_key().is_none() {
warn!("key[0] did not sign the transaction");
return Err(ProgramError::GenericError);
return Err(InstructionError::GenericError);
}
match instruction {
LoaderInstruction::Write { offset, bytes } => {
@ -102,7 +103,7 @@ pub fn entrypoint(
keyed_accounts[0].account.data.len(),
offset + bytes.len()
);
return Err(ProgramError::GenericError);
return Err(InstructionError::GenericError);
}
// native loader takes a name and we assume it all comes in at once
keyed_accounts[0].account.data = bytes;
@ -118,7 +119,7 @@ pub fn entrypoint(
}
} else {
warn!("Invalid data in instruction: {:?}", ix_data);
return Err(ProgramError::GenericError);
return Err(InstructionError::GenericError);
}
Ok(())
}

View File

@ -1,6 +1,5 @@
use crate::native_loader;
use solana_sdk::account::{create_keyed_accounts, Account, KeyedAccount};
use solana_sdk::native_program::ProgramError;
use solana_sdk::pubkey::Pubkey;
use solana_sdk::system_program;
use solana_sdk::transaction::{InstructionError, Transaction, TransactionError};
@ -70,18 +69,18 @@ fn verify_instruction(
Ok(())
}
fn verify_error(err: ProgramError) -> ProgramError {
fn verify_error(err: InstructionError) -> InstructionError {
match err {
ProgramError::CustomError(mut error) => {
InstructionError::CustomError(mut error) => {
error.truncate(32);
ProgramError::CustomError(error)
InstructionError::CustomError(error)
}
e => e,
}
}
pub type ProcessInstruction =
fn(&Pubkey, &mut [KeyedAccount], &[u8], u64) -> Result<(), ProgramError>;
fn(&Pubkey, &mut [KeyedAccount], &[u8], u64) -> Result<(), InstructionError>;
pub struct Runtime {
instruction_processors: Vec<(Pubkey, ProcessInstruction)>,
@ -118,7 +117,7 @@ impl Runtime {
executable_accounts: &mut [(Pubkey, Account)],
program_accounts: &mut [&mut Account],
tick_height: u64,
) -> Result<(), ProgramError> {
) -> Result<(), InstructionError> {
let program_id = tx.program_id(instruction_index);
let mut keyed_accounts = create_keyed_accounts(executable_accounts);
@ -182,8 +181,7 @@ impl Runtime {
program_accounts,
tick_height,
)
.map_err(verify_error)
.map_err(InstructionError::ProgramError)?;
.map_err(verify_error)?;
// Verify the instruction
for ((pre_program_id, pre_lamports, pre_data), post_account) in
@ -322,15 +320,15 @@ mod tests {
#[test]
fn test_verify_error() {
let short_error = ProgramError::CustomError(vec![1, 2, 3]);
let short_error = InstructionError::CustomError(vec![1, 2, 3]);
let expected_short_error = short_error.clone(); // short CustomError errors should be untouched
assert_eq!(verify_error(short_error), expected_short_error);
let long_error = ProgramError::CustomError(vec![8; 40]);
let expected_long_error = ProgramError::CustomError(vec![8; 32]); // long CustomError errors should be truncated
let long_error = InstructionError::CustomError(vec![8; 40]);
let expected_long_error = InstructionError::CustomError(vec![8; 32]); // long CustomError errors should be truncated
assert_eq!(verify_error(long_error), expected_long_error);
let other_error = ProgramError::GenericError;
let other_error = InstructionError::GenericError;
let expected_other_error = other_error.clone(); // non-CustomError errors should be untouched
assert_eq!(verify_error(other_error), expected_other_error);
}

View File

@ -1,10 +1,10 @@
use bincode::serialize;
use log::*;
use solana_sdk::account::KeyedAccount;
use solana_sdk::native_program::ProgramError;
use solana_sdk::pubkey::Pubkey;
use solana_sdk::system_instruction::{SystemError, SystemInstruction};
use solana_sdk::system_program;
use solana_sdk::transaction::InstructionError;
const FROM_ACCOUNT_INDEX: usize = 0;
const TO_ACCOUNT_INDEX: usize = 1;
@ -69,7 +69,7 @@ pub fn entrypoint(
keyed_accounts: &mut [KeyedAccount],
data: &[u8],
_tick_height: u64,
) -> Result<(), ProgramError> {
) -> Result<(), InstructionError> {
if let Ok(instruction) = bincode::deserialize(data) {
trace!("process_instruction: {:?}", instruction);
trace!("keyed_accounts: {:?}", keyed_accounts);
@ -77,7 +77,7 @@ pub fn entrypoint(
// All system instructions require that accounts_keys[0] be a signer
if keyed_accounts[FROM_ACCOUNT_INDEX].signer_key().is_none() {
info!("account[from] is unsigned");
Err(ProgramError::MissingRequiredSignature)?;
Err(InstructionError::MissingRequiredSignature)?;
}
match instruction {
@ -88,16 +88,16 @@ pub fn entrypoint(
} => create_system_account(keyed_accounts, lamports, space, &program_id),
SystemInstruction::Assign { program_id } => {
if !system_program::check_id(&keyed_accounts[FROM_ACCOUNT_INDEX].account.owner) {
Err(ProgramError::IncorrectProgramId)?;
Err(InstructionError::IncorrectProgramId)?;
}
assign_account_to_program(keyed_accounts, &program_id)
}
SystemInstruction::Move { lamports } => move_lamports(keyed_accounts, lamports),
}
.map_err(|e| ProgramError::CustomError(serialize(&e).unwrap()))
.map_err(|e| InstructionError::CustomError(serialize(&e).unwrap()))
} else {
info!("Invalid instruction data: {:?}", data);
Err(ProgramError::InvalidInstructionData)
Err(InstructionError::InvalidInstructionData)
}
}
@ -108,7 +108,6 @@ mod tests {
use crate::bank_client::BankClient;
use solana_sdk::account::Account;
use solana_sdk::genesis_block::GenesisBlock;
use solana_sdk::native_program::ProgramError;
use solana_sdk::script::Script;
use solana_sdk::signature::{Keypair, KeypairUtil};
use solana_sdk::system_instruction::SystemInstruction;
@ -245,7 +244,7 @@ mod tests {
};
let data = serialize(&instruction).unwrap();
let result = entrypoint(&system_program::id(), &mut keyed_accounts, &data, 0);
assert_eq!(result, Err(ProgramError::IncorrectProgramId));
assert_eq!(result, Err(InstructionError::IncorrectProgramId));
assert_eq!(from_account.owner, new_program_owner);
}
@ -301,7 +300,7 @@ mod tests {
mallory_client.process_script(malicious_script),
Err(TransactionError::InstructionError(
0,
InstructionError::ProgramError(ProgramError::MissingRequiredSignature)
InstructionError::MissingRequiredSignature
))
);
assert_eq!(bank.get_balance(&alice_pubkey), 50);

View File

@ -1,50 +1,6 @@
use crate::account::KeyedAccount;
use crate::pubkey::Pubkey;
use std;
/// Reasons a program might have rejected an instruction.
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum ProgramError {
/// The program instruction returned an error
GenericError,
/// The arguments provided to a program instruction where invalid
InvalidArgument,
/// An instruction's data contents was invalid
InvalidInstructionData,
/// An account's data contents was invalid
InvalidAccountData,
/// An account's data was too small
AccountDataTooSmall,
/// The account did not have the expected program id
IncorrectProgramId,
/// A signature was required but not found
MissingRequiredSignature,
/// An initialize instruction was sent to an account that has already been initialized.
AccountAlreadyInitialized,
/// An attempt to operate on an account that hasn't been initialized.
UninitializedAccount,
/// CustomError allows on-chain programs to implement program-specific error types and see
/// them returned by the Solana runtime. A CustomError may be any type that is serialized
/// to a Vec of bytes, max length 32 bytes. Any CustomError Vec greater than this length will
/// be truncated by the runtime.
CustomError(Vec<u8>),
}
impl std::fmt::Display for ProgramError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "error")
}
}
impl std::error::Error for ProgramError {}
use crate::transaction::InstructionError;
// All native programs export a symbol named process()
pub const ENTRYPOINT: &str = "process";
@ -55,7 +11,7 @@ pub type Entrypoint = unsafe extern "C" fn(
keyed_accounts: &mut [KeyedAccount],
data: &[u8],
tick_height: u64,
) -> Result<(), ProgramError>;
) -> Result<(), InstructionError>;
// Convenience macro to define the native program entrypoint. Supply a fn to this macro that
// conforms to the `Entrypoint` type signature.
@ -68,7 +24,7 @@ macro_rules! solana_entrypoint(
keyed_accounts: &mut [KeyedAccount],
data: &[u8],
tick_height: u64
) -> Result<(), ProgramError> {
) -> Result<(), InstructionError> {
$entrypoint(program_id, keyed_accounts, data, tick_height)
}
)

View File

@ -1,7 +1,6 @@
//! The `transaction` module provides functionality for creating log transactions.
use crate::hash::{Hash, Hasher};
use crate::native_program::ProgramError;
use crate::packet::PACKET_DATA_SIZE;
use crate::pubkey::Pubkey;
use crate::script::Script;
@ -21,8 +20,33 @@ use std::mem::size_of;
/// Reasons the runtime might have rejected an instruction.
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum InstructionError {
/// Executing the instruction produced an error.
ProgramError(ProgramError),
/// Deprecated! Use CustomError instead!
/// The program instruction returned an error
GenericError,
/// The arguments provided to a program instruction where invalid
InvalidArgument,
/// An instruction's data contents was invalid
InvalidInstructionData,
/// An account's data contents was invalid
InvalidAccountData,
/// An account's data was too small
AccountDataTooSmall,
/// The account did not have the expected program id
IncorrectProgramId,
/// A signature was required but not found
MissingRequiredSignature,
/// An initialize instruction was sent to an account that has already been initialized.
AccountAlreadyInitialized,
/// An attempt to operate on an account that hasn't been initialized.
UninitializedAccount,
/// Program's instruction lamport balance does not equal the balance after the instruction
UnbalancedInstruction,
@ -38,13 +62,19 @@ pub enum InstructionError {
/// An account was referenced more than once in a single instruction
DuplicateAccountIndex,
/// CustomError allows on-chain programs to implement program-specific error types and see
/// them returned by the Solana runtime. A CustomError may be any type that is serialized
/// to a Vec of bytes, max length 32 bytes. Any CustomError Vec greater than this length will
/// be truncated by the runtime.
CustomError(Vec<u8>),
}
impl InstructionError {
pub fn new_result_with_negative_lamports() -> Self {
let serialized_error =
bincode::serialize(&SystemError::ResultWithNegativeLamports).unwrap();
InstructionError::ProgramError(ProgramError::CustomError(serialized_error))
InstructionError::CustomError(serialized_error)
}
}