Skip to content

Commit

Permalink
Add get_processed_inner_instruction syscall
Browse files Browse the repository at this point in the history
  • Loading branch information
jackcmay committed Jan 15, 2022
1 parent 3bd5a89 commit 0ee41f9
Show file tree
Hide file tree
Showing 11 changed files with 398 additions and 10 deletions.
18 changes: 18 additions & 0 deletions program-runtime/src/invoke_context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@ pub struct InvokeContext<'a> {
pub timings: ExecuteDetailsTimings,
pub blockhash: Hash,
pub lamports_per_signature: u64,
pub sibling_instructions: Vec<Instruction>,
}

impl<'a> InvokeContext<'a> {
Expand Down Expand Up @@ -233,6 +234,7 @@ impl<'a> InvokeContext<'a> {
timings: ExecuteDetailsTimings::default(),
blockhash,
lamports_per_signature,
sibling_instructions: Vec::new(),
}
}

Expand Down Expand Up @@ -815,6 +817,7 @@ impl<'a> InvokeContext<'a> {
if let Some(instruction_recorder) = &self.instruction_recorder {
instruction_recorder.borrow_mut().begin_next_recording();
}
self.sibling_instructions.clear();
} else {
// Verify the calling program hasn't misbehaved
let mut verify_caller_time = Measure::start("verify_caller_time");
Expand Down Expand Up @@ -1012,6 +1015,21 @@ impl<'a> InvokeContext<'a> {
pub fn get_sysvar_cache(&self) -> &SysvarCache {
&self.sysvar_cache
}

// Push a sibling instruction
pub fn add_sibling_instruction(&mut self, instruction: Instruction) {
self.sibling_instructions.push(instruction.clone());
}

/// Get a sibling instruction, reverse ordered or last added is index 0
pub fn get_sibling_instruction(&self, index: usize) -> Option<&Instruction> {
let index = self
.sibling_instructions
.len()
.checked_sub(1)?
.checked_sub(index)?;
self.sibling_instructions.get(index)
}
}

pub struct MockInvokeContextPreparation {
Expand Down
7 changes: 7 additions & 0 deletions programs/bpf/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions programs/bpf/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ members = [
"rust/sanity",
"rust/secp256k1_recover",
"rust/sha",
"rust/sibling_instruction",
"rust/spoof1",
"rust/spoof1_system",
"rust/sysvar",
Expand Down
1 change: 1 addition & 0 deletions programs/bpf/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ fn main() {
"sanity",
"secp256k1_recover",
"sha",
"sibling_instruction",
"spoof1",
"spoof1_system",
"upgradeable",
Expand Down
23 changes: 23 additions & 0 deletions programs/bpf/rust/sibling_instruction/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
[package]
name = "solana-bpf-rust-sibling-instructions"
version = "1.10.0"
description = "Solana BPF test program written in Rust"
authors = ["Solana Maintainers <[email protected]>"]
repository = "https://github.com/solana-labs/solana"
license = "Apache-2.0"
homepage = "https://solana.com/"
documentation = "https://docs.rs/solana-bpf-rust-log-data"
edition = "2021"

[dependencies]
solana-program = { path = "../../../../sdk/program", version = "=1.10.0" }

[features]
default = ["program"]
program = []

[lib]
crate-type = ["lib", "cdylib"]

[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]
61 changes: 61 additions & 0 deletions programs/bpf/rust/sibling_instruction/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
//! Example Rust-based BPF program that uses sol_get_sibling_instruction syscall
#![cfg(feature = "program")]

use solana_program::{
account_info::AccountInfo,
entrypoint,
entrypoint::ProgramResult,
instruction::{get_sibling_instruction, AccountMeta, Instruction},
msg,
program::invoke,
pubkey::Pubkey,
};

entrypoint!(process_instruction);
fn process_instruction(
_program_id: &Pubkey,
accounts: &[AccountInfo],
instruction_data: &[u8],
) -> ProgramResult {
msg!("sibling");

// account 0 is mint
// account 1 is noop
// account 2 is invoke_and_return

let instruction3 = Instruction::new_with_bytes(*accounts[1].key, instruction_data, vec![]);
let instruction2 = Instruction::new_with_bytes(
*accounts[2].key,
instruction_data,
vec![AccountMeta::new_readonly(*accounts[1].key, false)],
);
let instruction1 = Instruction::new_with_bytes(
*accounts[1].key,
instruction_data,
vec![
AccountMeta::new_readonly(*accounts[0].key, true),
AccountMeta::new_readonly(*accounts[1].key, false),
],
);
let instruction0 = Instruction::new_with_bytes(
*accounts[1].key,
instruction_data,
vec![
AccountMeta::new_readonly(*accounts[1].key, false),
AccountMeta::new_readonly(*accounts[0].key, true),
],
);

invoke(&instruction2, accounts)?;
invoke(&instruction1, accounts)?;
invoke(&instruction0, accounts)?;

assert_eq!(Some(instruction0), get_sibling_instruction(0));
assert_eq!(Some(instruction1), get_sibling_instruction(1));
assert_eq!(Some(instruction2), get_sibling_instruction(2));
assert_eq!(Some(instruction3), get_sibling_instruction(3));
assert!(get_sibling_instruction(4).is_none());

Ok(())
}
67 changes: 60 additions & 7 deletions programs/bpf/tests/programs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -226,13 +226,16 @@ fn run_program(name: &str) -> u64 {
let mut instruction_count = 0;
let mut tracer = None;
for i in 0..2 {
invoke_context.transaction_context.set_return_data(
*invoke_context
.transaction_context
.get_program_key()
.unwrap(),
Vec::new(),
).unwrap();
invoke_context
.transaction_context
.set_return_data(
*invoke_context
.transaction_context
.get_program_key()
.unwrap(),
Vec::new(),
)
.unwrap();
let mut parameter_bytes = parameter_bytes.clone();
{
let mut vm = create_vm(
Expand Down Expand Up @@ -3325,3 +3328,53 @@ fn test_program_bpf_realloc_invoke() {
TransactionError::InstructionError(0, InstructionError::InvalidRealloc)
);
}

#[test]
#[cfg(any(feature = "bpf_rust"))]
fn test_program_bpf_sibling_instruction() {
solana_logger::setup();

let GenesisConfigInfo {
genesis_config,
mint_keypair,
..
} = create_genesis_config(50);
let mut bank = Bank::new_for_tests(&genesis_config);
let (name, id, entrypoint) = solana_bpf_loader_program!();
bank.add_builtin(&name, &id, entrypoint);
let bank = Arc::new(bank);
let bank_client = BankClient::new_shared(&bank);

let program_id = load_bpf_program(
&bank_client,
&bpf_loader::id(),
&mint_keypair,
"solana_bpf_rust_sibling_instructions",
);
let noop_program_id = load_bpf_program(
&bank_client,
&bpf_loader::id(),
&mint_keypair,
"solana_bpf_rust_noop",
);
let invoke_and_return_program_id = load_bpf_program(
&bank_client,
&bpf_loader::id(),
&mint_keypair,
"solana_bpf_rust_invoke_and_return",
);

let instruction = Instruction::new_with_bytes(
program_id,
&[1, 2, 3, 0, 4, 5, 6],
vec![
AccountMeta::new(mint_keypair.pubkey(), true),
AccountMeta::new_readonly(noop_program_id, false),
AccountMeta::new_readonly(invoke_and_return_program_id, false),
],
);
let message = Message::new(&[instruction], Some(&mint_keypair.pubkey()));
assert!(bank_client
.send_and_confirm_message(&[&mint_keypair], message)
.is_ok());
}
106 changes: 104 additions & 2 deletions programs/bpf_loader/src/syscalls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,10 @@ use {
fixed_memcpy_nonoverlapping_check, libsecp256k1_0_5_upgrade_enabled,
prevent_calling_precompiles_as_programs, return_data_syscall_enabled,
secp256k1_recover_syscall_enabled, sol_log_data_syscall_enabled,
update_syscall_base_costs,
update_syscall_base_costs, add_get_sibling_instruction_syscall
},
hash::{Hasher, HASH_BYTES},
instruction::{AccountMeta, Instruction, InstructionError},
instruction::{AccountMeta, Instruction, InstructionError, SiblingLengths},
keccak, native_loader,
precompiles::is_precompile,
program::MAX_RETURN_DATA,
Expand Down Expand Up @@ -222,6 +222,16 @@ pub fn register_syscalls(
syscall_registry.register_syscall_by_name(b"sol_log_data", SyscallLogData::call)?;
}

if invoke_context
.feature_set
.is_active(&add_get_sibling_instruction_syscall::id())
{
syscall_registry.register_syscall_by_name(
b"sol_get_sibling_instruction",
SyscallGetSiblingInstruction::call,
)?;
}

Ok(syscall_registry)
}

Expand Down Expand Up @@ -262,6 +272,9 @@ pub fn bind_syscall_context_objects<'a, 'b>(
let is_zk_token_sdk_enabled = invoke_context
.feature_set
.is_active(&feature_set::zk_token_sdk_enabled::id());
let add_get_sibling_instruction_syscall = invoke_context
.feature_set
.is_active(&add_get_sibling_instruction_syscall::id());

let loader_id = invoke_context
.transaction_context
Expand Down Expand Up @@ -444,6 +457,15 @@ pub fn bind_syscall_context_objects<'a, 'b>(
}),
);

// sibling instructions
bind_feature_gated_syscall_context_object!(
vm,
add_get_sibling_instruction_syscall,
Box::new(SyscallGetSiblingInstruction {
invoke_context: invoke_context.clone(),
}),
);

// Cross-program invocation syscalls
vm.bind_syscall_context_object(
Box::new(SyscallInvokeSignedC {
Expand Down Expand Up @@ -2677,6 +2699,8 @@ fn call<'a, 'b: 'a>(
)
.map_err(SyscallError::InstructionError)?;

invoke_context.add_sibling_instruction(instruction);

// Copy results back to caller
for (callee_account_index, caller_account) in accounts.iter_mut() {
if let Some(caller_account) = caller_account {
Expand Down Expand Up @@ -2955,6 +2979,84 @@ impl<'a, 'b> SyscallObject<BpfError> for SyscallLogData<'a, 'b> {
}
}

pub struct SyscallGetSiblingInstruction<'a, 'b> {
invoke_context: Rc<RefCell<&'a mut InvokeContext<'b>>>,
}
impl<'a, 'b> SyscallObject<BpfError> for SyscallGetSiblingInstruction<'a, 'b> {
fn call(
&mut self,
index: u64,
lengths_addr: u64,
program_id_addr: u64,
data_addr: u64,
accounts_addr: u64,
memory_mapping: &MemoryMapping,
result: &mut Result<u64, EbpfError<BpfError>>,
) {
let invoke_context = question_mark!(
self.invoke_context
.try_borrow()
.map_err(|_| SyscallError::InvokeContextBorrowFailed),
result
);
let loader_id = question_mark!(
invoke_context
.transaction_context
.get_loader_key()
.map_err(SyscallError::InstructionError),
result
);

let budget = invoke_context.get_compute_budget();
question_mark!(
invoke_context
.get_compute_meter()
.consume(budget.syscall_base_cost),
result
);

if let Some(instruction) = invoke_context.get_sibling_instruction(index as usize) {
let SiblingLengths {
data_len,
accounts_len,
} = question_mark!(
translate_type_mut::<SiblingLengths>(memory_mapping, lengths_addr, &loader_id),
result
);
if *data_len >= instruction.data.len() as u64
&& *accounts_len >= instruction.accounts.len() as u64
{
let program_id = question_mark!(
translate_type_mut::<Pubkey>(memory_mapping, program_id_addr, &loader_id),
result
);
let data = question_mark!(
translate_slice_mut::<u8>(memory_mapping, data_addr, *data_len, &loader_id,),
result
);
let accounts = question_mark!(
translate_slice_mut::<AccountMeta>(
memory_mapping,
accounts_addr,
*accounts_len,
&loader_id,
),
result
);

*program_id = instruction.program_id;
data.clone_from_slice(instruction.data.as_slice());
accounts.clone_from_slice(instruction.accounts.as_slice());
}
*data_len = instruction.data.len() as u64;
*accounts_len = instruction.accounts.len() as u64;
*result = Ok(true as u64);
} else {
*result = Ok(false as u64);
}
}
}

#[cfg(test)]
mod tests {
#[allow(deprecated)]
Expand Down
Loading

0 comments on commit 0ee41f9

Please sign in to comment.