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