Native/builtin programs now receive an InvokeContext

This commit is contained in:
Michael Vines
2020-10-28 20:21:50 -07:00
parent ca00197009
commit df8dab9d2b
36 changed files with 402 additions and 251 deletions

View File

@ -12,6 +12,7 @@ use solana_sdk::{
instruction::InstructionError,
keyed_account::KeyedAccount,
message::Message,
process_instruction::InvokeContext,
pubkey::Pubkey,
signature::{Keypair, Signer},
transaction::Transaction,
@ -33,6 +34,7 @@ fn process_instruction(
_program_id: &Pubkey,
_keyed_accounts: &[KeyedAccount],
_data: &[u8],
_invoke_context: &mut dyn InvokeContext,
) -> Result<(), InstructionError> {
Ok(())
}

View File

@ -17,10 +17,6 @@ use crate::{
instruction_recorder::InstructionRecorder,
log_collector::LogCollector,
message_processor::{Executors, MessageProcessor},
process_instruction::{
ErasedProcessInstruction, ErasedProcessInstructionWithContext, Executor,
ProcessInstruction, ProcessInstructionWithContext,
},
rent_collector::RentCollector,
stakes::Stakes,
status_cache::{SlotDelta, StatusCache},
@ -55,6 +51,9 @@ use solana_sdk::{
native_loader,
native_token::sol_to_lamports,
nonce, nonce_account,
process_instruction::{
ErasedProcessInstructionWithContext, Executor, ProcessInstructionWithContext,
},
program_utils::limited_deserialize,
pubkey::Pubkey,
recent_blockhashes_account,
@ -140,7 +139,7 @@ type EpochCount = u64;
#[derive(Copy, Clone)]
pub enum Entrypoint {
Program(ProcessInstruction),
Program(ProcessInstructionWithContext),
Loader(ProcessInstructionWithContext),
}
@ -157,7 +156,7 @@ impl fmt::Debug for Entrypoint {
let entrypoint = match self {
Entrypoint::Program(instruction) => EntrypointForDebug::Program(format!(
"{:p}",
*instruction as ErasedProcessInstruction
*instruction as ErasedProcessInstructionWithContext
)),
Entrypoint::Loader(instruction) => EntrypointForDebug::Loader(format!(
"{:p}",
@ -224,7 +223,7 @@ impl AbiExample for Builtin {
Self {
name: String::default(),
id: Pubkey::default(),
entrypoint: Entrypoint::Program(|_, _, _| Ok(())),
entrypoint: Entrypoint::Program(|_, _, _, _| Ok(())),
}
}
}
@ -3827,9 +3826,13 @@ impl Bank {
&mut self,
name: &str,
program_id: Pubkey,
process_instruction: ProcessInstruction,
process_instruction_with_context: ProcessInstructionWithContext,
) {
self.add_builtin(name, program_id, Entrypoint::Program(process_instruction));
self.add_builtin(
name,
program_id,
Entrypoint::Program(process_instruction_with_context),
);
}
pub fn add_builtin_loader(
@ -4125,7 +4128,6 @@ mod tests {
BOOTSTRAP_VALIDATOR_LAMPORTS,
},
native_loader::NativeLoaderError,
process_instruction::InvokeContext,
status_cache::MAX_CACHE_ENTRIES,
};
use solana_sdk::{
@ -4138,6 +4140,7 @@ mod tests {
message::{Message, MessageHeader},
nonce,
poh_config::PohConfig,
process_instruction::InvokeContext,
rent::Rent,
signature::{Keypair, Signer},
system_instruction::{self, SystemError},
@ -4428,6 +4431,7 @@ mod tests {
_program_id: &Pubkey,
keyed_accounts: &[KeyedAccount],
data: &[u8],
_invoke_context: &mut dyn InvokeContext,
) -> result::Result<(), InstructionError> {
if let Ok(instruction) = bincode::deserialize(data) {
match instruction {
@ -7724,6 +7728,7 @@ mod tests {
program_id: &Pubkey,
_keyed_accounts: &[KeyedAccount],
_instruction_data: &[u8],
_invoke_context: &mut dyn InvokeContext,
) -> std::result::Result<(), InstructionError> {
if mock_vote_program_id() != *program_id {
return Err(InstructionError::IncorrectProgramId);
@ -7781,6 +7786,7 @@ mod tests {
_pubkey: &Pubkey,
_ka: &[KeyedAccount],
_data: &[u8],
_invoke_context: &mut dyn InvokeContext,
) -> std::result::Result<(), InstructionError> {
Err(InstructionError::Custom(42))
}
@ -7831,6 +7837,7 @@ mod tests {
_pubkey: &Pubkey,
_ka: &[KeyedAccount],
_data: &[u8],
_invoke_context: &mut dyn InvokeContext,
) -> std::result::Result<(), InstructionError> {
Err(InstructionError::Custom(42))
}
@ -8499,6 +8506,7 @@ mod tests {
_program_id: &Pubkey,
keyed_accounts: &[KeyedAccount],
data: &[u8],
_invoke_context: &mut dyn InvokeContext,
) -> result::Result<(), InstructionError> {
let lamports = data[0] as u64;
{
@ -8551,6 +8559,7 @@ mod tests {
_program_id: &Pubkey,
_keyed_accounts: &[KeyedAccount],
_data: &[u8],
_invoke_context: &mut dyn InvokeContext,
) -> result::Result<(), InstructionError> {
Ok(())
}
@ -8733,6 +8742,7 @@ mod tests {
_pubkey: &Pubkey,
_ka: &[KeyedAccount],
_data: &[u8],
_invoke_context: &mut dyn InvokeContext,
) -> std::result::Result<(), InstructionError> {
Ok(())
}
@ -8982,6 +8992,7 @@ mod tests {
_program_id: &Pubkey,
keyed_accounts: &[KeyedAccount],
_data: &[u8],
_invoke_context: &mut dyn InvokeContext,
) -> result::Result<(), InstructionError> {
assert_eq!(42, keyed_accounts[0].lamports().unwrap());
let mut account = keyed_accounts[0].try_account_ref_mut()?;
@ -9163,6 +9174,7 @@ mod tests {
_pubkey: &Pubkey,
_ka: &[KeyedAccount],
_data: &[u8],
_invoke_context: &mut dyn InvokeContext,
) -> std::result::Result<(), InstructionError> {
Ok(())
}
@ -10065,22 +10077,15 @@ mod tests {
#[test]
fn test_debug_entrypoint() {
fn mock_process_instruction(
_program_id: &Pubkey,
_keyed_accounts: &[KeyedAccount],
_data: &[u8],
) -> std::result::Result<(), InstructionError> {
Ok(())
}
fn mock_ix_processor(
fn mock_processor(
_pubkey: &Pubkey,
_ka: &[KeyedAccount],
_data: &[u8],
_context: &mut dyn InvokeContext,
_invoke_context: &mut dyn InvokeContext,
) -> std::result::Result<(), InstructionError> {
Ok(())
}
assert!(!format!("{:?}", Entrypoint::Program(mock_process_instruction)).is_empty());
assert!(!format!("{:?}", Entrypoint::Loader(mock_ix_processor)).is_empty());
assert!(!format!("{:?}", Entrypoint::Program(mock_processor)).is_empty());
assert!(!format!("{:?}", Entrypoint::Loader(mock_processor)).is_empty());
}
}

View File

@ -1,96 +0,0 @@
use crate::process_instruction::{
ComputeBudget, ComputeMeter, Executor, InvokeContext, Logger, ProcessInstruction,
};
use solana_sdk::{
account::Account, instruction::CompiledInstruction, instruction::Instruction,
instruction::InstructionError, message::Message, pubkey::Pubkey,
};
use std::{cell::RefCell, rc::Rc, sync::Arc};
#[derive(Debug, Default, Clone)]
pub struct MockComputeMeter {
pub remaining: u64,
}
impl ComputeMeter for MockComputeMeter {
fn consume(&mut self, amount: u64) -> Result<(), InstructionError> {
let exceeded = self.remaining < amount;
self.remaining = self.remaining.saturating_sub(amount);
if exceeded {
return Err(InstructionError::ComputationalBudgetExceeded);
}
Ok(())
}
fn get_remaining(&self) -> u64 {
self.remaining
}
}
#[derive(Debug, Default, Clone)]
pub struct MockLogger {
pub log: Rc<RefCell<Vec<String>>>,
}
impl Logger for MockLogger {
fn log_enabled(&self) -> bool {
true
}
fn log(&mut self, message: &str) {
self.log.borrow_mut().push(message.to_string());
}
}
#[derive(Debug)]
pub struct MockInvokeContext {
pub key: Pubkey,
pub logger: MockLogger,
pub compute_budget: ComputeBudget,
pub compute_meter: MockComputeMeter,
}
impl Default for MockInvokeContext {
fn default() -> Self {
MockInvokeContext {
key: Pubkey::default(),
logger: MockLogger::default(),
compute_budget: ComputeBudget::default(),
compute_meter: MockComputeMeter {
remaining: std::i64::MAX as u64,
},
}
}
}
impl InvokeContext for MockInvokeContext {
fn push(&mut self, _key: &Pubkey) -> Result<(), InstructionError> {
Ok(())
}
fn pop(&mut self) {}
fn verify_and_update(
&mut self,
_message: &Message,
_instruction: &CompiledInstruction,
_accounts: &[Rc<RefCell<Account>>],
) -> Result<(), InstructionError> {
Ok(())
}
fn get_caller(&self) -> Result<&Pubkey, InstructionError> {
Ok(&self.key)
}
fn get_programs(&self) -> &[(Pubkey, ProcessInstruction)] {
&[]
}
fn get_logger(&self) -> Rc<RefCell<dyn Logger>> {
Rc::new(RefCell::new(self.logger.clone()))
}
fn get_compute_budget(&self) -> &ComputeBudget {
&self.compute_budget
}
fn get_compute_meter(&self) -> Rc<RefCell<dyn ComputeMeter>> {
Rc::new(RefCell::new(self.compute_meter.clone()))
}
fn add_executor(&mut self, _pubkey: &Pubkey, _executor: Arc<dyn Executor>) {}
fn get_executor(&mut self, _pubkey: &Pubkey) -> Option<Arc<dyn Executor>> {
None
}
fn record_instruction(&self, _instruction: &Instruction) {}
fn is_feature_active(&self, _feature_id: &Pubkey) -> bool {
true
}
}

View File

@ -1,79 +0,0 @@
use solana_sdk::{account::Account, clock::Slot};
solana_sdk::declare_id!("Feature111111111111111111111111111111111111");
/// The `Feature` struct is the on-chain representation of a runtime feature.
///
/// Feature activation is accomplished by:
/// 1. Activation is requested by the feature authority, who issues a transaction to create the
/// feature account. The newly created feature account will have the value of
/// `Feature::default()`
/// 2. When the next epoch is entered the runtime will check for new activation requests and
/// active them. When this occurs, the activation slot is recorded in the feature account
///
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct Feature {
pub activated_at: Option<Slot>,
}
impl Feature {
pub fn size_of() -> usize {
bincode::serialized_size(&Self {
activated_at: Some(0),
})
.unwrap() as usize
}
pub fn from_account(account: &Account) -> Option<Self> {
if account.owner != id() {
None
} else {
bincode::deserialize(&account.data).ok()
}
}
pub fn to_account(&self, account: &mut Account) -> Option<()> {
bincode::serialize_into(&mut account.data[..], self).ok()
}
pub fn create_account(&self, lamports: u64) -> Account {
let data_len = Self::size_of().max(bincode::serialized_size(self).unwrap() as usize);
let mut account = Account::new(lamports, data_len, &id());
self.to_account(&mut account).unwrap();
account
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn feature_deserialize_none() {
let just_initialized = Account::new(42, Feature::size_of(), &id());
assert_eq!(
Feature::from_account(&just_initialized),
Some(Feature { activated_at: None })
);
}
#[test]
fn feature_sizeof() {
assert!(
Feature::size_of() >= bincode::serialized_size(&Feature::default()).unwrap() as usize
);
assert_eq!(Feature::default(), Feature { activated_at: None });
let features = [
Feature {
activated_at: Some(0),
},
Feature {
activated_at: Some(Slot::MAX),
},
];
for feature in &features {
assert_eq!(
Feature::size_of(),
bincode::serialized_size(feature).unwrap() as usize
);
}
}
}

View File

@ -1,155 +0,0 @@
use lazy_static::lazy_static;
use solana_sdk::{
clock::Slot,
hash::{Hash, Hasher},
pubkey::Pubkey,
};
use std::collections::{HashMap, HashSet};
pub mod instructions_sysvar_enabled {
solana_sdk::declare_id!("EnvhHCLvg55P7PDtbvR1NwuTuAeodqpusV3MR5QEK8gs");
}
pub mod secp256k1_program_enabled {
solana_sdk::declare_id!("E3PHP7w8kB7np3CTQ1qQ2tW3KCtjRSXBQgW9vM2mWv2Y");
}
pub mod consistent_recent_blockhashes_sysvar {
solana_sdk::declare_id!("3h1BQWPDS5veRsq6mDBWruEpgPxRJkfwGexg5iiQ9mYg");
}
pub mod pico_inflation {
solana_sdk::declare_id!("GaBtBJvmS4Arjj5W1NmFcyvPjsHN38UGYDq2MDwbs9Qu");
}
pub mod inflation_kill_switch {
solana_sdk::declare_id!("SECCKV5UVUsr8sTVSVAzULjdm87r7mLPaqH2FGZjevR");
}
pub mod spl_token_v2_multisig_fix {
solana_sdk::declare_id!("E5JiFDQCwyC6QfT9REFyMpfK2mHcmv1GUDySU1Ue7TYv");
}
pub mod bpf_loader2_program {
solana_sdk::declare_id!("DFBnrgThdzH4W6wZ12uGPoWcMnvfZj11EHnxHcVxLPhD");
}
pub mod compute_budget_balancing {
solana_sdk::declare_id!("HxvjqDSiF5sYdSYuCXsUnS8UeAoWsMT9iGoFP8pgV1mB");
}
pub mod sha256_syscall_enabled {
solana_sdk::declare_id!("D7KfP7bZxpkYtD4Pc38t9htgs1k5k47Yhxe4rp6WDVi8");
}
pub mod no_overflow_rent_distribution {
solana_sdk::declare_id!("4kpdyrcj5jS47CZb2oJGfVxjYbsMm2Kx97gFyZrxxwXz");
}
pub mod ristretto_mul_syscall_enabled {
solana_sdk::declare_id!("HRe7A6aoxgjKzdjbBv6HTy7tJ4YWqE6tVmYCGho6S9Aq");
}
pub mod max_invoke_depth_4 {
solana_sdk::declare_id!("EdM9xggY5y7AhNMskRG8NgGMnaP4JFNsWi8ZZtyT1af5");
}
pub mod max_program_call_depth_64 {
solana_sdk::declare_id!("YCKSgA6XmjtkQrHBQjpyNrX6EMhJPcYcLWMVgWn36iv");
}
pub mod timestamp_correction {
solana_sdk::declare_id!("3zydSLUwuqqsV3wL5wBsaVgyvMox3XTHx7zLEuQf1U2Z");
}
pub mod cumulative_rent_related_fixes {
solana_sdk::declare_id!("FtjnuAtJTWwX3Kx9m24LduNEhzaGuuPfDW6e14SX2Fy5");
}
pub mod pubkey_log_syscall_enabled {
solana_sdk::declare_id!("MoqiU1vryuCGQSxFKA1SZ316JdLEFFhoAu6cKUNk7dN");
}
pub mod pull_request_ping_pong_check {
solana_sdk::declare_id!("5RzEHTnf6D7JPZCvwEzjM19kzBsyjSU3HoMfXaQmVgnZ");
}
pub mod bpf_just_in_time_compilation {
solana_sdk::declare_id!("3bZhti6PMmsdkPxqPT8TPNzB3n9NYbKtnwqEpUDnFuPi");
}
lazy_static! {
/// Map of feature identifiers to user-visible description
pub static ref FEATURE_NAMES: HashMap<Pubkey, &'static str> = [
(instructions_sysvar_enabled::id(), "instructions sysvar"),
(secp256k1_program_enabled::id(), "secp256k1 program"),
(consistent_recent_blockhashes_sysvar::id(), "consistent recentblockhashes sysvar"),
(pico_inflation::id(), "pico-inflation"),
(inflation_kill_switch::id(), "inflation kill switch"),
(spl_token_v2_multisig_fix::id(), "spl-token multisig fix"),
(bpf_loader2_program::id(), "bpf_loader2 program"),
(compute_budget_balancing::id(), "compute budget balancing"),
(sha256_syscall_enabled::id(), "sha256 syscall"),
(no_overflow_rent_distribution::id(), "no overflow rent distribution"),
(ristretto_mul_syscall_enabled::id(), "ristretto multiply syscall"),
(max_invoke_depth_4::id(), "max invoke call depth 4"),
(max_program_call_depth_64::id(), "max program call depth 64"),
(timestamp_correction::id(), "correct bank timestamps"),
(cumulative_rent_related_fixes::id(), "rent fixes (#10206, #10468, #11342)"),
(pubkey_log_syscall_enabled::id(), "pubkey log syscall"),
(pull_request_ping_pong_check::id(), "ping-pong packet check #12794"),
(bpf_just_in_time_compilation::id(), "bpf just-in-time compilation #12951"),
/*************** ADD NEW FEATURES HERE ***************/
]
.iter()
.cloned()
.collect();
/// Unique identifier of the current software's feature set
pub static ref ID: Hash = {
let mut hasher = Hasher::default();
let mut feature_ids = FEATURE_NAMES.keys().collect::<Vec<_>>();
feature_ids.sort();
for feature in feature_ids {
hasher.hash(feature.as_ref());
}
hasher.result()
};
}
/// `FeatureSet` holds the set of currently active/inactive runtime features
#[derive(AbiExample, Debug, Clone)]
pub struct FeatureSet {
pub active: HashMap<Pubkey, Slot>,
pub inactive: HashSet<Pubkey>,
}
impl Default for FeatureSet {
fn default() -> Self {
// All features disabled
Self {
active: HashMap::new(),
inactive: FEATURE_NAMES.keys().cloned().collect(),
}
}
}
impl FeatureSet {
pub fn is_active(&self, feature_id: &Pubkey) -> bool {
self.active.contains_key(feature_id)
}
pub fn activated_slot(&self, feature_id: &Pubkey) -> Option<Slot> {
self.active.get(feature_id).copied()
}
pub fn cumulative_rent_related_fixes_enabled(&self) -> bool {
self.is_active(&cumulative_rent_related_fixes::id())
}
/// All features enabled, useful for testing
pub fn all_enabled() -> Self {
Self {
active: FEATURE_NAMES.keys().cloned().map(|key| (key, 0)).collect(),
inactive: HashSet::new(),
}
}
}

View File

@ -10,12 +10,9 @@ pub mod bank_forks;
pub mod bank_utils;
mod blockhash_queue;
pub mod bloom;
pub mod bpf_test_utils;
pub mod builtins;
pub mod commitment;
pub mod epoch_stakes;
pub mod feature;
pub mod feature_set;
pub mod genesis_utils;
pub mod hardened_unpack;
pub mod instruction_recorder;
@ -23,7 +20,6 @@ pub mod loader_utils;
pub mod log_collector;
pub mod message_processor;
mod native_loader;
pub mod process_instruction;
pub mod rent_collector;
pub mod serde_snapshot;
pub mod snapshot_package;
@ -35,6 +31,10 @@ pub mod transaction_batch;
pub mod transaction_utils;
pub mod vote_sender_types;
// TODO: Refactor all feature users to reference the solana_sdk definitions directly and remove the
// next line
use solana_sdk::{feature, feature_set};
extern crate solana_config_program;
extern crate solana_stake_program;
extern crate solana_vote_program;

View File

@ -3,10 +3,6 @@ use crate::{
instruction_recorder::InstructionRecorder,
log_collector::LogCollector,
native_loader::NativeLoader,
process_instruction::{
ComputeBudget, ComputeMeter, ErasedProcessInstruction, ErasedProcessInstructionWithContext,
Executor, InvokeContext, Logger, ProcessInstruction, ProcessInstructionWithContext,
},
rent_collector::RentCollector,
};
use log::*;
@ -18,6 +14,10 @@ use solana_sdk::{
keyed_account::{create_keyed_readonly_accounts, KeyedAccount},
message::Message,
native_loader,
process_instruction::{
ComputeBudget, ComputeMeter, ErasedProcessInstructionWithContext, Executor, InvokeContext,
Logger, ProcessInstructionWithContext,
},
pubkey::Pubkey,
rent::Rent,
system_program,
@ -205,7 +205,7 @@ pub struct ThisInvokeContext {
program_ids: Vec<Pubkey>,
rent: Rent,
pre_accounts: Vec<PreAccount>,
programs: Vec<(Pubkey, ProcessInstruction)>,
programs: Vec<(Pubkey, ProcessInstructionWithContext)>,
logger: Rc<RefCell<dyn Logger>>,
compute_budget: ComputeBudget,
compute_meter: Rc<RefCell<dyn ComputeMeter>>,
@ -218,7 +218,7 @@ impl ThisInvokeContext {
program_id: &Pubkey,
rent: Rent,
pre_accounts: Vec<PreAccount>,
programs: Vec<(Pubkey, ProcessInstruction)>,
programs: Vec<(Pubkey, ProcessInstructionWithContext)>,
log_collector: Option<Rc<LogCollector>>,
compute_budget: ComputeBudget,
executors: Rc<RefCell<Executors>>,
@ -281,7 +281,7 @@ impl InvokeContext for ThisInvokeContext {
.last()
.ok_or(InstructionError::GenericError)
}
fn get_programs(&self) -> &[(Pubkey, ProcessInstruction)] {
fn get_programs(&self) -> &[(Pubkey, ProcessInstructionWithContext)] {
&self.programs
}
fn get_logger(&self) -> Rc<RefCell<dyn Logger>> {
@ -326,7 +326,7 @@ impl Logger for ThisLogger {
#[derive(Deserialize, Serialize)]
pub struct MessageProcessor {
#[serde(skip)]
programs: Vec<(Pubkey, ProcessInstruction)>,
programs: Vec<(Pubkey, ProcessInstructionWithContext)>,
#[serde(skip)]
loaders: Vec<(Pubkey, ProcessInstructionWithContext)>,
#[serde(skip)]
@ -349,7 +349,7 @@ impl std::fmt::Debug for MessageProcessor {
.programs
.iter()
.map(|(pubkey, instruction)| {
let erased_instruction: ErasedProcessInstruction = *instruction;
let erased_instruction: ErasedProcessInstructionWithContext = *instruction;
format!("{}: {:p}", pubkey, erased_instruction)
})
.collect::<Vec<_>>(),
@ -398,7 +398,11 @@ impl ::solana_frozen_abi::abi_example::AbiExample for MessageProcessor {
impl MessageProcessor {
/// Add a static entrypoint to intercept instructions before the dynamic loader.
pub fn add_program(&mut self, program_id: Pubkey, process_instruction: ProcessInstruction) {
pub fn add_program(
&mut self,
program_id: Pubkey,
process_instruction: ProcessInstructionWithContext,
) {
match self.programs.iter_mut().find(|(key, _)| program_id == *key) {
Some((_, processor)) => *processor = process_instruction,
None => self.programs.push((program_id, process_instruction)),
@ -476,6 +480,7 @@ impl MessageProcessor {
&root_id,
&keyed_accounts[1..],
instruction_data,
invoke_context,
);
}
}
@ -1266,6 +1271,7 @@ mod tests {
_program_id: &Pubkey,
keyed_accounts: &[KeyedAccount],
data: &[u8],
_invoke_context: &mut dyn InvokeContext,
) -> Result<(), InstructionError> {
if let Ok(instruction) = bincode::deserialize(data) {
match instruction {
@ -1400,6 +1406,7 @@ mod tests {
_program_id: &Pubkey,
keyed_accounts: &[KeyedAccount],
data: &[u8],
_invoke_context: &mut dyn InvokeContext,
) -> Result<(), InstructionError> {
if let Ok(instruction) = bincode::deserialize(data) {
match instruction {
@ -1559,6 +1566,7 @@ mod tests {
program_id: &Pubkey,
keyed_accounts: &[KeyedAccount],
data: &[u8],
_invoke_context: &mut dyn InvokeContext,
) -> Result<(), InstructionError> {
assert_eq!(*program_id, keyed_accounts[0].owner()?);
assert_ne!(
@ -1675,6 +1683,7 @@ mod tests {
_program_id: &Pubkey,
_keyed_accounts: &[KeyedAccount],
_data: &[u8],
_invoke_context: &mut dyn InvokeContext,
) -> Result<(), InstructionError> {
Ok(())
}

View File

@ -1,5 +1,4 @@
//! Native loader
use crate::process_instruction::{InvokeContext, LoaderEntrypoint};
#[cfg(unix)]
use libloading::os::unix::*;
#[cfg(windows)]
@ -11,6 +10,7 @@ use solana_sdk::{
entrypoint_native::ProgramEntrypoint,
instruction::InstructionError,
keyed_account::{next_keyed_account, KeyedAccount},
process_instruction::{InvokeContext, LoaderEntrypoint},
pubkey::Pubkey,
};
use std::{collections::HashMap, env, path::PathBuf, str, sync::RwLock};

View File

@ -1,187 +0,0 @@
use crate::feature_set::{
compute_budget_balancing, max_invoke_depth_4, max_program_call_depth_64,
pubkey_log_syscall_enabled, FeatureSet,
};
use solana_sdk::{
account::Account,
instruction::{CompiledInstruction, Instruction, InstructionError},
keyed_account::KeyedAccount,
message::Message,
pubkey::Pubkey,
};
use std::{cell::RefCell, fmt::Debug, rc::Rc, sync::Arc};
// Prototype of a native loader entry point
///
/// program_id: Program ID of the currently executing program
/// keyed_accounts: Accounts passed as part of the instruction
/// instruction_data: Instruction data
/// invoke_context: Invocation context
pub type LoaderEntrypoint = unsafe extern "C" fn(
program_id: &Pubkey,
keyed_accounts: &[KeyedAccount],
instruction_data: &[u8],
invoke_context: &dyn InvokeContext,
) -> Result<(), InstructionError>;
pub type ProcessInstruction = fn(&Pubkey, &[KeyedAccount], &[u8]) -> Result<(), InstructionError>;
pub type ProcessInstructionWithContext =
fn(&Pubkey, &[KeyedAccount], &[u8], &mut dyn InvokeContext) -> Result<(), InstructionError>;
// These are just type aliases for work around of Debug-ing above function pointers
pub type ErasedProcessInstructionWithContext = fn(
&'static Pubkey,
&'static [KeyedAccount<'static>],
&'static [u8],
&'static mut dyn InvokeContext,
) -> Result<(), InstructionError>;
pub type ErasedProcessInstruction = fn(
&'static Pubkey,
&'static [KeyedAccount<'static>],
&'static [u8],
) -> Result<(), InstructionError>;
/// Invocation context passed to loaders
pub trait InvokeContext {
/// Push a program ID on to the invocation stack
fn push(&mut self, key: &Pubkey) -> Result<(), InstructionError>;
/// Pop a program ID off of the invocation stack
fn pop(&mut self);
/// Verify and update PreAccount state based on program execution
fn verify_and_update(
&mut self,
message: &Message,
instruction: &CompiledInstruction,
accounts: &[Rc<RefCell<Account>>],
) -> Result<(), InstructionError>;
/// Get the program ID of the currently executing program
fn get_caller(&self) -> Result<&Pubkey, InstructionError>;
/// Get a list of built-in programs
fn get_programs(&self) -> &[(Pubkey, ProcessInstruction)];
/// Get this invocation's logger
fn get_logger(&self) -> Rc<RefCell<dyn Logger>>;
/// Get this invocation's compute budget
fn get_compute_budget(&self) -> &ComputeBudget;
/// Get this invocation's compute meter
fn get_compute_meter(&self) -> Rc<RefCell<dyn ComputeMeter>>;
/// Loaders may need to do work in order to execute a program. Cache
/// the work that can be re-used across executions
fn add_executor(&mut self, pubkey: &Pubkey, executor: Arc<dyn Executor>);
/// Get the completed loader work that can be re-used across executions
fn get_executor(&mut self, pubkey: &Pubkey) -> Option<Arc<dyn Executor>>;
/// Record invoked instruction
fn record_instruction(&self, instruction: &Instruction);
/// Get the bank's active feature set
fn is_feature_active(&self, feature_id: &Pubkey) -> bool;
}
#[derive(Clone, Copy, Debug)]
pub struct ComputeBudget {
/// Number of compute units that an instruction is allowed. Compute units
/// are consumed by program execution, resources they use, etc...
pub max_units: u64,
/// Number of compute units consumed by a log call
pub log_units: u64,
/// Number of compute units consumed by a log_u64 call
pub log_64_units: u64,
/// Number of compute units consumed by a create_program_address call
pub create_program_address_units: u64,
/// Number of compute units consumed by an invoke call (not including the cost incurred by
/// the called program)
pub invoke_units: u64,
/// Maximum cross-program invocation depth allowed including the original caller
pub max_invoke_depth: usize,
/// Base number of compute units consumed to call SHA256
pub sha256_base_cost: u64,
/// Incremental number of units consumed by SHA256 (based on bytes)
pub sha256_byte_cost: u64,
/// Maximum BPF to BPF call depth
pub max_call_depth: usize,
/// Size of a stack frame in bytes, must match the size specified in the LLVM BPF backend
pub stack_frame_size: usize,
/// Number of compute units consumed by logging a `Pubkey`
pub log_pubkey_units: u64,
}
impl Default for ComputeBudget {
fn default() -> Self {
Self::new(&FeatureSet::all_enabled())
}
}
impl ComputeBudget {
pub fn new(feature_set: &FeatureSet) -> Self {
let mut compute_budget =
// Original
ComputeBudget {
max_units: 100_000,
log_units: 0,
log_64_units: 0,
create_program_address_units: 0,
invoke_units: 0,
max_invoke_depth: 1,
sha256_base_cost: 85,
sha256_byte_cost: 1,
max_call_depth: 20,
stack_frame_size: 4_096,
log_pubkey_units: 0,
};
if feature_set.is_active(&compute_budget_balancing::id()) {
compute_budget = ComputeBudget {
max_units: 200_000,
log_units: 100,
log_64_units: 100,
create_program_address_units: 1500,
invoke_units: 1000,
..compute_budget
};
}
if feature_set.is_active(&max_invoke_depth_4::id()) {
compute_budget = ComputeBudget {
max_invoke_depth: 4,
..compute_budget
};
}
if feature_set.is_active(&max_program_call_depth_64::id()) {
compute_budget = ComputeBudget {
max_call_depth: 64,
..compute_budget
};
}
if feature_set.is_active(&pubkey_log_syscall_enabled::id()) {
compute_budget = ComputeBudget {
log_pubkey_units: 100,
..compute_budget
};
}
compute_budget
}
}
/// Compute meter
pub trait ComputeMeter {
/// Consume compute units
fn consume(&mut self, amount: u64) -> Result<(), InstructionError>;
/// Get the number of remaining compute units
fn get_remaining(&self) -> u64;
}
/// Log messages
pub trait Logger {
fn log_enabled(&self) -> bool;
/// Log a message
fn log(&mut self, message: &str);
}
/// Program executor
pub trait Executor: Debug + Send + Sync {
/// Execute the program
fn execute(
&self,
program_id: &Pubkey,
keyed_accounts: &[KeyedAccount],
instruction_data: &[u8],
invoke_context: &mut dyn InvokeContext,
) -> Result<(), InstructionError>;
}

View File

@ -6,6 +6,7 @@ use solana_sdk::{
keyed_account::{from_keyed_account, get_signers, next_keyed_account, KeyedAccount},
nonce,
nonce_keyed_account::NonceKeyedAccount,
process_instruction::InvokeContext,
program_utils::limited_deserialize,
pubkey::Pubkey,
system_instruction::{SystemError, SystemInstruction, MAX_PERMITTED_DATA_LENGTH},
@ -213,6 +214,7 @@ pub fn process_instruction(
_owner: &Pubkey,
keyed_accounts: &[KeyedAccount],
instruction_data: &[u8],
_invoke_context: &mut dyn InvokeContext,
) -> Result<(), InstructionError> {
let instruction = limited_deserialize(instruction_data)?;
@ -363,7 +365,9 @@ mod tests {
hash::{hash, Hash},
instruction::{AccountMeta, Instruction, InstructionError},
message::Message,
nonce, nonce_account, recent_blockhashes_account,
nonce, nonce_account,
process_instruction::MockInvokeContext,
recent_blockhashes_account,
signature::{Keypair, Signer},
system_instruction, system_program, sysvar,
sysvar::recent_blockhashes::IterItem,
@ -381,6 +385,19 @@ mod tests {
}
}
fn process_instruction(
owner: &Pubkey,
keyed_accounts: &[KeyedAccount],
instruction_data: &[u8],
) -> Result<(), InstructionError> {
super::process_instruction(
owner,
keyed_accounts,
instruction_data,
&mut MockInvokeContext::default(),
)
}
fn create_default_account() -> RefCell<Account> {
RefCell::new(Account::default())
}
@ -1194,7 +1211,7 @@ mod tests {
.zip(accounts.iter())
.map(|(meta, account)| KeyedAccount::new(&meta.pubkey, meta.is_signer, account))
.collect();
super::process_instruction(&Pubkey::default(), &keyed_accounts, &instruction.data)
process_instruction(&Pubkey::default(), &keyed_accounts, &instruction.data)
}
}
@ -1212,7 +1229,7 @@ mod tests {
#[test]
fn test_process_nonce_ix_no_keyed_accs_fail() {
assert_eq!(
super::process_instruction(
process_instruction(
&Pubkey::default(),
&[],
&serialize(&SystemInstruction::AdvanceNonceAccount).unwrap()
@ -1224,7 +1241,7 @@ mod tests {
#[test]
fn test_process_nonce_ix_only_nonce_acc_fail() {
assert_eq!(
super::process_instruction(
process_instruction(
&Pubkey::default(),
&[KeyedAccount::new(
&Pubkey::default(),
@ -1240,7 +1257,7 @@ mod tests {
#[test]
fn test_process_nonce_ix_bad_recent_blockhash_state_fail() {
assert_eq!(
super::process_instruction(
process_instruction(
&Pubkey::default(),
&[
KeyedAccount::new(&Pubkey::default(), true, &create_default_account()),
@ -1259,7 +1276,7 @@ mod tests {
#[test]
fn test_process_nonce_ix_ok() {
let nonce_acc = nonce_account::create_account(1_000_000);
super::process_instruction(
process_instruction(
&Pubkey::default(),
&[
KeyedAccount::new(&Pubkey::default(), true, &nonce_acc),
@ -1288,7 +1305,7 @@ mod tests {
),
);
assert_eq!(
super::process_instruction(
process_instruction(
&Pubkey::default(),
&[
KeyedAccount::new(&Pubkey::default(), true, &nonce_acc,),
@ -1320,7 +1337,7 @@ mod tests {
#[test]
fn test_process_withdraw_ix_no_keyed_accs_fail() {
assert_eq!(
super::process_instruction(
process_instruction(
&Pubkey::default(),
&[],
&serialize(&SystemInstruction::WithdrawNonceAccount(42)).unwrap(),
@ -1332,7 +1349,7 @@ mod tests {
#[test]
fn test_process_withdraw_ix_only_nonce_acc_fail() {
assert_eq!(
super::process_instruction(
process_instruction(
&Pubkey::default(),
&[KeyedAccount::new(
&Pubkey::default(),
@ -1348,7 +1365,7 @@ mod tests {
#[test]
fn test_process_withdraw_ix_bad_recent_blockhash_state_fail() {
assert_eq!(
super::process_instruction(
process_instruction(
&Pubkey::default(),
&[
KeyedAccount::new(&Pubkey::default(), true, &create_default_account()),
@ -1368,7 +1385,7 @@ mod tests {
#[test]
fn test_process_withdraw_ix_bad_rent_state_fail() {
assert_eq!(
super::process_instruction(
process_instruction(
&Pubkey::default(),
&[
KeyedAccount::new(
@ -1393,7 +1410,7 @@ mod tests {
#[test]
fn test_process_withdraw_ix_ok() {
assert_eq!(
super::process_instruction(
process_instruction(
&Pubkey::default(),
&[
KeyedAccount::new(
@ -1418,7 +1435,7 @@ mod tests {
#[test]
fn test_process_initialize_ix_no_keyed_accs_fail() {
assert_eq!(
super::process_instruction(
process_instruction(
&Pubkey::default(),
&[],
&serialize(&SystemInstruction::InitializeNonceAccount(Pubkey::default())).unwrap(),
@ -1430,7 +1447,7 @@ mod tests {
#[test]
fn test_process_initialize_ix_only_nonce_acc_fail() {
assert_eq!(
super::process_instruction(
process_instruction(
&Pubkey::default(),
&[KeyedAccount::new(
&Pubkey::default(),
@ -1446,7 +1463,7 @@ mod tests {
#[test]
fn test_process_initialize_bad_recent_blockhash_state_fail() {
assert_eq!(
super::process_instruction(
process_instruction(
&Pubkey::default(),
&[
KeyedAccount::new(
@ -1469,7 +1486,7 @@ mod tests {
#[test]
fn test_process_initialize_ix_bad_rent_state_fail() {
assert_eq!(
super::process_instruction(
process_instruction(
&Pubkey::default(),
&[
KeyedAccount::new(
@ -1493,7 +1510,7 @@ mod tests {
#[test]
fn test_process_initialize_ix_ok() {
assert_eq!(
super::process_instruction(
process_instruction(
&Pubkey::default(),
&[
KeyedAccount::new(
@ -1517,7 +1534,7 @@ mod tests {
#[test]
fn test_process_authorize_ix_ok() {
let nonce_acc = nonce_account::create_account(1_000_000);
super::process_instruction(
process_instruction(
&Pubkey::default(),
&[
KeyedAccount::new(&Pubkey::default(), true, &nonce_acc),
@ -1532,7 +1549,7 @@ mod tests {
)
.unwrap();
assert_eq!(
super::process_instruction(
process_instruction(
&Pubkey::default(),
&[KeyedAccount::new(&Pubkey::default(), true, &nonce_acc,),],
&serialize(&SystemInstruction::AuthorizeNonceAccount(Pubkey::default(),)).unwrap(),