Skip to main content

solana_program_runtime/
invoke_context.rs

1#[cfg(feature = "dev-context-only-utils")]
2use {
3    crate::program_cache::entry::ProgramCacheEntry,
4    qualifier_attr::qualifiers,
5    solana_account::{AccountSharedData, WritableAccount, state_traits::StateMutWincode as _},
6    solana_epoch_schedule::EpochSchedule,
7    solana_instruction::AccountMeta,
8    solana_message::{LegacyMessage, Message, SanitizedMessage},
9    solana_sdk_ids::sysvar,
10    solana_transaction_context::transaction_accounts::KeyedAccountSharedData,
11    std::collections::{HashMap, HashSet},
12};
13use {
14    crate::{
15        abi::ABI,
16        execution_budget::{SVMTransactionExecutionBudget, SVMTransactionExecutionCost},
17        memory_context::{MemoryContext, MemoryContexts},
18        program_cache::{
19            entry::ProgramCacheEntryType,
20            env::{ProgramRuntimeEnvironment, ProgramRuntimeEnvironments},
21            tx_batch::ProgramCacheForTxBatch,
22        },
23        stable_log,
24        sysvar_cache::SysvarCache,
25    },
26    solana_hash::Hash,
27    solana_instruction::Instruction,
28    solana_instruction_error::InstructionError,
29    solana_pubkey::Pubkey,
30    solana_sbpf::{
31        ebpf::MM_HEAP_START,
32        elf::{ElfError, Executable as GenericExecutable},
33        error::{EbpfError, ProgramResult},
34        memory_region::MemoryMapping,
35        program::{BuiltinProgram, SBPFVersion},
36        vm::{Config, ContextObject, EbpfVm},
37    },
38    solana_sdk_ids::{
39        bpf_loader, bpf_loader_deprecated, bpf_loader_upgradeable, loader_v4, native_loader,
40    },
41    solana_svm_callback::InvokeContextCallback,
42    solana_svm_feature_set::SVMFeatureSet,
43    solana_svm_log_collector::{LogCollector, ic_msg},
44    solana_svm_measure::{measure::Measure, measure_us},
45    solana_svm_timings::{ExecuteDetailsTimings, ExecuteTimings},
46    solana_svm_transaction::svm_message::SVMMessage,
47    solana_svm_type_overrides::sync::Arc,
48    solana_transaction_context::{
49        IndexOfAccount, MAX_ACCOUNTS_PER_TRANSACTION, instruction::InstructionContext,
50        instruction_accounts::InstructionAccount, transaction::TransactionContext,
51    },
52    std::{
53        alloc::Layout,
54        borrow::Cow,
55        cell::RefCell,
56        fmt::{self, Debug},
57        ptr,
58        rc::Rc,
59        time::Duration,
60    },
61};
62
63pub type BuiltinFunctionRegisterer =
64    fn(&mut BuiltinProgram<InvokeContext<'static, 'static>>, &str) -> Result<(), ElfError>;
65pub type Executable = GenericExecutable<InvokeContext<'static, 'static>>;
66pub type RegisterTrace<'a> = &'a [[u64; 12]];
67
68/// Adapter so we can unify the interfaces of built-in programs and syscalls
69#[macro_export]
70macro_rules! declare_process_instruction {
71    ($process_instruction:ident, $cu_to_consume:expr, |$invoke_context:ident| $inner:tt) => {
72        $crate::solana_sbpf::declare_builtin_function!(
73            $process_instruction,
74            fn rust(
75                invoke_context: &mut $crate::invoke_context::InvokeContext<'_, '_>,
76                _arg0: u64,
77                _arg1: u64,
78                _arg2: u64,
79                _arg3: u64,
80                _arg4: u64,
81            ) -> Result<u64, Box<dyn std::error::Error>> {
82                fn process_instruction_inner(
83                    $invoke_context: &mut $crate::invoke_context::InvokeContext,
84                ) -> std::result::Result<(), $crate::__private::InstructionError>
85                    $inner
86
87                let consumption_result = if $cu_to_consume > 0
88                {
89                    invoke_context.consume_checked($cu_to_consume)
90                } else {
91                    Ok(())
92                };
93                consumption_result
94                    .and_then(|_| {
95                        process_instruction_inner(invoke_context)
96                            .map(|_| 0)
97                            .map_err(|err| Box::new(err) as Box<dyn std::error::Error>)
98                    })
99                    .into()
100            }
101        );
102    };
103}
104
105impl ContextObject for InvokeContext<'_, '_> {
106    fn consume(&mut self, amount: u64) {
107        self.transaction_context
108            .compute_meter
109            .consume_unchecked(amount);
110    }
111
112    fn get_remaining(&self) -> u64 {
113        self.transaction_context.compute_meter.get_remaining()
114    }
115
116    fn active_mapping_ptr(&mut self) -> ptr::NonNull<MemoryMapping> {
117        let memory = self
118            .memory_contexts
119            .memory_mapping_mut()
120            .expect("The memory context must have been set for the current instruction");
121        ptr::NonNull::from_mut(memory)
122    }
123}
124
125#[derive(Clone, PartialEq, Eq, Debug)]
126pub struct AllocErr;
127impl fmt::Display for AllocErr {
128    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
129        f.write_str("Error: Memory allocation failed")
130    }
131}
132
133pub struct BpfAllocator {
134    len: u64,
135    pos: u64,
136}
137
138impl BpfAllocator {
139    pub fn new(len: u64) -> Self {
140        Self { len, pos: 0 }
141    }
142
143    pub fn alloc(&mut self, layout: Layout) -> Result<u64, AllocErr> {
144        let bytes_to_align = (self.pos as *const u8).align_offset(layout.align()) as u64;
145        if self
146            .pos
147            .saturating_add(bytes_to_align)
148            .saturating_add(layout.size() as u64)
149            <= self.len
150        {
151            self.pos = self.pos.saturating_add(bytes_to_align);
152            let addr = MM_HEAP_START.saturating_add(self.pos);
153            self.pos = self.pos.saturating_add(layout.size() as u64);
154            Ok(addr)
155        } else {
156            Err(AllocErr)
157        }
158    }
159}
160
161pub struct EnvironmentConfig<'a> {
162    pub blockhash: Hash,
163    pub blockhash_lamports_per_signature: u64,
164    epoch_stake_callback: &'a dyn InvokeContextCallback,
165    feature_set: &'a SVMFeatureSet,
166    program_runtime_environments: &'a ProgramRuntimeEnvironments,
167    sysvar_cache: &'a SysvarCache,
168}
169impl<'a> EnvironmentConfig<'a> {
170    pub fn new(
171        blockhash: Hash,
172        blockhash_lamports_per_signature: u64,
173        epoch_stake_callback: &'a dyn InvokeContextCallback,
174        feature_set: &'a SVMFeatureSet,
175        program_runtime_environments: &'a ProgramRuntimeEnvironments,
176        sysvar_cache: &'a SysvarCache,
177    ) -> Self {
178        Self {
179            blockhash,
180            blockhash_lamports_per_signature,
181            epoch_stake_callback,
182            feature_set,
183            program_runtime_environments,
184            sysvar_cache,
185        }
186    }
187
188    /// Get cached sysvars
189    pub fn sysvar_cache(&self) -> &'a SysvarCache {
190        self.sysvar_cache
191    }
192}
193
194/// Main pipeline from runtime to program execution.
195pub struct InvokeContext<'a, 'ix_data> {
196    /// Information about the currently executing transaction.
197    pub transaction_context: &'a mut TransactionContext<'ix_data>,
198    /// The local program cache for the transaction batch.
199    pub program_cache_for_tx_batch: &'a mut ProgramCacheForTxBatch,
200    /// Runtime configurations used to provision the invocation environment.
201    pub environment_config: EnvironmentConfig<'a>,
202    /// The compute budget for the current invocation.
203    compute_budget: SVMTransactionExecutionBudget,
204    /// The compute cost for the current invocation.
205    execution_cost: SVMTransactionExecutionCost,
206    log_collector: Option<Rc<RefCell<LogCollector>>>,
207    /// Time spent so far executing nested program calls.
208    pub total_nested_exec_time: Duration,
209    pub timings: ExecuteDetailsTimings,
210    pub memory_contexts: MemoryContexts,
211    /// Pairs of index in TX instruction trace and VM register trace
212    register_traces: Vec<(usize, Vec<[u64; 12]>)>,
213    /// Debug port to use for this executing transaction.
214    #[cfg(feature = "sbpf-debugger")]
215    pub debug_port: Option<u16>,
216}
217
218impl<'a, 'ix_data> InvokeContext<'a, 'ix_data> {
219    pub fn new(
220        transaction_context: &'a mut TransactionContext<'ix_data>,
221        program_cache_for_tx_batch: &'a mut ProgramCacheForTxBatch,
222        environment_config: EnvironmentConfig<'a>,
223        log_collector: Option<Rc<RefCell<LogCollector>>>,
224        compute_budget: SVMTransactionExecutionBudget,
225        execution_cost: SVMTransactionExecutionCost,
226    ) -> Self {
227        Self {
228            transaction_context,
229            program_cache_for_tx_batch,
230            environment_config,
231            log_collector,
232            compute_budget,
233            execution_cost,
234            total_nested_exec_time: Duration::ZERO,
235            timings: ExecuteDetailsTimings::default(),
236            memory_contexts: MemoryContexts::new(),
237            register_traces: Vec::new(),
238            #[cfg(feature = "sbpf-debugger")]
239            debug_port: None,
240        }
241    }
242
243    /// Push a stack frame onto the invocation stack
244    #[cfg_attr(feature = "dev-context-only-utils", qualifiers(pub))]
245    fn push(&mut self) -> Result<(), InstructionError> {
246        let instruction_context = self.transaction_context.get_next_instruction_context()?;
247        let program_id = instruction_context
248            .get_program_key()
249            .map_err(|_| InstructionError::UnsupportedProgramId)?;
250        if self.transaction_context.get_instruction_stack_height() != 0 {
251            let contains =
252                (0..self.transaction_context.get_instruction_stack_height()).any(|level| {
253                    self.transaction_context
254                        .get_instruction_context_at_nesting_level(level)
255                        .and_then(|instruction_context| instruction_context.get_program_key())
256                        .map(|program_key| program_key == program_id)
257                        .unwrap_or(false)
258                });
259            let is_last = self
260                .transaction_context
261                .get_current_instruction_context()
262                .and_then(|instruction_context| instruction_context.get_program_key())
263                .map(|program_key| program_key == program_id)
264                .unwrap_or(false);
265            if contains && !is_last {
266                // Reentrancy not allowed unless caller is calling itself
267                return Err(InstructionError::ReentrancyNotAllowed);
268            }
269        }
270
271        let detect_overflow_early = self
272            .environment_config
273            .feature_set
274            .early_instruction_trace_overflow_detection;
275        self.transaction_context.push(detect_overflow_early)?;
276        self.memory_contexts.push_placeholder();
277        Ok(())
278    }
279
280    /// Pop a stack frame from the invocation stack
281    #[cfg_attr(feature = "dev-context-only-utils", qualifiers(pub))]
282    fn pop(&mut self) -> Result<(), InstructionError> {
283        self.memory_contexts.pop();
284        self.transaction_context.pop()
285    }
286
287    /// Current height of the invocation stack, top level instructions are height
288    /// `solana_instruction::TRANSACTION_LEVEL_STACK_HEIGHT`
289    pub fn get_stack_height(&self) -> usize {
290        self.transaction_context.get_instruction_stack_height()
291    }
292
293    /// Entrypoint for a cross-program invocation from a builtin program.
294    ///
295    /// Takes signer seeds and derives PDAs internally via
296    /// `create_program_address`, mirroring the SBF CPI path. This makes
297    /// it structurally impossible for a builtin to vouch for a non-PDA
298    /// address (e.g. a user wallet) as a signer.
299    pub fn native_invoke_signed(
300        &mut self,
301        instruction: Instruction,
302        signer_seeds: &[&[&[u8]]],
303    ) -> Result<(), InstructionError> {
304        let caller_program_id = *self
305            .transaction_context
306            .get_current_instruction_context()?
307            .get_program_key()?;
308        // The conversion from `PubkeyError` to `InstructionError` through
309        // num-traits is incorrect, but it's the existing behavior.
310        let signers = signer_seeds
311            .iter()
312            .map(|seeds| Pubkey::create_program_address(seeds, &caller_program_id))
313            .collect::<Result<Vec<Pubkey>, solana_pubkey::PubkeyError>>()
314            .map_err(|e| e as u64)?;
315        self.build_instruction_frame(instruction)?;
316        self.internal_native_invoke(&signers)?;
317        Ok(())
318    }
319
320    /// A special native invoke for when the instruction is already configured in the instruction
321    /// trace
322    pub fn internal_native_invoke(&mut self, signers: &[Pubkey]) -> Result<(), InstructionError> {
323        self.verify_instruction_accounts(signers)?;
324        let mut compute_units_consumed = 0;
325        self.process_instruction(&mut compute_units_consumed, &mut ExecuteTimings::default())?;
326        Ok(())
327    }
328
329    /// Verifies if all the CPI accounts are present in the caller, and checks writability and
330    /// signing permissions.
331    pub(crate) fn verify_instruction_accounts(
332        &mut self,
333        signers: &[Pubkey],
334    ) -> Result<(), InstructionError> {
335        let instruction_context = self.transaction_context.get_current_instruction_context()?;
336        let next_context = self.transaction_context.get_next_instruction_context()?;
337        let callee_instruction_accounts = next_context.instruction_accounts();
338        for (idx, callee_account) in callee_instruction_accounts.iter().enumerate() {
339            if next_context
340                .is_instruction_account_duplicate(idx as u16)?
341                .is_some()
342            {
343                continue;
344            }
345
346            // The account passed down to the instruction is supposed to be present in the caller
347            let index_in_caller = instruction_context
348                .get_index_of_account_in_instruction(callee_account.index_in_transaction)?;
349
350            let caller_instruction_account = instruction_context
351                .instruction_accounts()
352                .get(index_in_caller as usize)
353                .expect(
354                    "get_index_of_account_in_instruction above has already checked if the index \
355                     is valid.",
356                );
357
358            let account_key = self
359                .transaction_context
360                .get_key_of_account_at_index(caller_instruction_account.index_in_transaction)?;
361
362            // Readonly in caller cannot become writable in callee
363            if callee_account.is_writable() && !caller_instruction_account.is_writable() {
364                ic_msg!(self, "{}'s writable privilege escalated", account_key,);
365                return Err(InstructionError::PrivilegeEscalation);
366            }
367
368            // To be signed in the callee,
369            // it must be either signed in the caller or by the program
370            if callee_account.is_signer()
371                && !(caller_instruction_account.is_signer() || signers.contains(account_key))
372            {
373                ic_msg!(self, "{}'s signer privilege escalated", account_key,);
374                return Err(InstructionError::PrivilegeEscalation);
375            }
376        }
377
378        // See if program account is part of the instruction
379        // `build_instruction_frame` already checked if the account is part of the transaction.
380        let program_id_tx_idx = next_context.get_index_of_program_account_in_transaction()?;
381        if instruction_context
382            .get_index_of_account_in_instruction(program_id_tx_idx)
383            .is_err()
384        {
385            let callee_program_id = self
386                .transaction_context
387                .get_key_of_account_at_index(program_id_tx_idx)
388                .expect("We should have checked that the program ID is in the transaction");
389            ic_msg!(self, "Unknown program {}", callee_program_id);
390            return Err(InstructionError::MissingAccount);
391        }
392
393        Ok(())
394    }
395
396    /// Convert an SDK Instruction from CPI to an InstructionFrame used by runtime.
397    pub(crate) fn build_instruction_frame(
398        &mut self,
399        instruction: Instruction,
400    ) -> Result<(), InstructionError> {
401        // We reference accounts by an u8 index, so we have a total of 256 accounts.
402        let transaction_callee_map_len = (self.transaction_context.get_number_of_accounts()
403            as usize)
404            .min(MAX_ACCOUNTS_PER_TRANSACTION);
405        let mut transaction_callee_map: Vec<u8> = vec![u8::MAX; transaction_callee_map_len];
406        let mut instruction_accounts: Vec<InstructionAccount> =
407            Vec::with_capacity(instruction.accounts.len());
408
409        // This code block is necessary to restrict the scope of the immutable borrow of
410        // transaction context (the `instruction_context` variable). At the end of this
411        // function, we must borrow it again as mutable.
412        let program_account_index = {
413            for account_meta in instruction.accounts.iter() {
414                let index_in_transaction = self
415                    .transaction_context
416                    .find_index_of_account(&account_meta.pubkey)
417                    .ok_or_else(|| {
418                        ic_msg!(
419                            self,
420                            "Instruction references an unknown account {}",
421                            account_meta.pubkey,
422                        );
423                        InstructionError::MissingAccount
424                    })?;
425
426                debug_assert!((index_in_transaction as usize) < transaction_callee_map.len());
427                let index_in_callee = transaction_callee_map
428                    .get_mut(index_in_transaction as usize)
429                    .unwrap();
430
431                if (*index_in_callee as usize) < instruction_accounts.len() {
432                    let cloned_account = {
433                        let instruction_account = instruction_accounts
434                            .get_mut(*index_in_callee as usize)
435                            .ok_or(InstructionError::MissingAccount)?;
436                        instruction_account.set_is_signer(
437                            instruction_account.is_signer() || account_meta.is_signer,
438                        );
439                        instruction_account.set_is_writable(
440                            instruction_account.is_writable() || account_meta.is_writable,
441                        );
442                        *instruction_account
443                    };
444                    instruction_accounts.push(cloned_account);
445                } else {
446                    *index_in_callee = instruction_accounts.len() as u8;
447                    instruction_accounts.push(InstructionAccount::new(
448                        index_in_transaction,
449                        account_meta.is_signer,
450                        account_meta.is_writable,
451                    ));
452                }
453            }
454
455            TransactionContext::replicate_account_flags(
456                &mut instruction_accounts,
457                &transaction_callee_map,
458            );
459
460            // Find executables / program accounts
461            let callee_program_id = &instruction.program_id;
462            let program_account_index_in_transaction = self
463                .transaction_context
464                .find_index_of_account(callee_program_id);
465
466            // Validate executables / program accounts
467            // Check if the account exists in the transaction
468            if program_account_index_in_transaction.is_none() {
469                ic_msg!(self, "Unknown program {}", callee_program_id);
470                return Err(InstructionError::MissingAccount);
471            }
472
473            // SAFETY: This unwrap is safe, because we checked the index in instruction in the
474            // previous if-condition.
475            program_account_index_in_transaction.unwrap()
476        };
477
478        // This ? operator should not error out because `fn get_current_instruction_index` is also called
479        // in `get_current_instruction_context`
480        let caller_index = self.transaction_context.get_current_instruction_index()?;
481        self.transaction_context.configure_instruction_at_index(
482            self.transaction_context.get_instruction_trace_length(),
483            program_account_index,
484            instruction_accounts,
485            transaction_callee_map,
486            Cow::Owned(instruction.data),
487            Some(caller_index as u16),
488        )?;
489        Ok(())
490    }
491
492    /// Process a message. Calls each instruction in the message over the
493    /// configured [`TransactionContext`] and returns the final result.
494    /// For any instructions that fail, a tuple is returned whose elements are
495    /// (index of instruction, instruction error). Once an error is returned,
496    /// execution stops.
497    pub fn process_message(
498        &mut self,
499        message: &'ix_data impl SVMMessage,
500        execute_timings: &mut ExecuteTimings,
501        accumulated_consumed_units: &mut u64,
502    ) -> Result<(), (u8, InstructionError)> {
503        self.prepare_top_level_instructions(message)?;
504
505        for (top_level_instruction_index, (program_id, instruction)) in
506            message.program_instructions_iter().enumerate()
507        {
508            let mut compute_units_consumed = 0;
509            let (result, process_instruction_us) = measure_us!({
510                if self.is_precompile(program_id) {
511                    self.process_precompile(
512                        program_id,
513                        instruction.data,
514                        message.instructions_iter().map(|ix| ix.data),
515                    )
516                } else {
517                    self.process_instruction(&mut compute_units_consumed, execute_timings)
518                }
519            });
520
521            *accumulated_consumed_units =
522                accumulated_consumed_units.saturating_add(compute_units_consumed);
523            // The per_program_timings are only used for metrics reporting at the trace
524            // level, so they should only be accumulated when trace level is enabled.
525            if log::log_enabled!(log::Level::Trace) {
526                execute_timings.details.accumulate_program(
527                    program_id,
528                    process_instruction_us,
529                    compute_units_consumed,
530                    result.is_err(),
531                );
532            }
533            self.timings = {
534                execute_timings.details.accumulate(&self.timings);
535                ExecuteDetailsTimings::default()
536            };
537            execute_timings
538                .execute_accessories
539                .process_instructions
540                .total_us += process_instruction_us;
541
542            result.map_err(|err| (top_level_instruction_index as u8, err))?;
543        }
544
545        Ok(())
546    }
547
548    /// Prepare the instruction trace with all the top level instructions
549    #[cfg_attr(feature = "dev-context-only-utils", qualifiers(pub))]
550    fn prepare_top_level_instructions(
551        &mut self,
552        message: &'ix_data impl SVMMessage,
553    ) -> Result<(), (u8, InstructionError)> {
554        for (top_level_instruction_index, (_, instruction)) in
555            message.program_instructions_iter().enumerate()
556        {
557            let transaction_callee_map_len = message
558                .account_keys()
559                .len()
560                .min(MAX_ACCOUNTS_PER_TRANSACTION);
561            let mut transaction_callee_map: Vec<u8> = vec![u8::MAX; transaction_callee_map_len];
562
563            let mut instruction_accounts: Vec<InstructionAccount> =
564                Vec::with_capacity(instruction.accounts.len());
565            for index_in_transaction in instruction.accounts.iter() {
566                let index_in_callee = transaction_callee_map
567                    .get_mut(*index_in_transaction as usize)
568                    .expect("Invalid index in transaction");
569
570                if (*index_in_callee as usize) > instruction_accounts.len() {
571                    *index_in_callee = instruction_accounts.len() as u8;
572                }
573
574                let index_in_transaction = *index_in_transaction as usize;
575                instruction_accounts.push(InstructionAccount::new(
576                    index_in_transaction as IndexOfAccount,
577                    message.is_signer(index_in_transaction),
578                    message.is_writable(index_in_transaction),
579                ));
580            }
581
582            self.transaction_context
583                .configure_instruction_at_index(
584                    top_level_instruction_index,
585                    instruction.program_id_index as u16,
586                    instruction_accounts,
587                    transaction_callee_map,
588                    Cow::Borrowed(instruction.data),
589                    None,
590                )
591                .map_err(|err| (top_level_instruction_index as u8, err))?;
592        }
593        Ok(())
594    }
595
596    /// Processes an instruction and returns how many compute units were used
597    #[cfg_attr(feature = "dev-context-only-utils", qualifiers(pub))]
598    pub(crate) fn process_instruction(
599        &mut self,
600        compute_units_consumed: &mut u64,
601        timings: &mut ExecuteTimings,
602    ) -> Result<(), InstructionError> {
603        *compute_units_consumed = 0;
604        self.push()?;
605        self.process_executable_chain(compute_units_consumed, timings)
606            // MUST pop if and only if `push` succeeded, independent of `result`.
607            // Thus, the `.and()` instead of an `.and_then()`.
608            .and(self.pop())
609    }
610
611    /// Processes a precompile instruction
612    #[cfg_attr(feature = "dev-context-only-utils", qualifiers(pub))]
613    fn process_precompile(
614        &mut self,
615        program_id: &Pubkey,
616        instruction_data: &[u8],
617        message_instruction_datas_iter: impl Iterator<Item = &'ix_data [u8]>,
618    ) -> Result<(), InstructionError> {
619        self.push()?;
620        let instruction_datas: Vec<_> = message_instruction_datas_iter.collect();
621        self.environment_config
622            .epoch_stake_callback
623            .process_precompile(program_id, instruction_data, instruction_datas)
624            .map_err(InstructionError::from)
625            .and(self.pop())
626    }
627
628    /// Calls the instruction's program entrypoint method
629    fn process_executable_chain(
630        &mut self,
631        compute_units_consumed: &mut u64,
632        timings: &mut ExecuteTimings,
633    ) -> Result<(), InstructionError> {
634        let instruction_context = self.transaction_context.get_current_instruction_context()?;
635        let process_executable_chain_time = Measure::start("process_executable_chain_time");
636
637        let builtin_id = {
638            let owner_id = instruction_context.get_program_owner()?;
639            if native_loader::check_id(&owner_id) {
640                *instruction_context.get_program_key()?
641            } else if bpf_loader_deprecated::check_id(&owner_id)
642                || bpf_loader::check_id(&owner_id)
643                || bpf_loader_upgradeable::check_id(&owner_id)
644                || loader_v4::check_id(&owner_id)
645            {
646                owner_id
647            } else {
648                return Err(InstructionError::UnsupportedProgramId);
649            }
650        };
651
652        // The Murmur3 hash value (used by RBPF) of the string "entrypoint"
653        const ENTRYPOINT_KEY: u32 = 0x71E3CF81;
654        let entry = self
655            .program_cache_for_tx_batch
656            .find(&builtin_id)
657            .ok_or(InstructionError::UnsupportedProgramId)?;
658        let function = match &entry.program {
659            ProgramCacheEntryType::Builtin(program) => program
660                .get_function_registry()
661                .lookup_by_key(ENTRYPOINT_KEY)
662                .map(|(_name, (function, _codegen))| function),
663            _ => None,
664        }
665        .ok_or(InstructionError::UnsupportedProgramId)?;
666
667        let program_id = *instruction_context.get_program_key()?;
668        self.transaction_context
669            .set_return_data(program_id, Vec::new())?;
670        let logger = self.get_log_collector();
671        stable_log::program_invoke(&logger, &program_id, self.get_stack_height());
672        let pre_remaining_units = self.get_remaining();
673        // For now, only built-ins are invoked from here, so the VM and its Config are irrelevant.
674        self.memory_contexts
675            .set_memory_context_abi_v1(MemoryContext::new(
676                BpfAllocator::new(0),
677                Vec::new(),
678                // SAFETY:
679                // This path invokes a builtin program, so this mapping is never used.
680                unsafe {
681                    MemoryMapping::new(Vec::new(), &Config::default(), SBPFVersion::Reserved)
682                        .unwrap()
683                },
684            ))?;
685        let mut vm = EbpfVm::new(
686            Arc::clone(
687                &**self
688                    .environment_config
689                    .program_runtime_environments
690                    .get_env_for_execution(),
691            ),
692            SBPFVersion::V0,
693            // Removes lifetime tracking
694            unsafe { std::mem::transmute::<&mut InvokeContext, &mut InvokeContext>(self) },
695            0,
696        );
697        vm.invoke_function(function);
698        let result = match vm.program_result {
699            ProgramResult::Ok(_) => {
700                stable_log::program_success(&logger, &program_id);
701                Ok(())
702            }
703            ProgramResult::Err(ref err) => {
704                if let EbpfError::SyscallError(syscall_error) = err {
705                    if let Some(instruction_err) = syscall_error.downcast_ref::<InstructionError>()
706                    {
707                        stable_log::program_failure(&logger, &program_id, instruction_err);
708                        Err(instruction_err.clone())
709                    } else {
710                        stable_log::program_failure(&logger, &program_id, syscall_error);
711                        Err(InstructionError::ProgramFailedToComplete)
712                    }
713                } else {
714                    stable_log::program_failure(&logger, &program_id, err);
715                    Err(InstructionError::ProgramFailedToComplete)
716                }
717            }
718        };
719        let post_remaining_units = self.get_remaining();
720        *compute_units_consumed = pre_remaining_units.saturating_sub(post_remaining_units);
721
722        if builtin_id == program_id && result.is_ok() && *compute_units_consumed == 0 {
723            return Err(InstructionError::BuiltinProgramsMustConsumeComputeUnits);
724        }
725
726        timings
727            .execute_accessories
728            .process_instructions
729            .process_executable_chain_us += process_executable_chain_time.end_as_us();
730        result
731    }
732
733    pub fn consume_checked(&self, amount: u64) -> Result<(), Box<dyn std::error::Error>> {
734        self.transaction_context
735            .compute_meter
736            .consume_checked(amount)
737    }
738
739    #[cfg(feature = "dev-context-only-utils")]
740    pub fn mock_set_remaining(&self, remaining: u64) {
741        self.transaction_context
742            .compute_meter
743            .mock_set_remaining(remaining)
744    }
745
746    /// Get this invocation's LogCollector
747    pub fn get_log_collector(&self) -> Option<Rc<RefCell<LogCollector>>> {
748        self.log_collector.clone()
749    }
750
751    /// Get this invocation's compute budget
752    pub fn get_compute_budget(&self) -> &SVMTransactionExecutionBudget {
753        &self.compute_budget
754    }
755
756    /// Get this invocation's compute budget
757    pub fn get_execution_cost(&self) -> &SVMTransactionExecutionCost {
758        &self.execution_cost
759    }
760
761    /// Get the current feature set.
762    pub fn get_feature_set(&self) -> &SVMFeatureSet {
763        self.environment_config.feature_set
764    }
765
766    pub fn get_program_runtime_environment_for_deployment(&self) -> &ProgramRuntimeEnvironment {
767        self.environment_config
768            .program_runtime_environments
769            .get_env_for_deployment()
770    }
771
772    /// Get cached epoch total stake.
773    pub fn get_epoch_stake(&self) -> u64 {
774        self.environment_config
775            .epoch_stake_callback
776            .get_epoch_stake()
777    }
778
779    /// Get cached stake for the epoch vote account.
780    pub fn get_epoch_stake_for_vote_account(&self, pubkey: &'a Pubkey) -> u64 {
781        self.environment_config
782            .epoch_stake_callback
783            .get_epoch_stake_for_vote_account(pubkey)
784    }
785
786    pub fn is_precompile(&self, pubkey: &Pubkey) -> bool {
787        self.environment_config
788            .epoch_stake_callback
789            .is_precompile(pubkey)
790    }
791
792    /// Get the current instruction's [`ABI`].
793    pub fn abi(&self) -> ABI {
794        self.transaction_context
795            .get_current_instruction_context()
796            .and_then(|instruction_context| {
797                let owner_id = instruction_context.get_program_owner();
798                debug_assert!(owner_id.is_ok());
799                owner_id
800            })
801            .map(|owner_id| ABI::resolve(&owner_id))
802            .unwrap_or(ABI::V1)
803    }
804
805    /// Insert a VM register trace
806    pub(crate) fn insert_register_trace(&mut self, register_trace: Vec<[u64; 12]>) {
807        if register_trace.is_empty() {
808            return;
809        }
810        let Ok(instruction_context) = self.transaction_context.get_current_instruction_context()
811        else {
812            return;
813        };
814        self.register_traces
815            .push((instruction_context.get_index_in_trace(), register_trace));
816    }
817
818    /// Iterates over all VM register traces (including CPI)
819    pub fn iterate_vm_traces(
820        &self,
821        callback: &dyn Fn(InstructionContext, &Executable, RegisterTrace),
822    ) {
823        for (index_in_trace, register_trace) in &self.register_traces {
824            let Ok(instruction_context) = self
825                .transaction_context
826                .get_instruction_context_at_index_in_trace(*index_in_trace)
827            else {
828                continue;
829            };
830            let Ok(program_id) = instruction_context.get_program_key() else {
831                continue;
832            };
833            let Some(entry) = self.program_cache_for_tx_batch.find(program_id) else {
834                continue;
835            };
836            let ProgramCacheEntryType::Loaded(ref executable) = entry.program else {
837                continue;
838            };
839            callback(instruction_context, executable, register_trace.as_slice());
840        }
841    }
842}
843
844#[cfg(feature = "dev-context-only-utils")]
845#[macro_export]
846macro_rules! with_mock_invoke_context_with_feature_set {
847    (
848        $invoke_context:ident,
849        $transaction_context:ident,
850        $feature_set:ident,
851        $top_level_instructions:literal,
852        $transaction_accounts:expr,
853        $all_accounts:expr $(,)?
854    ) => {
855        use {
856            solana_svm_callback::InvokeContextCallback,
857            solana_svm_log_collector::LogCollector,
858            $crate::{
859                __private::{
860                    ComputeMeter, DropOnBailOut, Hash, ReadableAccount, Rent, TransactionContext,
861                },
862                execution_budget::{SVMTransactionExecutionBudget, SVMTransactionExecutionCost},
863                invoke_context::{EnvironmentConfig, InvokeContext},
864                program_cache::{
865                    env::ProgramRuntimeEnvironments, tx_batch::ProgramCacheForTxBatch,
866                },
867                sysvar_cache::SysvarCache,
868            },
869        };
870
871        struct MockInvokeContextCallback {}
872        impl InvokeContextCallback for MockInvokeContextCallback {}
873
874        let compute_budget = SVMTransactionExecutionBudget::new_with_defaults(
875            $feature_set.raise_cpi_nesting_limit_to_8,
876        );
877        let mut sysvar_cache = SysvarCache::default();
878        sysvar_cache.fill_missing_entries(|pubkey, callback| {
879            for (key, account) in $all_accounts.iter() {
880                if key == pubkey {
881                    callback(account.data());
882                }
883            }
884        });
885        let mut $transaction_context = TransactionContext::new_with_feature_flags(
886            $transaction_accounts,
887            Rent::default(),
888            compute_budget.max_instruction_stack_depth,
889            compute_budget.max_instruction_trace_length,
890            $top_level_instructions,
891            ComputeMeter::new(compute_budget.compute_unit_limit),
892            DropOnBailOut::Disabled,
893        );
894        let program_runtime_environments = ProgramRuntimeEnvironments::mock();
895        let environment_config = EnvironmentConfig::new(
896            Hash::default(),
897            0,
898            &MockInvokeContextCallback {},
899            $feature_set,
900            &program_runtime_environments,
901            &sysvar_cache,
902        );
903        let mut program_cache_for_tx_batch = ProgramCacheForTxBatch::default();
904        let mut $invoke_context = InvokeContext::new(
905            &mut $transaction_context,
906            &mut program_cache_for_tx_batch,
907            environment_config,
908            Some(LogCollector::new_ref()),
909            compute_budget,
910            SVMTransactionExecutionCost::default(),
911        );
912    };
913    (
914        $invoke_context:ident,
915        $transaction_context:ident,
916        $feature_set:ident,
917        $top_level_instructions:literal,
918        $transaction_accounts:expr $(,)?
919    ) => {
920        let transaction_accounts: Vec<(solana_pubkey::Pubkey, solana_account::AccountSharedData)> =
921            $transaction_accounts;
922        $crate::with_mock_invoke_context_with_feature_set!(
923            $invoke_context,
924            $transaction_context,
925            $feature_set,
926            $top_level_instructions,
927            transaction_accounts,
928            &transaction_accounts
929        );
930    };
931    (
932        $invoke_context:ident,
933        $transaction_context:ident,
934        $feature_set:ident,
935        $transaction_accounts:expr $(,)?
936    ) => {
937        $crate::with_mock_invoke_context_with_feature_set!(
938            $invoke_context,
939            $transaction_context,
940            $feature_set,
941            1,
942            $transaction_accounts
943        );
944    };
945}
946
947#[cfg(feature = "dev-context-only-utils")]
948#[macro_export]
949macro_rules! with_mock_invoke_context {
950    (
951        $invoke_context:ident,
952        $transaction_context:ident,
953        $top_level_instructions:literal,
954        $transaction_accounts:expr $(,)?
955    ) => {
956        let feature_set = &solana_svm_feature_set::SVMFeatureSet::default();
957        $crate::with_mock_invoke_context_with_feature_set!(
958            $invoke_context,
959            $transaction_context,
960            feature_set,
961            $top_level_instructions,
962            $transaction_accounts
963        )
964    };
965    (
966        $invoke_context:ident,
967        $transaction_context:ident,
968        $transaction_accounts:expr $(,)?
969    ) => {
970        with_mock_invoke_context!(
971            $invoke_context,
972            $transaction_context,
973            1,
974            $transaction_accounts
975        );
976    };
977}
978
979#[cfg(feature = "dev-context-only-utils")]
980pub fn mock_compile_message<A>(
981    instruction: &Instruction,
982    accounts: &[(Pubkey, A)],
983    program_id: &Pubkey,
984    loader_key: &Pubkey,
985) -> (SanitizedMessage, Vec<(Pubkey, AccountSharedData)>)
986where
987    AccountSharedData: From<A>,
988    A: Clone,
989{
990    let message = Message::new(std::slice::from_ref(instruction), None);
991    let transaction_accounts: Vec<_> = message
992        .account_keys
993        .iter()
994        .map(|key| {
995            let account = accounts
996                .iter()
997                .find(|(k, _)| k == key)
998                .map(|(_, a)| AccountSharedData::from(a.clone()))
999                .unwrap_or_else(|| {
1000                    if key == program_id {
1001                        let mut account = AccountSharedData::empty(0, loader_key);
1002                        account.set_executable(true);
1003                        account
1004                    } else {
1005                        AccountSharedData::default()
1006                    }
1007                });
1008            (*key, account)
1009        })
1010        .collect();
1011
1012    let sanitized_message = SanitizedMessage::Legacy(LegacyMessage::new(message, &HashSet::new()));
1013
1014    (sanitized_message, transaction_accounts)
1015}
1016
1017#[cfg(feature = "dev-context-only-utils")]
1018pub fn mock_process_instruction_with_feature_set<
1019    F: FnMut(&mut InvokeContext),
1020    G: FnMut(&mut InvokeContext),
1021>(
1022    program_id: &Pubkey,
1023    instruction_data: &[u8],
1024    mut accounts: Vec<KeyedAccountSharedData>,
1025    instruction_account_metas: Vec<AccountMeta>,
1026    expected_result: Result<(), InstructionError>,
1027    builtin: BuiltinFunctionRegisterer,
1028    mut pre_adjustments: F,
1029    mut post_adjustments: G,
1030    feature_set: &SVMFeatureSet,
1031) -> Vec<AccountSharedData> {
1032    let original_len = accounts.len();
1033    if !accounts
1034        .iter()
1035        .any(|(key, _)| *key == sysvar::epoch_schedule::id())
1036    {
1037        let account = AccountSharedData::new_data_with_space(
1038            1,
1039            &EpochSchedule::default(),
1040            solana_epoch_schedule::SIZE,
1041            &sysvar::id(),
1042        )
1043        .unwrap();
1044        accounts.push((sysvar::epoch_schedule::id(), account));
1045    }
1046
1047    let instruction =
1048        Instruction::new_with_bytes(*program_id, instruction_data, instruction_account_metas);
1049    let (sanitized_message, transaction_accounts) =
1050        mock_compile_message(&instruction, &accounts, program_id, &native_loader::id());
1051
1052    let program_owner = accounts
1053        .iter()
1054        .find(|(key, _)| key == program_id)
1055        .map(|(_, acct)| *acct.owner())
1056        .unwrap_or_else(native_loader::id);
1057    let is_builtin = native_loader::check_id(&program_owner);
1058
1059    with_mock_invoke_context_with_feature_set!(
1060        invoke_context,
1061        transaction_context,
1062        feature_set,
1063        1,
1064        transaction_accounts,
1065        &accounts
1066    );
1067
1068    let mut program_cache_for_tx_batch = ProgramCacheForTxBatch::default();
1069    program_cache_for_tx_batch.replenish(
1070        if is_builtin {
1071            *program_id
1072        } else {
1073            program_owner
1074        },
1075        Arc::new(ProgramCacheEntry::new_builtin(builtin)),
1076    );
1077    program_cache_for_tx_batch.set_slot_for_tests(
1078        invoke_context
1079            .environment_config
1080            .sysvar_cache()
1081            .get_clock()
1082            .map(|clock| clock.slot)
1083            .unwrap_or(1),
1084    );
1085    invoke_context.program_cache_for_tx_batch = &mut program_cache_for_tx_batch;
1086
1087    pre_adjustments(&mut invoke_context);
1088
1089    invoke_context
1090        .prepare_top_level_instructions(&sanitized_message)
1091        .unwrap();
1092
1093    let result = invoke_context.process_instruction(&mut 0, &mut ExecuteTimings::default());
1094    assert_eq!(result, expected_result);
1095    post_adjustments(&mut invoke_context);
1096
1097    let txn_result_keys: Vec<_> = (0..transaction_context.get_number_of_accounts())
1098        .map(|i| *transaction_context.get_key_of_account_at_index(i).unwrap())
1099        .collect();
1100    let txn_result_accounts = transaction_context.deconstruct_without_keys().unwrap();
1101    let txn_result_map = txn_result_keys
1102        .into_iter()
1103        .zip(txn_result_accounts)
1104        .collect::<HashMap<Pubkey, AccountSharedData>>();
1105
1106    accounts
1107        .into_iter()
1108        .take(original_len)
1109        .map(|(key, original)| txn_result_map.get(&key).cloned().unwrap_or(original))
1110        .collect()
1111}
1112
1113#[cfg(feature = "dev-context-only-utils")]
1114pub fn mock_process_instruction<F: FnMut(&mut InvokeContext), G: FnMut(&mut InvokeContext)>(
1115    program_id: &Pubkey,
1116    instruction_data: &[u8],
1117    accounts: Vec<KeyedAccountSharedData>,
1118    instruction_account_metas: Vec<AccountMeta>,
1119    expected_result: Result<(), InstructionError>,
1120    builtin: BuiltinFunctionRegisterer,
1121    pre_adjustments: F,
1122    post_adjustments: G,
1123) -> Vec<AccountSharedData> {
1124    mock_process_instruction_with_feature_set(
1125        program_id,
1126        instruction_data,
1127        accounts,
1128        instruction_account_metas,
1129        expected_result,
1130        builtin,
1131        pre_adjustments,
1132        post_adjustments,
1133        &SVMFeatureSet::all_enabled(),
1134    )
1135}
1136
1137#[cfg(test)]
1138mod tests {
1139    use {
1140        super::*,
1141        crate::execution_budget::{
1142            DEFAULT_INSTRUCTION_COMPUTE_UNIT_LIMIT, MAX_INSTRUCTION_STACK_DEPTH,
1143            MAX_INSTRUCTION_STACK_DEPTH_SIMD_0268,
1144        },
1145        openssl::{
1146            ec::{EcGroup, EcKey},
1147            nid::Nid,
1148        },
1149        solana_account::{Account, ReadableAccount},
1150        solana_ed25519_program::new_ed25519_instruction_with_signature,
1151        solana_keypair::{Address, Keypair},
1152        solana_message::AccountKeys,
1153        solana_precompile_error::PrecompileError,
1154        solana_rent::Rent,
1155        solana_sbpf::program::BuiltinFunctionDefinition,
1156        solana_sdk_ids::{ed25519_program, secp256k1_program, system_program},
1157        solana_secp256k1_program::{
1158            eth_address_from_pubkey, new_secp256k1_instruction_with_signature,
1159        },
1160        solana_secp256r1_program::{new_secp256r1_instruction_with_signature, sign_message},
1161        solana_signer::Signer,
1162        solana_svm_feature_set::SVMFeatureSet,
1163        solana_transaction::{Transaction, sanitized::SanitizedTransaction},
1164        solana_transaction_context::{MAX_ACCOUNTS_PER_INSTRUCTION, MAX_ACCOUNTS_PER_TRANSACTION},
1165        test_case::test_case,
1166    };
1167
1168    #[derive(Debug, wincode::SchemaRead, wincode::SchemaWrite)]
1169    enum MockInstruction {
1170        NoopSuccess,
1171        NoopFail,
1172        ModifyOwned,
1173        ModifyNotOwned,
1174        ModifyReadonly,
1175        UnbalancedPush,
1176        UnbalancedPop,
1177        ConsumeComputeUnits {
1178            compute_units_to_consume: u64,
1179            desired_result: Result<(), InstructionError>,
1180        },
1181        Resize {
1182            new_len: u64,
1183        },
1184    }
1185
1186    const MOCK_BUILTIN_COMPUTE_UNIT_COST: u64 = 1;
1187
1188    declare_process_instruction!(
1189        MockBuiltin,
1190        MOCK_BUILTIN_COMPUTE_UNIT_COST,
1191        |invoke_context| {
1192            let transaction_context = &invoke_context.transaction_context;
1193            let instruction_context = transaction_context.get_current_instruction_context()?;
1194            let instruction_data = instruction_context.get_instruction_data();
1195            let program_id = instruction_context.get_program_key()?;
1196            let instruction_accounts = (0..4)
1197                .map(|instruction_account_index| {
1198                    InstructionAccount::new(instruction_account_index, false, false)
1199                })
1200                .collect::<Vec<_>>();
1201            assert_eq!(
1202                program_id,
1203                instruction_context
1204                    .try_borrow_instruction_account(0)?
1205                    .get_owner()
1206            );
1207            assert_ne!(
1208                instruction_context
1209                    .try_borrow_instruction_account(1)?
1210                    .get_owner(),
1211                instruction_context.get_key_of_instruction_account(0)?
1212            );
1213
1214            if let Ok(instruction) = wincode::deserialize(instruction_data) {
1215                match instruction {
1216                    MockInstruction::NoopSuccess => (),
1217                    MockInstruction::NoopFail => return Err(InstructionError::GenericError),
1218                    MockInstruction::ModifyOwned => instruction_context
1219                        .try_borrow_instruction_account(0)?
1220                        .set_data_from_slice(&[1])?,
1221                    MockInstruction::ModifyNotOwned => instruction_context
1222                        .try_borrow_instruction_account(1)?
1223                        .set_data_from_slice(&[1])?,
1224                    MockInstruction::ModifyReadonly => instruction_context
1225                        .try_borrow_instruction_account(2)?
1226                        .set_data_from_slice(&[1])?,
1227                    MockInstruction::UnbalancedPush => {
1228                        instruction_context
1229                            .try_borrow_instruction_account(0)?
1230                            .checked_add_lamports(1)?;
1231                        let program_id = *transaction_context.get_key_of_account_at_index(3)?;
1232                        let metas = vec![
1233                            AccountMeta::new_readonly(
1234                                *transaction_context.get_key_of_account_at_index(0)?,
1235                                false,
1236                            ),
1237                            AccountMeta::new_readonly(
1238                                *transaction_context.get_key_of_account_at_index(1)?,
1239                                false,
1240                            ),
1241                        ];
1242                        let inner_instruction = Instruction::new_with_wincode(
1243                            program_id,
1244                            &MockInstruction::NoopSuccess,
1245                            metas,
1246                        );
1247                        invoke_context
1248                            .transaction_context
1249                            .configure_top_level_instruction_for_tests(
1250                                3,
1251                                instruction_accounts,
1252                                vec![],
1253                            )
1254                            .unwrap();
1255                        let result = invoke_context.push();
1256                        assert_eq!(result, Err(InstructionError::UnbalancedInstruction));
1257                        result?;
1258                        invoke_context
1259                            .native_invoke_signed(inner_instruction, &[])
1260                            .and(invoke_context.pop())?;
1261                    }
1262                    MockInstruction::UnbalancedPop => instruction_context
1263                        .try_borrow_instruction_account(0)?
1264                        .checked_add_lamports(1)?,
1265                    MockInstruction::ConsumeComputeUnits {
1266                        compute_units_to_consume,
1267                        desired_result,
1268                    } => {
1269                        invoke_context
1270                            .consume_checked(compute_units_to_consume)
1271                            .map_err(|_| InstructionError::ComputationalBudgetExceeded)?;
1272                        return desired_result;
1273                    }
1274                    MockInstruction::Resize { new_len } => instruction_context
1275                        .try_borrow_instruction_account(0)?
1276                        .set_data_from_slice(&vec![0; new_len as usize])?,
1277                }
1278            } else {
1279                return Err(InstructionError::InvalidInstructionData);
1280            }
1281            Ok(())
1282        }
1283    );
1284
1285    #[test_case(false; "SIMD-0268 disabled")]
1286    #[test_case(true; "SIMD-0268 enabled")]
1287    fn test_instruction_stack_height(simd_0268_active: bool) {
1288        let feature_set = &SVMFeatureSet {
1289            raise_cpi_nesting_limit_to_8: simd_0268_active,
1290            ..SVMFeatureSet::all_enabled()
1291        };
1292        let max_depth = SVMTransactionExecutionBudget::new_with_defaults(simd_0268_active)
1293            .max_instruction_stack_depth;
1294        assert_eq!(
1295            max_depth,
1296            if simd_0268_active {
1297                MAX_INSTRUCTION_STACK_DEPTH_SIMD_0268
1298            } else {
1299                MAX_INSTRUCTION_STACK_DEPTH
1300            },
1301        );
1302
1303        // Set up max_depth + 1 accounts (one extra to trigger the failing push)
1304        // and a matching program account for each.
1305        let mut invoke_stack = vec![];
1306        let mut transaction_accounts = vec![];
1307        let mut instruction_accounts = vec![];
1308        for index in 0..max_depth.saturating_add(1) {
1309            let program_id = solana_pubkey::new_rand();
1310            invoke_stack.push(program_id);
1311            transaction_accounts.push((
1312                solana_pubkey::new_rand(),
1313                AccountSharedData::new_with_data(1, vec![0; 1], &program_id),
1314            ));
1315            instruction_accounts.push(InstructionAccount::new(
1316                index as IndexOfAccount,
1317                false,
1318                true,
1319            ));
1320        }
1321
1322        // Append program accounts after the regular accounts so that
1323        // `first_program_account + depth` indexes the right program.
1324        let first_program_account = transaction_accounts.len();
1325        for (index, program_id) in invoke_stack.iter().enumerate() {
1326            transaction_accounts.push((
1327                *program_id,
1328                AccountSharedData::new_with_data(1, vec![0; 1], &solana_pubkey::Pubkey::default()),
1329            ));
1330            instruction_accounts.push(InstructionAccount::new(
1331                index as IndexOfAccount,
1332                false,
1333                false,
1334            ));
1335        }
1336        with_mock_invoke_context_with_feature_set!(
1337            invoke_context,
1338            transaction_context,
1339            feature_set,
1340            transaction_accounts,
1341        );
1342
1343        // Each push must succeed and the stack height must track.
1344        for depth in 0..max_depth {
1345            assert_eq!(invoke_context.get_stack_height(), depth);
1346            invoke_context
1347                .transaction_context
1348                .configure_top_level_instruction_for_tests(
1349                    (first_program_account.saturating_add(depth)) as IndexOfAccount,
1350                    instruction_accounts.clone(),
1351                    vec![],
1352                )
1353                .unwrap();
1354            assert!(
1355                invoke_context.push().is_ok(),
1356                "push at depth {depth} should succeed (max_depth={max_depth})",
1357            );
1358        }
1359
1360        // At exactly max_depth, one more push must fail with CallDepth.
1361        assert_eq!(invoke_context.get_stack_height(), max_depth);
1362        invoke_context
1363            .transaction_context
1364            .configure_top_level_instruction_for_tests(
1365                (first_program_account.saturating_add(max_depth)) as IndexOfAccount,
1366                instruction_accounts.clone(),
1367                vec![],
1368            )
1369            .unwrap();
1370        assert_eq!(invoke_context.push(), Err(InstructionError::CallDepth),);
1371
1372        // Stack height must not have changed after the rejected push.
1373        assert_eq!(invoke_context.get_stack_height(), max_depth);
1374    }
1375
1376    #[test_case(false; "simd_582_disabled")]
1377    #[test_case(true; "simd_582_enabled")]
1378    fn test_max_instruction_trace_length_top_level(fail_early: bool) {
1379        const MAX_INSTRUCTIONS: usize = 8;
1380        let mut transaction_context = TransactionContext::new(
1381            vec![(
1382                Pubkey::new_unique(),
1383                AccountSharedData::new_with_data(1, vec![0; 1], &Pubkey::new_unique()),
1384            )],
1385            Rent::default(),
1386            1,
1387            MAX_INSTRUCTIONS,
1388            MAX_INSTRUCTIONS,
1389        );
1390        for _ in 0..MAX_INSTRUCTIONS {
1391            transaction_context.push(fail_early).unwrap();
1392            transaction_context
1393                .configure_top_level_instruction_for_tests(
1394                    0,
1395                    vec![InstructionAccount::new(0, false, false)],
1396                    vec![],
1397                )
1398                .unwrap();
1399            transaction_context.pop().unwrap();
1400        }
1401
1402        assert_eq!(
1403            transaction_context.push(fail_early),
1404            Err(InstructionError::MaxInstructionTraceLengthExceeded)
1405        );
1406    }
1407
1408    #[test_case(false; "simd_582_disabled")]
1409    #[test_case(true; "simd_582_enabled")]
1410    fn test_max_instruction_trace_length_cpi(fail_early: bool) {
1411        // Hitting the limit with CPIs
1412        const MAX_INSTRUCTIONS: usize = 8;
1413        let mut transaction_context = TransactionContext::new(
1414            vec![(
1415                Pubkey::new_unique(),
1416                AccountSharedData::new_with_data(1, vec![0; 1], &Pubkey::new_unique()),
1417            )],
1418            Rent::default(),
1419            256,
1420            MAX_INSTRUCTIONS,
1421            2,
1422        );
1423        let num_transaction_accounts = usize::from(transaction_context.get_number_of_accounts());
1424
1425        transaction_context
1426            .configure_instruction_at_index(
1427                0,
1428                0,
1429                vec![InstructionAccount::new(0, false, false)],
1430                vec![u8::MAX; num_transaction_accounts],
1431                Cow::Owned(Vec::new()),
1432                None,
1433            )
1434            .unwrap();
1435
1436        transaction_context
1437            .configure_instruction_at_index(
1438                1,
1439                0,
1440                vec![InstructionAccount::new(0, false, false)],
1441                vec![u8::MAX; num_transaction_accounts],
1442                Cow::Owned(Vec::new()),
1443                None,
1444            )
1445            .unwrap();
1446
1447        for ix_in_trace in (2..).take(MAX_INSTRUCTIONS) {
1448            let result = transaction_context.push(fail_early);
1449            if ix_in_trace > MAX_INSTRUCTIONS && fail_early {
1450                assert_eq!(
1451                    result,
1452                    Err(InstructionError::MaxInstructionTraceLengthExceeded)
1453                );
1454            } else {
1455                assert!(result.is_ok());
1456            }
1457
1458            transaction_context
1459                .configure_next_cpi_for_tests(
1460                    0,
1461                    vec![InstructionAccount::new(0, false, false)],
1462                    Vec::new(),
1463                )
1464                .unwrap();
1465        }
1466
1467        if !fail_early {
1468            assert_eq!(
1469                transaction_context.push(false),
1470                Err(InstructionError::MaxInstructionTraceLengthExceeded)
1471            );
1472        }
1473    }
1474
1475    #[test_case(MockInstruction::NoopSuccess, Ok(()); "NoopSuccess")]
1476    #[test_case(MockInstruction::NoopFail, Err(InstructionError::GenericError); "NoopFail")]
1477    #[test_case(MockInstruction::ModifyOwned, Ok(()); "ModifyOwned")]
1478    #[test_case(MockInstruction::ModifyNotOwned, Err(InstructionError::ExternalAccountDataModified); "ModifyNotOwned")]
1479    #[test_case(MockInstruction::ModifyReadonly, Err(InstructionError::ReadonlyDataModified); "ModifyReadonly")]
1480    #[test_case(MockInstruction::UnbalancedPush, Err(InstructionError::UnbalancedInstruction); "UnbalancedPush")]
1481    #[test_case(MockInstruction::UnbalancedPop, Err(InstructionError::UnbalancedInstruction); "UnbalancedPop")]
1482    fn test_process_instruction_account_modifications(
1483        instruction: MockInstruction,
1484        expected_result: Result<(), InstructionError>,
1485    ) {
1486        let callee_program_id = solana_pubkey::new_rand();
1487        let owned_account = AccountSharedData::new_with_data(42, vec![0; 1], &callee_program_id);
1488        let not_owned_account =
1489            AccountSharedData::new_with_data(84, vec![0; 1], &solana_pubkey::new_rand());
1490        let readonly_account =
1491            AccountSharedData::new_with_data(168, vec![0; 1], &solana_pubkey::new_rand());
1492        let loader_account = AccountSharedData::new_with_data(0, vec![0; 1], &native_loader::id());
1493        let mut program_account =
1494            AccountSharedData::new_with_data(1, vec![0; 1], &native_loader::id());
1495        program_account.set_executable(true);
1496        let transaction_accounts = vec![
1497            (solana_pubkey::new_rand(), owned_account),
1498            (solana_pubkey::new_rand(), not_owned_account),
1499            (solana_pubkey::new_rand(), readonly_account),
1500            (callee_program_id, program_account),
1501            (solana_pubkey::new_rand(), loader_account),
1502        ];
1503        let metas = vec![
1504            AccountMeta::new(transaction_accounts.first().unwrap().0, false),
1505            AccountMeta::new(transaction_accounts.get(1).unwrap().0, false),
1506            AccountMeta::new_readonly(transaction_accounts.get(2).unwrap().0, false),
1507        ];
1508        let instruction_accounts = (0..4)
1509            .map(|instruction_account_index| {
1510                InstructionAccount::new(
1511                    instruction_account_index,
1512                    false,
1513                    instruction_account_index < 2,
1514                )
1515            })
1516            .collect::<Vec<_>>();
1517        with_mock_invoke_context!(invoke_context, transaction_context, transaction_accounts);
1518        let mut program_cache_for_tx_batch = ProgramCacheForTxBatch::default();
1519        program_cache_for_tx_batch.replenish(
1520            callee_program_id,
1521            Arc::new(ProgramCacheEntry::new_builtin(MockBuiltin::register)),
1522        );
1523        invoke_context.program_cache_for_tx_batch = &mut program_cache_for_tx_batch;
1524
1525        // Account modification tests
1526        invoke_context
1527            .transaction_context
1528            .configure_top_level_instruction_for_tests(4, instruction_accounts, vec![])
1529            .unwrap();
1530        invoke_context.push().unwrap();
1531        let inner_instruction =
1532            Instruction::new_with_wincode(callee_program_id, &instruction, metas);
1533        let result = invoke_context
1534            .native_invoke_signed(inner_instruction, &[])
1535            .and(invoke_context.pop());
1536        assert_eq!(result, expected_result);
1537    }
1538
1539    #[test_case(Ok(()); "Ok")]
1540    #[test_case(Err(InstructionError::GenericError); "GenericError")]
1541    fn test_process_instruction_compute_unit_consumption(
1542        expected_result: Result<(), InstructionError>,
1543    ) {
1544        let callee_program_id = solana_pubkey::new_rand();
1545        let owned_account = AccountSharedData::new_with_data(42, vec![0; 1], &callee_program_id);
1546        let not_owned_account =
1547            AccountSharedData::new_with_data(84, vec![0; 1], &solana_pubkey::new_rand());
1548        let readonly_account =
1549            AccountSharedData::new_with_data(168, vec![0; 1], &solana_pubkey::new_rand());
1550        let loader_account = AccountSharedData::new_with_data(0, vec![0; 1], &native_loader::id());
1551        let mut program_account =
1552            AccountSharedData::new_with_data(1, vec![0; 1], &native_loader::id());
1553        program_account.set_executable(true);
1554        let transaction_accounts = vec![
1555            (solana_pubkey::new_rand(), owned_account),
1556            (solana_pubkey::new_rand(), not_owned_account),
1557            (solana_pubkey::new_rand(), readonly_account),
1558            (callee_program_id, program_account),
1559            (solana_pubkey::new_rand(), loader_account),
1560        ];
1561        let metas = vec![
1562            AccountMeta::new(transaction_accounts.first().unwrap().0, false),
1563            AccountMeta::new(transaction_accounts.get(1).unwrap().0, false),
1564            AccountMeta::new_readonly(transaction_accounts.get(2).unwrap().0, false),
1565        ];
1566        let instruction_accounts = (0..4)
1567            .map(|instruction_account_index| {
1568                InstructionAccount::new(
1569                    instruction_account_index,
1570                    false,
1571                    instruction_account_index < 2,
1572                )
1573            })
1574            .collect::<Vec<_>>();
1575        with_mock_invoke_context!(invoke_context, transaction_context, transaction_accounts);
1576        let mut program_cache_for_tx_batch = ProgramCacheForTxBatch::default();
1577        program_cache_for_tx_batch.replenish(
1578            callee_program_id,
1579            Arc::new(ProgramCacheEntry::new_builtin(MockBuiltin::register)),
1580        );
1581        invoke_context.program_cache_for_tx_batch = &mut program_cache_for_tx_batch;
1582
1583        // Compute unit consumption tests
1584        let compute_units_to_consume = 10;
1585        invoke_context
1586            .transaction_context
1587            .configure_top_level_instruction_for_tests(4, instruction_accounts, vec![])
1588            .unwrap();
1589        invoke_context.push().unwrap();
1590        let inner_instruction = Instruction::new_with_wincode(
1591            callee_program_id,
1592            &MockInstruction::ConsumeComputeUnits {
1593                compute_units_to_consume,
1594                desired_result: expected_result.clone(),
1595            },
1596            metas,
1597        );
1598
1599        invoke_context
1600            .build_instruction_frame(inner_instruction)
1601            .unwrap();
1602        invoke_context.verify_instruction_accounts(&[]).unwrap();
1603
1604        let mut compute_units_consumed = 0;
1605        let result = invoke_context
1606            .process_instruction(&mut compute_units_consumed, &mut ExecuteTimings::default());
1607
1608        // Because the instruction had compute cost > 0, then regardless of the execution result,
1609        // the number of compute units consumed should be a non-default which is something greater
1610        // than zero.
1611        assert!(compute_units_consumed > 0);
1612        assert_eq!(
1613            compute_units_consumed,
1614            compute_units_to_consume.saturating_add(MOCK_BUILTIN_COMPUTE_UNIT_COST),
1615        );
1616        assert_eq!(result, expected_result);
1617
1618        invoke_context.pop().unwrap();
1619    }
1620
1621    #[test]
1622    fn test_invoke_context_compute_budget() {
1623        let transaction_accounts = vec![(solana_pubkey::new_rand(), AccountSharedData::default())];
1624        let execution_budget = SVMTransactionExecutionBudget {
1625            compute_unit_limit: u64::from(DEFAULT_INSTRUCTION_COMPUTE_UNIT_LIMIT),
1626            ..SVMTransactionExecutionBudget::default()
1627        };
1628
1629        with_mock_invoke_context!(invoke_context, transaction_context, transaction_accounts);
1630        invoke_context.compute_budget = execution_budget;
1631
1632        invoke_context
1633            .transaction_context
1634            .configure_top_level_instruction_for_tests(0, vec![], vec![])
1635            .unwrap();
1636        invoke_context.push().unwrap();
1637        assert_eq!(*invoke_context.get_compute_budget(), execution_budget);
1638        invoke_context.pop().unwrap();
1639    }
1640
1641    #[test_case(0; "Resize the account to *the same size*, so not consuming any additional size")]
1642    #[test_case(1; "Resize the account larger")]
1643    #[test_case(-1; "Resize the account smaller")]
1644    fn test_process_instruction_accounts_resize_delta(resize_delta: i64) {
1645        let program_key = Pubkey::new_unique();
1646        let user_account_data_len = 123usize;
1647        let user_account =
1648            AccountSharedData::new_with_data(100, vec![0; user_account_data_len], &program_key);
1649        let dummy_account = AccountSharedData::empty(10, &program_key);
1650        let mut program_account =
1651            AccountSharedData::new_with_data(500, vec![0; 500], &native_loader::id());
1652        program_account.set_executable(true);
1653        let transaction_accounts = vec![
1654            (Pubkey::new_unique(), user_account),
1655            (Pubkey::new_unique(), dummy_account),
1656            (program_key, program_account),
1657        ];
1658        let instruction_accounts = vec![
1659            InstructionAccount::new(0, false, true),
1660            InstructionAccount::new(1, false, false),
1661        ];
1662        with_mock_invoke_context!(invoke_context, transaction_context, transaction_accounts);
1663        let mut program_cache_for_tx_batch = ProgramCacheForTxBatch::default();
1664        program_cache_for_tx_batch.replenish(
1665            program_key,
1666            Arc::new(ProgramCacheEntry::new_builtin(MockBuiltin::register)),
1667        );
1668        invoke_context.program_cache_for_tx_batch = &mut program_cache_for_tx_batch;
1669
1670        let new_len = (user_account_data_len as i64).saturating_add(resize_delta) as u64;
1671        let instruction_data = wincode::serialize(&MockInstruction::Resize { new_len }).unwrap();
1672
1673        invoke_context
1674            .transaction_context
1675            .configure_top_level_instruction_for_tests(2, instruction_accounts, instruction_data)
1676            .unwrap();
1677        let result = invoke_context.process_instruction(&mut 0, &mut ExecuteTimings::default());
1678
1679        assert!(result.is_ok());
1680        assert_eq!(
1681            invoke_context.transaction_context.accounts().resize_delta(),
1682            resize_delta
1683        );
1684    }
1685
1686    #[test]
1687    fn test_prepare_instruction_maximum_accounts() {
1688        const MAX_ACCOUNTS_REFERENCED: usize = MAX_ACCOUNTS_PER_INSTRUCTION;
1689        let mut transaction_accounts: Vec<KeyedAccountSharedData> =
1690            Vec::with_capacity(MAX_ACCOUNTS_PER_TRANSACTION);
1691        let mut account_metas: Vec<AccountMeta> = Vec::with_capacity(MAX_ACCOUNTS_REFERENCED);
1692
1693        // Fee-payer
1694        let fee_payer = Keypair::new();
1695        transaction_accounts.push((
1696            fee_payer.pubkey(),
1697            AccountSharedData::new_with_data(1, vec![0; 1], &Pubkey::new_unique()),
1698        ));
1699        account_metas.push(AccountMeta::new(fee_payer.pubkey(), true));
1700
1701        let program_id = Pubkey::new_unique();
1702        let mut program_account =
1703            AccountSharedData::new_with_data(1, vec![0; 1], &Pubkey::new_unique());
1704        program_account.set_executable(true);
1705        transaction_accounts.push((program_id, program_account));
1706        account_metas.push(AccountMeta::new_readonly(program_id, false));
1707
1708        // Reference the maximum number of instruction accounts.
1709        for _ in 2..MAX_ACCOUNTS_REFERENCED {
1710            let key = Pubkey::new_unique();
1711            transaction_accounts.push((
1712                key,
1713                AccountSharedData::new_with_data(1, vec![0; 1], &Pubkey::new_unique()),
1714            ));
1715            account_metas.push(AccountMeta::new_readonly(key, false));
1716        }
1717
1718        with_mock_invoke_context!(invoke_context, transaction_context, 2, transaction_accounts);
1719
1720        let instruction_1 = Instruction::new_with_bytes(program_id, &[20], account_metas.clone());
1721
1722        let instruction_2 = Instruction::new_with_bytes(
1723            program_id,
1724            &[20],
1725            account_metas.iter().rev().cloned().collect(),
1726        );
1727
1728        let transaction = Transaction::new_with_payer(
1729            &[instruction_1.clone(), instruction_2.clone()],
1730            Some(&fee_payer.pubkey()),
1731        );
1732
1733        let sanitized =
1734            SanitizedTransaction::try_from_legacy_transaction(transaction, &HashSet::new())
1735                .unwrap();
1736
1737        fn test_case_1(invoke_context: &InvokeContext) {
1738            let instruction_context = invoke_context
1739                .transaction_context
1740                .get_next_instruction_context()
1741                .unwrap();
1742            for index_in_instruction in 0..MAX_ACCOUNTS_REFERENCED as IndexOfAccount {
1743                let index_in_transaction = instruction_context
1744                    .get_index_of_instruction_account_in_transaction(index_in_instruction)
1745                    .unwrap();
1746                let other_ix_index = instruction_context
1747                    .get_index_of_account_in_instruction(index_in_transaction)
1748                    .unwrap();
1749                assert_eq!(index_in_instruction, index_in_transaction);
1750                assert_eq!(index_in_instruction, other_ix_index);
1751            }
1752        }
1753
1754        fn test_case_2(invoke_context: &InvokeContext) {
1755            let instruction_context = invoke_context
1756                .transaction_context
1757                .get_next_instruction_context()
1758                .unwrap();
1759            for index_in_instruction in 0..MAX_ACCOUNTS_REFERENCED as IndexOfAccount {
1760                let index_in_transaction = instruction_context
1761                    .get_index_of_instruction_account_in_transaction(index_in_instruction)
1762                    .unwrap();
1763                let other_ix_index = instruction_context
1764                    .get_index_of_account_in_instruction(index_in_transaction)
1765                    .unwrap();
1766                assert_eq!(
1767                    index_in_transaction,
1768                    (MAX_ACCOUNTS_REFERENCED as u16)
1769                        .saturating_sub(index_in_instruction)
1770                        .saturating_sub(1)
1771                );
1772                assert_eq!(index_in_instruction, other_ix_index);
1773            }
1774        }
1775
1776        invoke_context
1777            .prepare_top_level_instructions(&sanitized)
1778            .unwrap();
1779
1780        test_case_1(&invoke_context);
1781
1782        invoke_context.transaction_context.push(true).unwrap();
1783        invoke_context.transaction_context.pop().unwrap();
1784
1785        test_case_2(&invoke_context);
1786
1787        invoke_context.transaction_context.push(true).unwrap();
1788        invoke_context
1789            .build_instruction_frame(instruction_1)
1790            .unwrap();
1791        invoke_context
1792            .verify_instruction_accounts(&[fee_payer.pubkey()])
1793            .unwrap();
1794        test_case_1(&invoke_context);
1795
1796        invoke_context.transaction_context.push(true).unwrap();
1797        invoke_context
1798            .build_instruction_frame(instruction_2)
1799            .unwrap();
1800        invoke_context
1801            .verify_instruction_accounts(&[fee_payer.pubkey()])
1802            .unwrap();
1803        test_case_2(&invoke_context);
1804    }
1805
1806    #[test]
1807    fn test_duplicated_accounts() {
1808        let mut transaction_accounts: Vec<KeyedAccountSharedData> =
1809            Vec::with_capacity(MAX_ACCOUNTS_PER_TRANSACTION);
1810        let mut account_metas: Vec<AccountMeta> =
1811            Vec::with_capacity(MAX_ACCOUNTS_PER_INSTRUCTION.saturating_sub(1));
1812
1813        // Fee-payer
1814        let fee_payer = Keypair::new();
1815        transaction_accounts.push((
1816            fee_payer.pubkey(),
1817            AccountSharedData::new_with_data(1, vec![0; 1], &Pubkey::new_unique()),
1818        ));
1819        account_metas.push(AccountMeta::new(fee_payer.pubkey(), true));
1820
1821        let program_id = Pubkey::new_unique();
1822        let mut program_account =
1823            AccountSharedData::new_with_data(1, vec![0; 1], &Pubkey::new_unique());
1824        program_account.set_executable(true);
1825        transaction_accounts.push((program_id, program_account));
1826        account_metas.push(AccountMeta::new_readonly(program_id, false));
1827
1828        for i in 2..account_metas.capacity() {
1829            if i % 2 == 0 {
1830                let key = Pubkey::new_unique();
1831                transaction_accounts.push((
1832                    key,
1833                    AccountSharedData::new_with_data(1, vec![0; 1], &Pubkey::new_unique()),
1834                ));
1835                account_metas.push(AccountMeta::new_readonly(key, false));
1836            } else {
1837                let last_key = transaction_accounts.last().unwrap().0;
1838                account_metas.push(AccountMeta::new_readonly(last_key, false));
1839            }
1840        }
1841
1842        with_mock_invoke_context!(invoke_context, transaction_context, transaction_accounts);
1843
1844        let instruction = Instruction::new_with_bytes(program_id, &[20], account_metas.clone());
1845
1846        let transaction = Transaction::new_with_payer(&[instruction], Some(&fee_payer.pubkey()));
1847
1848        let sanitized =
1849            SanitizedTransaction::try_from_legacy_transaction(transaction, &HashSet::new())
1850                .unwrap();
1851
1852        invoke_context
1853            .prepare_top_level_instructions(&sanitized)
1854            .unwrap();
1855
1856        {
1857            let instruction_context = invoke_context
1858                .transaction_context
1859                .get_next_instruction_context()
1860                .unwrap();
1861            for index_in_instruction in 2..account_metas.len() as IndexOfAccount {
1862                let is_duplicate = instruction_context
1863                    .is_instruction_account_duplicate(index_in_instruction)
1864                    .unwrap();
1865                if index_in_instruction % 2 == 0 {
1866                    assert!(is_duplicate.is_none());
1867                } else {
1868                    assert_eq!(is_duplicate, Some(index_in_instruction.saturating_sub(1)));
1869                }
1870            }
1871        }
1872
1873        invoke_context.transaction_context.push(true).unwrap();
1874
1875        let instruction = Instruction::new_with_bytes(
1876            program_id,
1877            &[20],
1878            account_metas.iter().cloned().rev().collect(),
1879        );
1880
1881        invoke_context.build_instruction_frame(instruction).unwrap();
1882        invoke_context
1883            .verify_instruction_accounts(&[fee_payer.pubkey()])
1884            .unwrap();
1885        let instruction_context = invoke_context
1886            .transaction_context
1887            .get_next_instruction_context()
1888            .unwrap();
1889        for index_in_instruction in 2..account_metas.len().saturating_sub(1) as u16 {
1890            let is_duplicate = instruction_context
1891                .is_instruction_account_duplicate(index_in_instruction)
1892                .unwrap();
1893            if index_in_instruction % 2 == 0 {
1894                assert!(is_duplicate.is_none());
1895            } else {
1896                assert_eq!(is_duplicate, Some(index_in_instruction.saturating_sub(1)));
1897            }
1898        }
1899    }
1900
1901    // Used for native_invoke_signed tests below.
1902    const TEST_CALLER_PROGRAM_ID: Pubkey = Pubkey::new_from_array([1u8; 32]);
1903    const TEST_CALLEE_PROGRAM_ID: Pubkey = Pubkey::new_from_array([2u8; 32]);
1904    const TEST_WRONG_PROGRAM_ID: Pubkey = Pubkey::new_from_array([3u8; 32]);
1905    const TEST_MOCK_EXTRA_KEY: Pubkey = Pubkey::new_from_array([4u8; 32]);
1906    const TEST_ACCOUNT_KEY: Pubkey = Pubkey::new_from_array([5u8; 32]);
1907
1908    /// Runs a `native_invoke_signed` call with the standard test setup and returns
1909    /// the result.
1910    ///
1911    /// Same layout for all tests:
1912    ///   0: target account (writable, signer iff `target_is_signer`)
1913    ///   1: caller program (executable)
1914    ///   2: mock extra (satisfies MockBuiltin's 2-account requirement)
1915    ///   3: callee program (executable)
1916    fn run_native_invoke_signed_test(
1917        target_key: Pubkey,
1918        target_is_signer: bool,
1919        inner_instruction: Instruction,
1920        signer_seeds: &[&[&[u8]]],
1921    ) -> Result<(), InstructionError> {
1922        let target_account = AccountSharedData::empty(100, &TEST_CALLEE_PROGRAM_ID);
1923        let mock_extra_account =
1924            AccountSharedData::new_with_data(0, vec![0; 1], &system_program::id());
1925        let mut caller_program_account =
1926            AccountSharedData::new_with_data(1, vec![0; 1], &native_loader::id());
1927        caller_program_account.set_executable(true);
1928        let mut callee_program_account =
1929            AccountSharedData::new_with_data(1, vec![0; 1], &native_loader::id());
1930        callee_program_account.set_executable(true);
1931        let transaction_accounts = vec![
1932            (target_key, target_account),
1933            (TEST_CALLER_PROGRAM_ID, caller_program_account),
1934            (TEST_MOCK_EXTRA_KEY, mock_extra_account),
1935            (TEST_CALLEE_PROGRAM_ID, callee_program_account),
1936        ];
1937
1938        with_mock_invoke_context!(invoke_context, transaction_context, transaction_accounts);
1939        let mut program_cache_for_tx_batch = ProgramCacheForTxBatch::default();
1940        program_cache_for_tx_batch.replenish(
1941            TEST_CALLEE_PROGRAM_ID,
1942            Arc::new(ProgramCacheEntry::new_builtin(MockBuiltin::register)),
1943        );
1944        invoke_context.program_cache_for_tx_batch = &mut program_cache_for_tx_batch;
1945
1946        let instruction_accounts = (0..4)
1947            .map(|i| InstructionAccount::new(i, i == 0 && target_is_signer, i < 2))
1948            .collect::<Vec<_>>();
1949        invoke_context
1950            .transaction_context
1951            .configure_top_level_instruction_for_tests(1, instruction_accounts, vec![])
1952            .unwrap();
1953        invoke_context.push().unwrap();
1954
1955        let result = invoke_context.native_invoke_signed(inner_instruction, signer_seeds);
1956        invoke_context.pop().unwrap();
1957        result
1958    }
1959
1960    #[test]
1961    fn test_native_invoke_signed_instruction_account_limit() {
1962        let instruction = Instruction::new_with_wincode(
1963            TEST_CALLEE_PROGRAM_ID,
1964            &MockInstruction::NoopSuccess,
1965            vec![
1966                AccountMeta::new_readonly(TEST_ACCOUNT_KEY, false);
1967                MAX_ACCOUNTS_PER_INSTRUCTION + 1
1968            ],
1969        );
1970        assert_eq!(
1971            run_native_invoke_signed_test(TEST_ACCOUNT_KEY, false, instruction, &[]),
1972            Err(InstructionError::MaxAccountsExceeded),
1973        );
1974    }
1975
1976    // Valid PDA seeds grant signer privilege to the derived address.
1977    #[test]
1978    fn test_native_invoke_signed_with_valid_pda_signer() {
1979        let (pda_key, bump_seed) =
1980            Pubkey::find_program_address(&[b"seed"], &TEST_CALLER_PROGRAM_ID);
1981        let instruction = Instruction::new_with_wincode(
1982            TEST_CALLEE_PROGRAM_ID,
1983            &MockInstruction::NoopSuccess,
1984            vec![
1985                AccountMeta::new(pda_key, true),
1986                AccountMeta::new_readonly(TEST_MOCK_EXTRA_KEY, false),
1987            ],
1988        );
1989        let result =
1990            run_native_invoke_signed_test(pda_key, false, instruction, &[&[b"seed", &[bump_seed]]]);
1991        assert!(
1992            result.is_ok(),
1993            "valid PDA signer should succeed: {result:?}"
1994        );
1995    }
1996
1997    // Oversized seeds (>MAX_SEED_LEN) hit `MaxSeedLengthExceeded`
1998    // (discriminant 0) which the broken `as u64` num-traits conversion
1999    // maps to `Custom(0)`.
2000    #[test]
2001    fn test_native_invoke_signed_with_invalid_seeds() {
2002        let instruction = Instruction::new_with_wincode(
2003            TEST_CALLEE_PROGRAM_ID,
2004            &MockInstruction::NoopSuccess,
2005            vec![AccountMeta::new(TEST_ACCOUNT_KEY, true)],
2006        );
2007        let oversized_seed = [0u8; 33];
2008        let result = run_native_invoke_signed_test(
2009            TEST_ACCOUNT_KEY,
2010            false,
2011            instruction,
2012            &[&[&oversized_seed]],
2013        );
2014        assert_eq!(result, Err(InstructionError::Custom(0)));
2015    }
2016
2017    // CPI marks an account as signer but caller provides no seeds —
2018    // signer privilege escalation.
2019    #[test]
2020    fn test_native_invoke_signed_pda_privilege_escalation_without_seeds() {
2021        let (pda_key, _bump_seed) =
2022            Pubkey::find_program_address(&[b"seed"], &TEST_CALLER_PROGRAM_ID);
2023        let instruction = Instruction::new_with_wincode(
2024            TEST_CALLEE_PROGRAM_ID,
2025            &MockInstruction::NoopSuccess,
2026            vec![AccountMeta::new(pda_key, true)],
2027        );
2028        let result = run_native_invoke_signed_test(pda_key, false, instruction, &[]);
2029        assert_eq!(result, Err(InstructionError::PrivilegeEscalation));
2030    }
2031
2032    // Seeds valid for a different program ID don't grant signer privilege
2033    // because native_invoke_signed derives against the caller's own program ID.
2034    #[test]
2035    fn test_native_invoke_signed_uses_caller_program_id_for_pda() {
2036        let (pda_key, bump_seed) = Pubkey::find_program_address(&[b"seed"], &TEST_WRONG_PROGRAM_ID);
2037        let instruction = Instruction::new_with_wincode(
2038            TEST_CALLEE_PROGRAM_ID,
2039            &MockInstruction::NoopSuccess,
2040            vec![AccountMeta::new(pda_key, true)],
2041        );
2042        let result =
2043            run_native_invoke_signed_test(pda_key, false, instruction, &[&[b"seed", &[bump_seed]]]);
2044        assert_eq!(result, Err(InstructionError::PrivilegeEscalation));
2045    }
2046
2047    // Top-level signer privilege carries through CPI without needing seeds.
2048    #[test]
2049    fn test_native_invoke_signed_top_level_signer_needs_no_seeds() {
2050        let (pda_key, _bump_seed) =
2051            Pubkey::find_program_address(&[b"seed"], &TEST_CALLER_PROGRAM_ID);
2052        let instruction = Instruction::new_with_wincode(
2053            TEST_CALLEE_PROGRAM_ID,
2054            &MockInstruction::NoopSuccess,
2055            vec![
2056                AccountMeta::new(pda_key, true),
2057                AccountMeta::new_readonly(TEST_MOCK_EXTRA_KEY, false),
2058            ],
2059        );
2060        let result = run_native_invoke_signed_test(pda_key, true, instruction, &[]);
2061        assert!(
2062            result.is_ok(),
2063            "top-level signer should not need seeds: {result:?}"
2064        );
2065    }
2066
2067    #[test]
2068    fn test_compile_message() {
2069        let program_id = Pubkey::new_from_array([1u8; 32]);
2070        let writable = Pubkey::new_from_array([2u8; 32]);
2071        let loader_key = Pubkey::new_from_array([3u8; 32]);
2072
2073        let instruction = Instruction {
2074            program_id,
2075            accounts: vec![AccountMeta::new(writable, false)],
2076            data: vec![1, 2, 3],
2077        };
2078
2079        let accounts = vec![(
2080            writable,
2081            Account {
2082                lamports: 100,
2083                ..Account::default()
2084            },
2085        )];
2086
2087        let (message, tx_accounts) =
2088            mock_compile_message(&instruction, &accounts, &program_id, &loader_key);
2089
2090        assert_eq!(message.instructions().len(), 1);
2091        assert_eq!(tx_accounts.len(), 2);
2092        assert_eq!(tx_accounts.first().unwrap().0, writable);
2093        assert_eq!(tx_accounts.get(1).unwrap().0, program_id);
2094
2095        // Verify the writable account is NOT promoted to signer.
2096        assert!(!message.is_signer(0));
2097    }
2098
2099    struct MockCallback {}
2100    impl InvokeContextCallback for MockCallback {}
2101
2102    fn create_loadable_account_for_test(name: &str) -> AccountSharedData {
2103        AccountSharedData::from(Account {
2104            lamports: 1,
2105            owner: native_loader::id(),
2106            data: name.as_bytes().to_vec(),
2107            executable: true,
2108            rent_epoch: u64::MAX,
2109        })
2110    }
2111
2112    fn new_sanitized_message(message: Message) -> SanitizedMessage {
2113        SanitizedMessage::try_from_legacy_message(message, &HashSet::new()).unwrap()
2114    }
2115
2116    #[test]
2117    fn test_reject_instruction_with_more_than_255_accounts() {
2118        let payer = Pubkey::new_unique();
2119        let other_account = Pubkey::new_unique();
2120        let program_id = Pubkey::new_unique();
2121        let mut instruction_accounts = vec![0; 256];
2122        instruction_accounts.push(1);
2123        let message = new_sanitized_message(Message::new_with_compiled_instructions(
2124            1,
2125            0,
2126            2,
2127            vec![payer, other_account, program_id],
2128            Hash::default(),
2129            vec![solana_message::compiled_instruction::CompiledInstruction {
2130                program_id_index: 2,
2131                accounts: instruction_accounts,
2132                data: vec![],
2133            }],
2134        ));
2135        let accounts = vec![
2136            (payer, AccountSharedData::default()),
2137            (other_account, AccountSharedData::default()),
2138            (program_id, create_loadable_account_for_test("noop")),
2139        ];
2140        with_mock_invoke_context!(invoke_context, transaction_context, accounts);
2141        assert_eq!(
2142            invoke_context.prepare_top_level_instructions(&message),
2143            Err((0, InstructionError::MaxAccountsExceeded)),
2144        );
2145    }
2146
2147    #[test]
2148    fn test_process_message_readonly_handling() {
2149        #[derive(wincode::SchemaRead, wincode::SchemaWrite)]
2150        enum MockSystemInstruction {
2151            Correct,
2152            TransferLamports { lamports: u64 },
2153            ChangeData { data: u8 },
2154        }
2155
2156        declare_process_instruction!(MockBuiltin, 1, |invoke_context| {
2157            let transaction_context = &invoke_context.transaction_context;
2158            let instruction_context = transaction_context.get_current_instruction_context()?;
2159            let instruction_data = instruction_context.get_instruction_data();
2160            if let Ok(instruction) = wincode::deserialize(instruction_data) {
2161                match instruction {
2162                    MockSystemInstruction::Correct => Ok(()),
2163                    MockSystemInstruction::TransferLamports { lamports } => {
2164                        instruction_context
2165                            .try_borrow_instruction_account(0)?
2166                            .checked_sub_lamports(lamports)?;
2167                        instruction_context
2168                            .try_borrow_instruction_account(1)?
2169                            .checked_add_lamports(lamports)?;
2170                        Ok(())
2171                    }
2172                    MockSystemInstruction::ChangeData { data } => {
2173                        instruction_context
2174                            .try_borrow_instruction_account(1)?
2175                            .set_data_from_slice(&[data])?;
2176                        Ok(())
2177                    }
2178                }
2179            } else {
2180                Err(InstructionError::InvalidInstructionData)
2181            }
2182        });
2183
2184        let writable_pubkey = Pubkey::new_unique();
2185        let readonly_pubkey = Pubkey::new_unique();
2186        let mock_system_program_id = Pubkey::new_unique();
2187
2188        let accounts = vec![
2189            (
2190                writable_pubkey,
2191                AccountSharedData::new_with_data(100, vec![0; 1], &mock_system_program_id),
2192            ),
2193            (
2194                readonly_pubkey,
2195                AccountSharedData::new_with_data(0, vec![0; 1], &mock_system_program_id),
2196            ),
2197            (
2198                mock_system_program_id,
2199                create_loadable_account_for_test("mock_system_program"),
2200            ),
2201        ];
2202        let mut transaction_context =
2203            TransactionContext::new(accounts.clone(), Rent::default(), 1, 3, 1);
2204        let mut program_cache_for_tx_batch = ProgramCacheForTxBatch::default();
2205        program_cache_for_tx_batch.replenish(
2206            mock_system_program_id,
2207            Arc::new(ProgramCacheEntry::new_builtin(MockBuiltin::register)),
2208        );
2209        let account_keys = (0..transaction_context.get_number_of_accounts())
2210            .map(|index| {
2211                *transaction_context
2212                    .get_key_of_account_at_index(index)
2213                    .unwrap()
2214            })
2215            .collect::<Vec<_>>();
2216        let account_metas = vec![
2217            AccountMeta::new(writable_pubkey, true),
2218            AccountMeta::new_readonly(readonly_pubkey, false),
2219        ];
2220
2221        let message = new_sanitized_message(Message::new_with_compiled_instructions(
2222            1,
2223            0,
2224            2,
2225            account_keys.clone(),
2226            Hash::default(),
2227            AccountKeys::new(&account_keys, None).compile_instructions(&[
2228                Instruction::new_with_wincode(
2229                    mock_system_program_id,
2230                    &MockSystemInstruction::Correct,
2231                    account_metas.clone(),
2232                ),
2233            ]),
2234        ));
2235        let sysvar_cache = SysvarCache::default();
2236        let feature_set = SVMFeatureSet::all_enabled();
2237        let program_runtime_environments = ProgramRuntimeEnvironments::mock();
2238        let environment_config = EnvironmentConfig::new(
2239            Hash::default(),
2240            0,
2241            &MockCallback {},
2242            &feature_set,
2243            &program_runtime_environments,
2244            &sysvar_cache,
2245        );
2246        let mut invoke_context = InvokeContext::new(
2247            &mut transaction_context,
2248            &mut program_cache_for_tx_batch,
2249            environment_config,
2250            None,
2251            SVMTransactionExecutionBudget::default(),
2252            SVMTransactionExecutionCost::default(),
2253        );
2254        let result =
2255            invoke_context.process_message(&message, &mut ExecuteTimings::default(), &mut 0);
2256        assert!(result.is_ok());
2257        assert_eq!(
2258            transaction_context
2259                .accounts()
2260                .try_borrow(0)
2261                .unwrap()
2262                .lamports(),
2263            100
2264        );
2265        assert_eq!(
2266            transaction_context
2267                .accounts()
2268                .try_borrow(1)
2269                .unwrap()
2270                .lamports(),
2271            0
2272        );
2273
2274        let message = new_sanitized_message(Message::new_with_compiled_instructions(
2275            1,
2276            0,
2277            2,
2278            account_keys.clone(),
2279            Hash::default(),
2280            AccountKeys::new(&account_keys, None).compile_instructions(&[
2281                Instruction::new_with_wincode(
2282                    mock_system_program_id,
2283                    &MockSystemInstruction::TransferLamports { lamports: 50 },
2284                    account_metas.clone(),
2285                ),
2286            ]),
2287        ));
2288        let program_runtime_environments = ProgramRuntimeEnvironments::mock();
2289        let environment_config = EnvironmentConfig::new(
2290            Hash::default(),
2291            0,
2292            &MockCallback {},
2293            &feature_set,
2294            &program_runtime_environments,
2295            &sysvar_cache,
2296        );
2297        let mut transaction_context =
2298            TransactionContext::new(accounts.clone(), Rent::default(), 1, 3, 1);
2299        let mut invoke_context = InvokeContext::new(
2300            &mut transaction_context,
2301            &mut program_cache_for_tx_batch,
2302            environment_config,
2303            None,
2304            SVMTransactionExecutionBudget::default(),
2305            SVMTransactionExecutionCost::default(),
2306        );
2307        let result =
2308            invoke_context.process_message(&message, &mut ExecuteTimings::default(), &mut 0);
2309        assert_eq!(result, Err((0, InstructionError::ReadonlyLamportChange)));
2310
2311        let message = new_sanitized_message(Message::new_with_compiled_instructions(
2312            1,
2313            0,
2314            2,
2315            account_keys.clone(),
2316            Hash::default(),
2317            AccountKeys::new(&account_keys, None).compile_instructions(&[
2318                Instruction::new_with_wincode(
2319                    mock_system_program_id,
2320                    &MockSystemInstruction::ChangeData { data: 50 },
2321                    account_metas,
2322                ),
2323            ]),
2324        ));
2325        let program_runtime_environments = ProgramRuntimeEnvironments::mock();
2326        let environment_config = EnvironmentConfig::new(
2327            Hash::default(),
2328            0,
2329            &MockCallback {},
2330            &feature_set,
2331            &program_runtime_environments,
2332            &sysvar_cache,
2333        );
2334        let mut transaction_context = TransactionContext::new(accounts, Rent::default(), 1, 3, 1);
2335        let mut invoke_context = InvokeContext::new(
2336            &mut transaction_context,
2337            &mut program_cache_for_tx_batch,
2338            environment_config,
2339            None,
2340            SVMTransactionExecutionBudget::default(),
2341            SVMTransactionExecutionCost::default(),
2342        );
2343        let result =
2344            invoke_context.process_message(&message, &mut ExecuteTimings::default(), &mut 0);
2345        assert_eq!(result, Err((0, InstructionError::ReadonlyDataModified)));
2346    }
2347
2348    #[test]
2349    fn test_process_message_duplicate_accounts() {
2350        #[derive(wincode::SchemaRead, wincode::SchemaWrite)]
2351        enum MockSystemInstruction {
2352            BorrowFail,
2353            MultiBorrowMut,
2354            DoWork { lamports: u64, data: u8 },
2355        }
2356
2357        declare_process_instruction!(MockBuiltin, 1, |invoke_context| {
2358            let transaction_context = &invoke_context.transaction_context;
2359            let instruction_context = transaction_context.get_current_instruction_context()?;
2360            let instruction_data = instruction_context.get_instruction_data();
2361            let mut to_account = instruction_context.try_borrow_instruction_account(1)?;
2362            if let Ok(instruction) = wincode::deserialize(instruction_data) {
2363                match instruction {
2364                    MockSystemInstruction::BorrowFail => {
2365                        let from_account = instruction_context.try_borrow_instruction_account(0)?;
2366                        let dup_account = instruction_context.try_borrow_instruction_account(2)?;
2367                        if from_account.get_lamports() != dup_account.get_lamports() {
2368                            return Err(InstructionError::InvalidArgument);
2369                        }
2370                        Ok(())
2371                    }
2372                    MockSystemInstruction::MultiBorrowMut => {
2373                        let lamports_a = instruction_context
2374                            .try_borrow_instruction_account(0)?
2375                            .get_lamports();
2376                        let lamports_b = instruction_context
2377                            .try_borrow_instruction_account(2)?
2378                            .get_lamports();
2379                        if lamports_a != lamports_b {
2380                            return Err(InstructionError::InvalidArgument);
2381                        }
2382                        Ok(())
2383                    }
2384                    MockSystemInstruction::DoWork { lamports, data } => {
2385                        let mut dup_account =
2386                            instruction_context.try_borrow_instruction_account(2)?;
2387                        dup_account.checked_sub_lamports(lamports)?;
2388                        to_account.checked_add_lamports(lamports)?;
2389                        dup_account.set_data_from_slice(&[data])?;
2390                        drop(dup_account);
2391                        let mut from_account =
2392                            instruction_context.try_borrow_instruction_account(0)?;
2393                        from_account.checked_sub_lamports(lamports)?;
2394                        to_account.checked_add_lamports(lamports)?;
2395                        Ok(())
2396                    }
2397                }
2398            } else {
2399                Err(InstructionError::InvalidInstructionData)
2400            }
2401        });
2402        let mock_program_id = Pubkey::from([2u8; 32]);
2403        let accounts = vec![
2404            (
2405                solana_pubkey::new_rand(),
2406                AccountSharedData::new_with_data(100, vec![0; 1], &mock_program_id),
2407            ),
2408            (
2409                solana_pubkey::new_rand(),
2410                AccountSharedData::new_with_data(0, vec![0; 1], &mock_program_id),
2411            ),
2412            (
2413                mock_program_id,
2414                create_loadable_account_for_test("mock_system_program"),
2415            ),
2416        ];
2417        let mut transaction_context =
2418            TransactionContext::new(accounts.clone(), Rent::default(), 1, 3, 1);
2419        let mut program_cache_for_tx_batch = ProgramCacheForTxBatch::default();
2420        program_cache_for_tx_batch.replenish(
2421            mock_program_id,
2422            Arc::new(ProgramCacheEntry::new_builtin(MockBuiltin::register)),
2423        );
2424        let account_metas = vec![
2425            AccountMeta::new(
2426                *transaction_context.get_key_of_account_at_index(0).unwrap(),
2427                true,
2428            ),
2429            AccountMeta::new(
2430                *transaction_context.get_key_of_account_at_index(1).unwrap(),
2431                false,
2432            ),
2433            AccountMeta::new(
2434                *transaction_context.get_key_of_account_at_index(0).unwrap(),
2435                false,
2436            ),
2437        ];
2438
2439        // Try to borrow mut the same account
2440        let message = new_sanitized_message(Message::new(
2441            &[Instruction::new_with_wincode(
2442                mock_program_id,
2443                &MockSystemInstruction::BorrowFail,
2444                account_metas.clone(),
2445            )],
2446            Some(transaction_context.get_key_of_account_at_index(0).unwrap()),
2447        ));
2448        let sysvar_cache = SysvarCache::default();
2449        let feature_set = SVMFeatureSet::all_enabled();
2450        let program_runtime_environments = ProgramRuntimeEnvironments::mock();
2451        let environment_config = EnvironmentConfig::new(
2452            Hash::default(),
2453            0,
2454            &MockCallback {},
2455            &feature_set,
2456            &program_runtime_environments,
2457            &sysvar_cache,
2458        );
2459        let mut invoke_context = InvokeContext::new(
2460            &mut transaction_context,
2461            &mut program_cache_for_tx_batch,
2462            environment_config,
2463            None,
2464            SVMTransactionExecutionBudget::default(),
2465            SVMTransactionExecutionCost::default(),
2466        );
2467        let result =
2468            invoke_context.process_message(&message, &mut ExecuteTimings::default(), &mut 0);
2469        assert_eq!(result, Err((0, InstructionError::AccountBorrowFailed)));
2470
2471        // Try to borrow mut the same account in a safe way
2472        let message = new_sanitized_message(Message::new(
2473            &[Instruction::new_with_wincode(
2474                mock_program_id,
2475                &MockSystemInstruction::MultiBorrowMut,
2476                account_metas.clone(),
2477            )],
2478            Some(transaction_context.get_key_of_account_at_index(0).unwrap()),
2479        ));
2480        let program_runtime_environments = ProgramRuntimeEnvironments::mock();
2481        let environment_config = EnvironmentConfig::new(
2482            Hash::default(),
2483            0,
2484            &MockCallback {},
2485            &feature_set,
2486            &program_runtime_environments,
2487            &sysvar_cache,
2488        );
2489        let mut transaction_context =
2490            TransactionContext::new(accounts.clone(), Rent::default(), 1, 3, 1);
2491        let mut invoke_context = InvokeContext::new(
2492            &mut transaction_context,
2493            &mut program_cache_for_tx_batch,
2494            environment_config,
2495            None,
2496            SVMTransactionExecutionBudget::default(),
2497            SVMTransactionExecutionCost::default(),
2498        );
2499        let result =
2500            invoke_context.process_message(&message, &mut ExecuteTimings::default(), &mut 0);
2501        assert!(result.is_ok());
2502
2503        // Do work on the same transaction account but at different instruction accounts
2504        let message = new_sanitized_message(Message::new(
2505            &[Instruction::new_with_wincode(
2506                mock_program_id,
2507                &MockSystemInstruction::DoWork {
2508                    lamports: 10,
2509                    data: 42,
2510                },
2511                account_metas,
2512            )],
2513            Some(transaction_context.get_key_of_account_at_index(0).unwrap()),
2514        ));
2515        let program_runtime_environments = ProgramRuntimeEnvironments::mock();
2516        let environment_config = EnvironmentConfig::new(
2517            Hash::default(),
2518            0,
2519            &MockCallback {},
2520            &feature_set,
2521            &program_runtime_environments,
2522            &sysvar_cache,
2523        );
2524        let mut transaction_context = TransactionContext::new(accounts, Rent::default(), 1, 3, 1);
2525        let mut invoke_context = InvokeContext::new(
2526            &mut transaction_context,
2527            &mut program_cache_for_tx_batch,
2528            environment_config,
2529            None,
2530            SVMTransactionExecutionBudget::default(),
2531            SVMTransactionExecutionCost::default(),
2532        );
2533        let result =
2534            invoke_context.process_message(&message, &mut ExecuteTimings::default(), &mut 0);
2535        assert!(result.is_ok());
2536        assert_eq!(
2537            transaction_context
2538                .accounts()
2539                .try_borrow(0)
2540                .unwrap()
2541                .lamports(),
2542            80
2543        );
2544        assert_eq!(
2545            transaction_context
2546                .accounts()
2547                .try_borrow(1)
2548                .unwrap()
2549                .lamports(),
2550            20
2551        );
2552        assert_eq!(
2553            transaction_context.accounts().try_borrow(0).unwrap().data(),
2554            &vec![42]
2555        );
2556    }
2557
2558    fn secp256k1_instruction_for_test() -> Instruction {
2559        let message = b"hello";
2560        let bytes: [u8; 32] = rand::random();
2561        let secret_key = libsecp256k1::SecretKey::parse(&bytes).unwrap();
2562        let pubkey = libsecp256k1::PublicKey::from_secret_key(&secret_key);
2563        let eth_address = eth_address_from_pubkey(&pubkey.serialize()[1..].try_into().unwrap());
2564        let (signature, recovery_id) =
2565            solana_secp256k1_program::sign_message(&secret_key.serialize(), &message[..]).unwrap();
2566        new_secp256k1_instruction_with_signature(
2567            &message[..],
2568            &signature,
2569            recovery_id,
2570            &eth_address,
2571        )
2572    }
2573
2574    fn ed25519_instruction_for_test() -> Instruction {
2575        let keypair = Keypair::new();
2576        let signature = keypair.sign_message(b"hello");
2577        let pubkey = keypair.pubkey().to_bytes();
2578        new_ed25519_instruction_with_signature(b"hello", signature.as_array(), &pubkey)
2579    }
2580
2581    fn secp256r1_instruction_for_test() -> Instruction {
2582        let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap();
2583        let secret_key = EcKey::generate(&group).unwrap();
2584        let signature = sign_message(b"hello", &secret_key.private_key_to_der().unwrap()).unwrap();
2585        let mut ctx = openssl::bn::BigNumContext::new().unwrap();
2586        let pubkey = secret_key
2587            .public_key()
2588            .to_bytes(
2589                &group,
2590                openssl::ec::PointConversionForm::COMPRESSED,
2591                &mut ctx,
2592            )
2593            .unwrap();
2594        new_secp256r1_instruction_with_signature(b"hello", &signature, &pubkey.try_into().unwrap())
2595    }
2596
2597    #[test]
2598    fn test_precompile() {
2599        let mock_program_id = Pubkey::new_unique();
2600        declare_process_instruction!(MockBuiltin, 1, |_invoke_context| {
2601            Err(InstructionError::Custom(0xbabb1e))
2602        });
2603
2604        let mut secp256k1_account = AccountSharedData::empty(1, &native_loader::id());
2605        secp256k1_account.set_executable(true);
2606        let mut ed25519_account = AccountSharedData::empty(1, &native_loader::id());
2607        ed25519_account.set_executable(true);
2608        let mut secp256r1_account = AccountSharedData::empty(1, &native_loader::id());
2609        secp256r1_account.set_executable(true);
2610        let mut mock_program_account = AccountSharedData::empty(1, &native_loader::id());
2611        mock_program_account.set_executable(true);
2612
2613        let fee_payer = Pubkey::new_unique();
2614        let accounts_map: HashMap<Address, AccountSharedData> = HashMap::from([
2615            (
2616                fee_payer,
2617                AccountSharedData::empty(1, &system_program::id()),
2618            ),
2619            (secp256k1_program::id(), secp256k1_account),
2620            (ed25519_program::id(), ed25519_account),
2621            (solana_secp256r1_program::id(), secp256r1_account),
2622            (mock_program_id, mock_program_account),
2623        ]);
2624
2625        let message = new_sanitized_message(Message::new(
2626            &[
2627                secp256k1_instruction_for_test(),
2628                ed25519_instruction_for_test(),
2629                secp256r1_instruction_for_test(),
2630                Instruction::new_with_bytes(mock_program_id, &[], vec![]),
2631            ],
2632            Some(&fee_payer),
2633        ));
2634
2635        let accounts = message
2636            .account_keys()
2637            .iter()
2638            .map(|key| (*key, accounts_map.get(key).unwrap().clone()))
2639            .collect();
2640        let mut transaction_context = TransactionContext::new(accounts, Rent::default(), 1, 4, 4);
2641
2642        let sysvar_cache = SysvarCache::default();
2643        let mut program_cache_for_tx_batch = ProgramCacheForTxBatch::default();
2644        program_cache_for_tx_batch.replenish(
2645            mock_program_id,
2646            Arc::new(ProgramCacheEntry::new_builtin(MockBuiltin::register)),
2647        );
2648
2649        struct MockCallback {}
2650        impl InvokeContextCallback for MockCallback {
2651            fn is_precompile(&self, program_id: &Pubkey) -> bool {
2652                program_id == &secp256k1_program::id()
2653                    || program_id == &ed25519_program::id()
2654                    || program_id == &solana_secp256r1_program::id()
2655            }
2656
2657            fn process_precompile(
2658                &self,
2659                program_id: &Pubkey,
2660                _data: &[u8],
2661                _instruction_datas: Vec<&[u8]>,
2662            ) -> std::result::Result<(), PrecompileError> {
2663                if self.is_precompile(program_id) {
2664                    Ok(())
2665                } else {
2666                    Err(PrecompileError::InvalidPublicKey)
2667                }
2668            }
2669        }
2670        let feature_set = SVMFeatureSet::all_enabled();
2671        let program_runtime_environments = ProgramRuntimeEnvironments::mock();
2672        let environment_config = EnvironmentConfig::new(
2673            Hash::default(),
2674            0,
2675            &MockCallback {},
2676            &feature_set,
2677            &program_runtime_environments,
2678            &sysvar_cache,
2679        );
2680        let mut invoke_context = InvokeContext::new(
2681            &mut transaction_context,
2682            &mut program_cache_for_tx_batch,
2683            environment_config,
2684            None,
2685            SVMTransactionExecutionBudget::default(),
2686            SVMTransactionExecutionCost::default(),
2687        );
2688        let result =
2689            invoke_context.process_message(&message, &mut ExecuteTimings::default(), &mut 0);
2690
2691        assert_eq!(result, Err((3, InstructionError::Custom(0xbabb1e))));
2692        assert_eq!(
2693            transaction_context.number_of_called_instructions_in_trace(),
2694            4
2695        );
2696    }
2697
2698    #[test]
2699    fn test_abi_follows_instruction_stack() {
2700        let transaction_accounts = vec![
2701            (
2702                Pubkey::new_unique(),
2703                AccountSharedData::empty(0, &bpf_loader_deprecated::id()),
2704            ),
2705            (
2706                Pubkey::new_unique(),
2707                AccountSharedData::empty(0, &bpf_loader_upgradeable::id()),
2708            ),
2709        ];
2710        with_mock_invoke_context!(invoke_context, transaction_context, transaction_accounts);
2711
2712        // No instruction.
2713        assert_eq!(invoke_context.abi(), ABI::V1);
2714
2715        // ABIv0 program.
2716        invoke_context
2717            .transaction_context
2718            .configure_top_level_instruction_for_tests(0, vec![], vec![])
2719            .unwrap();
2720        invoke_context.push().unwrap();
2721        assert_eq!(invoke_context.abi(), ABI::V0);
2722
2723        // It invokes an ABIv1 program.
2724        invoke_context
2725            .transaction_context
2726            .configure_next_cpi_for_tests(1, vec![], vec![])
2727            .unwrap();
2728        invoke_context.push().unwrap();
2729        assert_eq!(invoke_context.abi(), ABI::V1);
2730
2731        // The callee returns.
2732        invoke_context.pop().unwrap();
2733        assert_eq!(invoke_context.abi(), ABI::V0);
2734    }
2735}