Skip to main content

solana_transaction_context/
transaction.rs

1#[cfg(feature = "dev-context-only-utils")]
2use crate::DEFAULT_INSTRUCTION_COMPUTE_UNIT_LIMIT;
3#[cfg(not(any(target_arch = "bpf", target_arch = "sbf")))]
4use {
5    crate::{
6        DropOnBailOut, IndexOfAccount, MAX_ACCOUNT_DATA_GROWTH_PER_TRANSACTION,
7        MAX_ACCOUNT_DATA_LEN, MAX_ACCOUNTS_PER_INSTRUCTION, MAX_ACCOUNTS_PER_TRANSACTION,
8        instruction::{InstructionContext, InstructionFrame},
9        transaction_accounts::{KeyedAccountSharedData, TransactionAccounts},
10        vm_addresses::{
11            GUEST_INSTRUCTION_ACCOUNT_BASE_ADDRESS, GUEST_INSTRUCTION_DATA_BASE_ADDRESS,
12            GUEST_REGION_SIZE, RETURN_DATA_SCRATCHPAD,
13        },
14    },
15    solana_account::{AccountSharedData, ReadableAccount, WritableAccount},
16    solana_instruction_error::InstructionError,
17    solana_instructions_sysvar as instructions,
18    solana_rent::Rent,
19    solana_sbpf::{
20        memory_region::{AccessType, AccessViolationHandler, MemoryRegion},
21        vm::ContextObject,
22    },
23    std::{borrow::Cow, cell::Cell, rc::Rc},
24};
25use {
26    crate::{instruction_accounts::InstructionAccount, vm_slice::VmSlice},
27    solana_pubkey::Pubkey,
28};
29
30#[derive(Debug)]
31pub struct ComputeMeter(Cell<u64>);
32
33impl ComputeMeter {
34    /// Consume compute units
35    pub fn consume_unchecked(&self, amount: u64) {
36        let compute_meter = self.0.get();
37        self.0.set(compute_meter.saturating_sub(amount));
38    }
39
40    /// Consume compute units and check for ComputationalBudgetExceeded
41    pub fn consume_checked(&self, amount: u64) -> Result<(), Box<dyn std::error::Error>> {
42        let compute_meter = self.0.get();
43        let exceeded = compute_meter < amount;
44        self.0.set(compute_meter.saturating_sub(amount));
45        if exceeded {
46            return Err(Box::new(InstructionError::ComputationalBudgetExceeded));
47        }
48        Ok(())
49    }
50
51    /// Set compute units
52    ///
53    /// Only use for tests and benchmarks
54    #[cfg(feature = "dev-context-only-utils")]
55    pub fn mock_set_remaining(&self, remaining: u64) {
56        self.0.set(remaining);
57    }
58
59    /// Returns the remaining compute units
60    pub fn get_remaining(&self) -> u64 {
61        self.0.get()
62    }
63
64    /// Construct from compute units
65    pub fn new(remaining: u64) -> Self {
66        Self(Cell::new(remaining))
67    }
68}
69
70/// Used only in fn `take_instruction_trace` for deconstructing TransactionContext
71pub type InstructionTrace<'ix_data> = (
72    Vec<InstructionFrame>,
73    Vec<Box<[InstructionAccount]>>,
74    Vec<Cow<'ix_data, [u8]>>,
75);
76
77/// This data structure is shared with programs in ABIv2, providing information about the
78/// transaction metadata.
79///
80/// Modifications without a feature gate and proper versioning might break programs.
81#[repr(C)]
82#[derive(Debug)]
83struct TransactionFrame {
84    /// Pubkey of the last program to write to the return data scratchpad
85    return_data_pubkey: Pubkey,
86    return_data_scratchpad: VmSlice<u8>,
87    /// Scratchpad for programs to write CPI instruction data
88    pub cpi_data_scratchpad: VmSlice<u8>,
89    /// Scratchpad for programs to write CPI accounts
90    pub cpi_accounts_scratchpad: VmSlice<InstructionAccount>,
91    /// Index of current executing instruction
92    current_executing_instruction: u16,
93    /// Number of instructions in the instruction trace (including top level and CPIs)
94    total_number_of_instructions_in_trace: u16,
95    /// Number of CPIs in the instruction trace
96    number_of_cpis_in_trace: u16,
97    /// Number of transaction accounts
98    number_of_transaction_accounts: u16,
99}
100
101#[cfg(not(any(target_arch = "sbf", target_arch = "bpf")))]
102impl TransactionFrame {
103    fn configure_cpi(&mut self) {
104        self.total_number_of_instructions_in_trace =
105            self.total_number_of_instructions_in_trace.saturating_add(1);
106        let next_data_ptr = self
107            .cpi_data_scratchpad
108            .ptr()
109            .saturating_add(GUEST_REGION_SIZE);
110        self.cpi_data_scratchpad = VmSlice::new(next_data_ptr, 0);
111        let next_accounts_ptr = self
112            .cpi_accounts_scratchpad
113            .ptr()
114            .saturating_add(GUEST_REGION_SIZE);
115        self.cpi_accounts_scratchpad = VmSlice::new(next_accounts_ptr, 0);
116    }
117}
118
119/// Loaded transaction shared between runtime and programs.
120///
121/// This context is valid for the entire duration of a transaction being processed.
122#[derive(Debug)]
123#[cfg(not(any(target_arch = "bpf", target_arch = "sbf")))]
124pub struct TransactionContext<'ix_data> {
125    pub(crate) accounts: Rc<TransactionAccounts>,
126    instruction_stack_capacity: usize,
127    instruction_trace_capacity: usize,
128    instruction_stack: Vec<usize>,
129    instruction_trace: Vec<InstructionFrame>,
130    transaction_frame: TransactionFrame,
131    return_data_bytes: Vec<u8>,
132    next_top_level_instruction_index: usize,
133    /// Instruction compute meter, for tracking compute units consumed against
134    /// the designated compute budget during program execution.
135    #[cfg(not(target_os = "solana"))]
136    pub compute_meter: ComputeMeter,
137    #[cfg(not(target_os = "solana"))]
138    pub(crate) lamports_delta: Cell<i128>,
139    #[cfg(not(target_os = "solana"))]
140    pub(crate) rent: Rent,
141    /// This is an account deduplication map that maps index_in_transaction to index_in_instruction
142    /// Usage: dedup_map[index_in_transaction] = index_in_instruction
143    /// Each entry in `deduplication_maps` represents the deduplication map for each instruction.
144    deduplication_maps: Vec<Box<[u8]>>,
145    /// Each entry in `instruction_accounts` represents the array of accounts for each instruction.
146    instruction_accounts: Vec<Box<[InstructionAccount]>>,
147    /// Each entry in `instruction_data` represents the data for instruction at the corresponding
148    /// index.
149    instruction_data: Vec<Cow<'ix_data, [u8]>>,
150}
151
152#[cfg(not(any(target_arch = "bpf", target_arch = "sbf")))]
153impl<'ix_data> TransactionContext<'ix_data> {
154    /// Constructs a new TransactionContext
155    pub fn new_with_feature_flags(
156        transaction_accounts: Vec<KeyedAccountSharedData>,
157        rent: Rent,
158        instruction_stack_capacity: usize,
159        instruction_trace_capacity: usize,
160        number_of_top_level_instructions: usize,
161        compute_meter: ComputeMeter,
162        drop_on_bail_out: DropOnBailOut,
163    ) -> Self {
164        let transaction_frame = TransactionFrame {
165            return_data_pubkey: Pubkey::default(),
166            return_data_scratchpad: VmSlice::new(RETURN_DATA_SCRATCHPAD, 0),
167            cpi_data_scratchpad: VmSlice::new(
168                GUEST_INSTRUCTION_DATA_BASE_ADDRESS.saturating_add(
169                    GUEST_REGION_SIZE.saturating_mul(number_of_top_level_instructions as u64),
170                ),
171                0,
172            ),
173            cpi_accounts_scratchpad: VmSlice::new(
174                GUEST_INSTRUCTION_ACCOUNT_BASE_ADDRESS.saturating_add(
175                    GUEST_REGION_SIZE.saturating_mul(number_of_top_level_instructions as u64),
176                ),
177                0,
178            ),
179            current_executing_instruction: 0,
180            total_number_of_instructions_in_trace: number_of_top_level_instructions as u16,
181            number_of_cpis_in_trace: 0,
182            number_of_transaction_accounts: transaction_accounts.len() as u16,
183        };
184
185        // We need an extra space for the placeholder, so we avoid relocations.
186        let mut instruction_trace =
187            Vec::with_capacity(instruction_trace_capacity.saturating_add(1));
188        instruction_trace.resize_with(
189            number_of_top_level_instructions.saturating_add(1),
190            InstructionFrame::default,
191        );
192
193        Self {
194            accounts: Rc::new(TransactionAccounts::new_with_feature_flags(
195                transaction_accounts,
196                drop_on_bail_out,
197            )),
198            instruction_stack_capacity,
199            instruction_trace_capacity,
200            instruction_stack: Vec::with_capacity(instruction_stack_capacity),
201            instruction_trace,
202            return_data_bytes: Vec::new(),
203            transaction_frame,
204            next_top_level_instruction_index: 0,
205            compute_meter,
206            lamports_delta: Cell::new(0),
207            rent,
208            instruction_accounts: Vec::with_capacity(instruction_trace_capacity),
209            deduplication_maps: Vec::with_capacity(instruction_trace_capacity),
210            instruction_data: Vec::with_capacity(instruction_trace_capacity),
211        }
212    }
213
214    /// Constructs a new TransactionContext with all features active
215    #[cfg(feature = "dev-context-only-utils")]
216    pub fn new(
217        transaction_accounts: Vec<KeyedAccountSharedData>,
218        rent: Rent,
219        instruction_stack_capacity: usize,
220        instruction_trace_capacity: usize,
221        number_of_top_level_instructions: usize,
222    ) -> Self {
223        Self::new_with_feature_flags(
224            transaction_accounts,
225            rent,
226            instruction_stack_capacity,
227            instruction_trace_capacity,
228            number_of_top_level_instructions,
229            ComputeMeter::new(DEFAULT_INSTRUCTION_COMPUTE_UNIT_LIMIT as u64),
230            DropOnBailOut::Disabled,
231        )
232    }
233
234    /// Used in mock_process_instruction
235    pub fn deconstruct_without_keys(self) -> Result<Vec<AccountSharedData>, InstructionError> {
236        if !self.instruction_stack.is_empty() {
237            return Err(InstructionError::CallDepth);
238        }
239
240        let accounts = Rc::try_unwrap(self.accounts)
241            .expect("transaction_context.accounts has unexpected outstanding refs")
242            .deconstruct_into_account_shared_data();
243
244        Ok(accounts)
245    }
246
247    pub(crate) fn add_lamports_delta(&self, balance: i128) -> Result<(), InstructionError> {
248        let delta = self.lamports_delta.get();
249        self.lamports_delta.set(
250            delta
251                .checked_add(balance)
252                .ok_or(InstructionError::ArithmeticOverflow)?,
253        );
254        Ok(())
255    }
256
257    pub fn accounts(&self) -> &Rc<TransactionAccounts> {
258        &self.accounts
259    }
260
261    /// Returns the total number of accounts loaded in this Transaction
262    pub fn get_number_of_accounts(&self) -> IndexOfAccount {
263        self.accounts.len() as IndexOfAccount
264    }
265
266    /// Searches for an account by its key
267    pub fn get_key_of_account_at_index(
268        &self,
269        index_in_transaction: IndexOfAccount,
270    ) -> Result<&Pubkey, InstructionError> {
271        self.accounts
272            .account_key(index_in_transaction)
273            .ok_or(InstructionError::MissingAccount)
274    }
275
276    /// Searches for an account by its key
277    pub fn find_index_of_account(&self, pubkey: &Pubkey) -> Option<IndexOfAccount> {
278        self.accounts
279            .account_keys_iter()
280            .position(|key| key == pubkey)
281            .map(|index| index as IndexOfAccount)
282    }
283
284    /// Gets the max length of the instruction trace
285    pub fn get_instruction_trace_capacity(&self) -> usize {
286        self.instruction_trace_capacity
287    }
288
289    /// Returns the instruction trace length.
290    ///
291    /// Not counting the last empty instruction which is always pre-reserved for the next instruction.
292    pub fn get_instruction_trace_length(&self) -> usize {
293        self.instruction_trace.len().saturating_sub(1)
294    }
295
296    /// Gets a view on an instruction by its index in the trace
297    pub fn get_instruction_context_at_index_in_trace(
298        &self,
299        index_in_trace: usize,
300    ) -> Result<InstructionContext<'_, '_>, InstructionError> {
301        let instruction = self
302            .instruction_trace
303            .get(index_in_trace)
304            .ok_or(InstructionError::CallDepth)?;
305
306        // These commands will return a default empty slice if we are retrieving an instruction
307        // that hasn't been configured yet.
308        let instruction_accounts = self
309            .instruction_accounts
310            .get(index_in_trace)
311            .map(|item| item.as_ref())
312            .unwrap_or_default();
313        let dedup_map = self
314            .deduplication_maps
315            .get(index_in_trace)
316            .map(|item| item.as_ref())
317            .unwrap_or_default();
318        let instruction_data = self
319            .instruction_data
320            .get(index_in_trace)
321            .map(|item| item.as_ref())
322            .unwrap_or_default();
323        Ok(InstructionContext {
324            transaction_context: self,
325            index_in_trace,
326            nesting_level: instruction.nesting_level as usize,
327            program_account_index_in_tx: instruction.program_account_index_in_tx as IndexOfAccount,
328            instruction_accounts,
329            dedup_map,
330            instruction_data,
331            index_of_caller_instruction: instruction.index_of_caller_instruction as usize,
332        })
333    }
334
335    /// Gets a view on the instruction by its nesting level in the stack
336    pub fn get_instruction_context_at_nesting_level(
337        &self,
338        nesting_level: usize,
339    ) -> Result<InstructionContext<'_, '_>, InstructionError> {
340        let index_in_trace = *self
341            .instruction_stack
342            .get(nesting_level)
343            .ok_or(InstructionError::CallDepth)?;
344        let instruction_context = self.get_instruction_context_at_index_in_trace(index_in_trace)?;
345        debug_assert_eq!(instruction_context.nesting_level, nesting_level);
346        Ok(instruction_context)
347    }
348
349    /// Gets the max height of the instruction stack
350    pub fn get_instruction_stack_capacity(&self) -> usize {
351        self.instruction_stack_capacity
352    }
353
354    /// Gets instruction stack height, top-level instructions are height
355    /// `solana_instruction::TRANSACTION_LEVEL_STACK_HEIGHT`
356    pub fn get_instruction_stack_height(&self) -> usize {
357        self.instruction_stack.len()
358    }
359
360    /// Returns the index in the instruction trace of the current executing instruction
361    pub fn get_current_instruction_index(&self) -> Result<usize, InstructionError> {
362        self.instruction_stack
363            .last()
364            .copied()
365            .ok_or(InstructionError::CallDepth)
366    }
367
368    /// Returns a view on the current instruction
369    pub fn get_current_instruction_context(
370        &self,
371    ) -> Result<InstructionContext<'_, '_>, InstructionError> {
372        let index_in_trace = self.get_current_instruction_index()?;
373        self.get_instruction_context_at_index_in_trace(index_in_trace)
374    }
375
376    /// Returns a view on the next instruction. This function assumes it has already been
377    /// configured with the correct values in `prepare_next_instruction` or
378    /// `prepare_next_top_level_instruction`
379    pub fn get_next_instruction_context(
380        &self,
381    ) -> Result<InstructionContext<'_, '_>, InstructionError> {
382        let index_in_trace = if self.instruction_stack.is_empty() {
383            self.next_top_level_instruction_index
384        } else {
385            self.instruction_trace
386                .len()
387                .checked_sub(1)
388                .ok_or(InstructionError::CallDepth)?
389        };
390        self.get_instruction_context_at_index_in_trace(index_in_trace)
391    }
392
393    /// Configures an instruction at a specific index in trace.
394    pub fn configure_instruction_at_index(
395        &mut self,
396        instruction_index: usize,
397        program_index: IndexOfAccount,
398        instruction_accounts: Vec<InstructionAccount>,
399        deduplication_map: Vec<u8>,
400        instruction_data: Cow<'ix_data, [u8]>,
401        caller_index: Option<u16>,
402    ) -> Result<(), InstructionError> {
403        // The deduplication map reserves u8::MAX for an absent account, and
404        // the SBF parameter ABI reserves it as the non-duplicate marker.
405        if instruction_accounts.len() > MAX_ACCOUNTS_PER_INSTRUCTION {
406            return Err(InstructionError::MaxAccountsExceeded);
407        }
408
409        debug_assert_eq!(
410            deduplication_map.len(),
411            usize::from(self.get_number_of_accounts()).min(MAX_ACCOUNTS_PER_TRANSACTION)
412        );
413
414        let instruction = self
415            .instruction_trace
416            .get_mut(instruction_index)
417            .ok_or(InstructionError::MaxInstructionTraceLengthExceeded)?;
418
419        // If we have a parent index, then we are dealing with a CPI.
420        if let Some(caller_index) = caller_index {
421            instruction.index_of_caller_instruction = caller_index;
422            self.transaction_frame.configure_cpi();
423        }
424
425        instruction.program_account_index_in_tx = program_index;
426        instruction.configure_vm_slices(
427            instruction_index as u64,
428            instruction_accounts.len(),
429            instruction_data.len() as u64,
430        );
431        self.deduplication_maps
432            .push(deduplication_map.into_boxed_slice());
433        self.instruction_accounts
434            .push(instruction_accounts.into_boxed_slice());
435        self.instruction_data.push(instruction_data);
436        Ok(())
437    }
438
439    fn deduplicate_accounts(
440        num_accounts: usize,
441        instruction_accounts: &mut [InstructionAccount],
442    ) -> Vec<u8> {
443        let mut dedup_map = vec![u8::MAX; num_accounts];
444        for idx_in_ix in 0..instruction_accounts.len() {
445            let first_occurrence_in_ix = dedup_map
446                .get_mut(
447                    instruction_accounts
448                        .get(idx_in_ix)
449                        .unwrap()
450                        .index_in_transaction as usize,
451                )
452                .unwrap();
453            if *first_occurrence_in_ix == u8::MAX {
454                *first_occurrence_in_ix = idx_in_ix as u8;
455            } else {
456                // Let's update the signer and writable flags for the first appearance of this
457                // account.
458                let [this_account, other_account] = instruction_accounts
459                    .get_disjoint_mut([idx_in_ix, *first_occurrence_in_ix as usize])
460                    .expect("Accounts indices must exist in array");
461
462                other_account.set_is_signer(other_account.is_signer() || this_account.is_signer());
463                other_account
464                    .set_is_writable(other_account.is_writable() || this_account.is_writable());
465            }
466        }
467
468        Self::replicate_account_flags(instruction_accounts, &dedup_map);
469        dedup_map
470    }
471
472    /// Replicate account flags to duplicated accounts.
473    /// This function only works if the accounts had been previously deduplicated, like in
474    /// `deduplicate_accounts` and `build_instruction_frame`.
475    pub fn replicate_account_flags(
476        instruction_accounts: &mut [InstructionAccount],
477        dedup_map: &[u8],
478    ) {
479        for current_index in 0..instruction_accounts.len() {
480            let instruction_account = instruction_accounts.get(current_index).unwrap();
481            let other_account_index = *dedup_map
482                .get(instruction_account.index_in_transaction as usize)
483                .expect("Deduplication map must contain this account")
484                as usize;
485
486            let Ok([current_account, reference_account]) =
487                instruction_accounts.get_disjoint_mut([current_index, other_account_index])
488            else {
489                continue;
490            };
491
492            // The deduplication procedure must have used the first occurrence of the account
493            // as the source of truths for the flags.
494            current_account
495                .set_is_signer(current_account.is_signer() || reference_account.is_signer());
496            current_account
497                .set_is_writable(current_account.is_writable() || reference_account.is_writable());
498        }
499    }
500
501    /// A version of `configure_top_level_instruction` to help creating the deduplication map in tests
502    pub fn configure_top_level_instruction_for_tests(
503        &mut self,
504        program_index: IndexOfAccount,
505        mut instruction_accounts: Vec<InstructionAccount>,
506        instruction_data: Vec<u8>,
507    ) -> Result<(), InstructionError> {
508        debug_assert!(instruction_accounts.len() <= u8::MAX as usize);
509        let dedup_map = Self::deduplicate_accounts(
510            self.get_number_of_accounts() as usize,
511            &mut instruction_accounts,
512        );
513
514        self.configure_instruction_at_index(
515            self.next_top_level_instruction_index,
516            program_index,
517            instruction_accounts,
518            dedup_map,
519            Cow::Owned(instruction_data),
520            None,
521        )?;
522        Ok(())
523    }
524
525    /// A helper function to facilitate creating a CPI in tests
526    pub fn configure_next_cpi_for_tests(
527        &mut self,
528        program_index: IndexOfAccount,
529        mut instruction_accounts: Vec<InstructionAccount>,
530        instruction_data: Vec<u8>,
531    ) -> Result<(), InstructionError> {
532        debug_assert!(instruction_accounts.len() <= u8::MAX as usize);
533        let dedup_map = Self::deduplicate_accounts(
534            self.get_number_of_accounts() as usize,
535            &mut instruction_accounts,
536        );
537        let caller_index = self.get_current_instruction_index()?;
538        let cpi_index = self.get_instruction_trace_length();
539        self.configure_instruction_at_index(
540            cpi_index,
541            program_index,
542            instruction_accounts,
543            dedup_map,
544            Cow::Owned(instruction_data),
545            Some(caller_index as u16),
546        )?;
547        Ok(())
548    }
549
550    /// Pushes the next instruction
551    pub fn push(&mut self, detect_overflow_early: bool) -> Result<(), InstructionError> {
552        let nesting_level = self.get_instruction_stack_height();
553        if !self.instruction_stack.is_empty() && self.lamports_delta.get() != 0 {
554            return Err(InstructionError::UnbalancedInstruction);
555        }
556        {
557            let instruction = self
558                .instruction_trace
559                .last_mut()
560                .ok_or(InstructionError::CallDepth)?;
561            instruction.nesting_level = nesting_level as u16;
562        }
563
564        if !detect_overflow_early
565            && self.number_of_called_instructions_in_trace() >= self.instruction_trace_capacity
566        {
567            return Err(InstructionError::MaxInstructionTraceLengthExceeded);
568        }
569
570        if detect_overflow_early
571            && ((self.transaction_frame.total_number_of_instructions_in_trace as usize
572                > self.instruction_trace_capacity)
573                || (self.number_of_called_instructions_in_trace()
574                    >= self.instruction_trace_capacity))
575        {
576            // The condition after the OR is necessary if in any case we execute more top
577            // level instructions than expected, since `total_number_of_instructions_in_trace` is
578            // with the number of top level instructions when TransactionContext is created
579            // and only updated for CPIs afterward.
580            //
581            // Having more top-level instructions than TransactionContext was created with
582            // should be impossible to happen with the current code configuration, so the extra
583            // check serves as a failsafe guard.
584            return Err(InstructionError::MaxInstructionTraceLengthExceeded);
585        }
586
587        let (index_in_trace, current_top_level_instruction) = if self.instruction_stack.is_empty() {
588            let index = self.next_top_level_instruction_index;
589            self.next_top_level_instruction_index =
590                self.next_top_level_instruction_index.saturating_add(1);
591            (index, index)
592        } else {
593            let index = self.get_instruction_trace_length();
594            self.transaction_frame.number_of_cpis_in_trace = self
595                .transaction_frame
596                .number_of_cpis_in_trace
597                .saturating_add(1);
598            self.instruction_trace.push(InstructionFrame::default());
599            (
600                index,
601                self.next_top_level_instruction_index.saturating_sub(1),
602            )
603        };
604
605        if nesting_level >= self.instruction_stack_capacity {
606            return Err(InstructionError::CallDepth);
607        }
608        self.transaction_frame.current_executing_instruction = index_in_trace as u16;
609        self.instruction_stack.push(index_in_trace);
610        if let Some(index_in_transaction) = self.find_index_of_account(&instructions::id()) {
611            let mut mut_account_ref = self.accounts.try_borrow_mut(index_in_transaction)?;
612            if mut_account_ref.owner() != &solana_sdk_ids::sysvar::id() {
613                return Err(InstructionError::InvalidAccountOwner);
614            }
615            instructions::store_current_index_checked(
616                mut_account_ref.data_as_mut_slice(),
617                current_top_level_instruction as u16,
618            )?;
619        }
620        Ok(())
621    }
622
623    /// Pops the current instruction
624    pub fn pop(&mut self) -> Result<(), InstructionError> {
625        if self.instruction_stack.is_empty() {
626            return Err(InstructionError::CallDepth);
627        }
628        // Verify (before we pop) that the total sum of all lamports in this instruction did not change
629        let detected_an_unbalanced_instruction =
630            self.get_current_instruction_context()
631                .and_then(|instruction_context| {
632                    // Verify all executable accounts have no outstanding refs
633                    self.accounts
634                        .try_borrow_mut(
635                            instruction_context.get_index_of_program_account_in_transaction()?,
636                        )
637                        .map_err(|err| {
638                            if err == InstructionError::AccountBorrowFailed {
639                                InstructionError::AccountBorrowOutstanding
640                            } else {
641                                err
642                            }
643                        })?;
644                    Ok(self.lamports_delta.get() != 0)
645                });
646        // Always pop, even if we `detected_an_unbalanced_instruction`
647        self.instruction_stack.pop();
648        if let Some(instr_idx) = self.instruction_stack.last() {
649            self.transaction_frame.current_executing_instruction = *instr_idx as u16;
650        }
651        if detected_an_unbalanced_instruction? {
652            Err(InstructionError::UnbalancedInstruction)
653        } else {
654            Ok(())
655        }
656    }
657
658    /// Gets the return data of the current instruction or any above
659    pub fn get_return_data(&self) -> (&Pubkey, &[u8]) {
660        (
661            &self.transaction_frame.return_data_pubkey,
662            &self.return_data_bytes,
663        )
664    }
665
666    /// Set the return data of the current instruction
667    pub fn set_return_data(
668        &mut self,
669        program_id: Pubkey,
670        data: Vec<u8>,
671    ) -> Result<(), InstructionError> {
672        self.transaction_frame.return_data_pubkey = program_id;
673        self.transaction_frame
674            .return_data_scratchpad
675            .set_len(data.len() as u64);
676        self.return_data_bytes = data;
677        Ok(())
678    }
679
680    /// Returns a new account data write access handler
681    pub fn access_violation_handler(
682        &self,
683        virtual_address_space_adjustments: bool,
684        account_data_direct_mapping: bool,
685    ) -> AccessViolationHandler {
686        let accounts = Rc::clone(&self.accounts);
687        Box::new(
688            move |_context_object: &mut dyn ContextObject,
689                  region: &mut MemoryRegion,
690                  address_space_reserved_for_account: u64,
691                  access_type: AccessType,
692                  vm_addr: u64,
693                  len: u64| {
694                if access_type == AccessType::Load {
695                    return;
696                }
697                let Some(index_in_transaction) = region.access_violation_handler_payload else {
698                    // This region is not a writable account.
699                    return;
700                };
701                let region_vm_addr_start = region.vm_addr_range().start;
702                let requested_length = vm_addr
703                    .saturating_add(len)
704                    .saturating_sub(region_vm_addr_start)
705                    as usize;
706                if requested_length > address_space_reserved_for_account as usize {
707                    // Requested access goes further than the account region.
708                    return;
709                }
710
711                // The four calls below can't really fail. If they fail because of a bug,
712                // whatever is writing will trigger an EbpfError::AccessViolation like
713                // if the region was readonly, and the transaction will fail gracefully.
714                let Ok(mut account) = accounts.try_borrow_mut(index_in_transaction) else {
715                    debug_assert!(false);
716                    return;
717                };
718                if accounts.touch(index_in_transaction).is_err() {
719                    debug_assert!(false);
720                    return;
721                }
722
723                let remaining_allowed_growth = MAX_ACCOUNT_DATA_GROWTH_PER_TRANSACTION
724                    .saturating_sub(accounts.resize_delta())
725                    .max(0) as usize;
726
727                if requested_length > region.len() {
728                    // Realloc immediately here to fit the requested access,
729                    // then later in CPI or deserialization realloc again to the
730                    // account length the program stored in AccountInfo.
731                    let old_len = account.data().len();
732                    let new_len = (address_space_reserved_for_account as usize)
733                        .min(MAX_ACCOUNT_DATA_LEN as usize)
734                        .min(old_len.saturating_add(remaining_allowed_growth));
735                    // The last two min operations ensure the following:
736                    debug_assert!(accounts.can_data_be_resized(old_len, new_len).is_ok());
737                    if accounts
738                        .update_accounts_resize_delta(old_len, new_len)
739                        .is_err()
740                    {
741                        return;
742                    }
743
744                    account.resize(new_len, 0);
745                    let data_ptr = region.host_buffer().ptr() as *mut u8;
746                    let new_buffer = std::ptr::slice_from_raw_parts_mut(data_ptr, new_len);
747                    unsafe {
748                        // SAFETY:
749                        //
750                        // Contract from `MemoryRegion::redirect`: MemoryRegion must point to a
751                        // valid object live for the duration of this `MemoryMapping`.
752                        //
753                        // Evidence: There are two distinct cases, when the account buffer is
754                        // serialized and when the account buffer is directly mapped.
755                        // * In the serialization case we continue pointing at the same buffer as
756                        // before, and the original buffer must have satisfied the liveness
757                        // condition before.
758                        // * In the direct mapping case `account.resize` invalidates the buffer this
759                        // region has been pointing at, but this is fixed up later in the "unshare"
760                        // branch later.
761                        // * In the serialization case the section of serialized buffer has the
762                        // necessary padding after the account payload proper for resize. This
763                        // padding is a part of the originally constructed `MemoryRegion` and is
764                        // only later subsliced to not expose it before the first access to the
765                        // area (which invokes this handler.)
766                        //
767                        // Contract from `MemoryRegion::redirect`: For `MemoryRegion`s marked
768                        // writable, the host buffer must accept arbitrary bytes being overwritten
769                        // without it resulting in unsoundness.
770                        //
771                        // Evidence: The account payloads dont have any internal soundness
772                        // invariants. The buffer in the serialization case starts off and remains
773                        // writable (even though the HostBuffer might have been initially created as
774                        // immutable.) In the direct mapping case we redirect the region to the
775                        // buffer stored in the account later on.
776                        region.redirect(new_buffer);
777                    }
778                }
779
780                // Potentially unshare / make the account shared data unique (CoW logic).
781                if virtual_address_space_adjustments && account_data_direct_mapping {
782                    unsafe {
783                        // SAFETY: refer to the comment above.
784                        region.redirect(account.raw_mut_data_slice());
785                    }
786                }
787            },
788        )
789    }
790
791    /// Take ownership of the instruction trace
792    pub fn take_instruction_trace(&mut self) -> InstructionTrace<'_> {
793        // The last frame is a placeholder for the next instruction to be executed, so it
794        // is empty.
795        self.instruction_trace.pop();
796        (
797            std::mem::take(&mut self.instruction_trace),
798            std::mem::take(&mut self.instruction_accounts),
799            std::mem::take(&mut self.instruction_data),
800        )
801    }
802
803    /// Called instruction are those that the program runtime has already called into. It
804    /// encompasses instructions under execution (e.g. all nested CPIs are already called) and
805    /// finished ones.
806    ///
807    /// Top level instructions that have not yet been executed aren't considered called.
808    pub fn number_of_called_instructions_in_trace(&self) -> usize {
809        self.next_top_level_instruction_index
810            .saturating_add(self.transaction_frame.number_of_cpis_in_trace as usize)
811    }
812
813    /// Return next top level instruction to execute
814    pub fn next_top_level_instruction_index(&self) -> usize {
815        self.next_top_level_instruction_index
816    }
817
818    /// Return number of CPIs in instruction trace
819    pub fn number_of_cpis_in_trace(&self) -> usize {
820        self.transaction_frame.number_of_cpis_in_trace as usize
821    }
822}
823
824/// Return data at the end of a transaction
825#[cfg(not(any(target_arch = "bpf", target_arch = "sbf")))]
826#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
827#[cfg_attr(feature = "wincode", derive(wincode::SchemaRead, wincode::SchemaWrite))]
828#[derive(Clone, Debug, Default, PartialEq, Eq)]
829pub struct TransactionReturnData {
830    pub program_id: Pubkey,
831    pub data: Vec<u8>,
832}
833
834/// Everything that needs to be recorded from a TransactionContext after execution
835#[cfg(not(any(target_arch = "bpf", target_arch = "sbf")))]
836pub struct ExecutionRecord {
837    pub accounts: Vec<KeyedAccountSharedData>,
838    pub return_data: TransactionReturnData,
839    /// Parallel to `accounts`: whether each account was modified by the VM.
840    pub touched_flags: Box<[bool]>,
841    pub accounts_resize_delta: i64,
842}
843
844/// Used by the bank in the runtime to write back the processed accounts and recorded instructions
845#[cfg(not(any(target_arch = "bpf", target_arch = "sbf")))]
846impl From<TransactionContext<'_>> for ExecutionRecord {
847    fn from(context: TransactionContext) -> Self {
848        let (accounts, touched_flags, resize_delta) = Rc::try_unwrap(context.accounts)
849            .expect("transaction_context.accounts has unexpected outstanding refs")
850            .take();
851
852        // The flags only needed interior mutability while the VM was running.
853        // Now that we own them, unwrap the per-element `Cell`s into a plain
854        // `Box<[bool]>`. `Vec::from` reuses the box's allocation and the mapped
855        // collect reuses that same buffer in place (`Cell<bool>` and `bool` have
856        // identical layout), so no reallocation occurs.
857        let touched_flags: Box<[bool]> = Vec::from(touched_flags)
858            .into_iter()
859            .map(|flag| flag.into_inner())
860            .collect();
861
862        let return_data = TransactionReturnData {
863            program_id: context.transaction_frame.return_data_pubkey,
864            data: context.return_data_bytes,
865        };
866
867        Self {
868            accounts,
869            return_data,
870            touched_flags,
871            accounts_resize_delta: Cell::into_inner(resize_delta),
872        }
873    }
874}
875
876#[cfg(all(test, not(target_arch = "sbf"), not(target_arch = "bpf")))]
877mod tests {
878    use {super::*, crate::MAX_INSTRUCTION_TRACE_LENGTH, test_case::test_case};
879
880    #[test]
881    fn test_instructions_sysvar_store_index_checked() {
882        let build_transaction_context = |account: AccountSharedData| {
883            TransactionContext::new(
884                vec![
885                    (Pubkey::new_unique(), AccountSharedData::default()),
886                    (instructions::id(), account),
887                ],
888                Rent::default(),
889                /* max_instruction_stack_depth */ 2,
890                /* max_instruction_trace_length */ 2,
891                /* number_of_top_level_instructions */ 1,
892            )
893        };
894
895        let correct_space = 2;
896        let rent_exempt_lamports = Rent::default().minimum_balance(correct_space);
897
898        // First try it with the wrong owner.
899        let account = AccountSharedData::new_with_data(
900            rent_exempt_lamports,
901            vec![0; correct_space],
902            &Pubkey::new_unique(),
903        );
904        assert_eq!(
905            build_transaction_context(account).push(true),
906            Err(InstructionError::InvalidAccountOwner),
907        );
908
909        // Now with the wrong data length.
910        let account = AccountSharedData::empty(rent_exempt_lamports, &solana_sdk_ids::sysvar::id());
911        assert_eq!(
912            build_transaction_context(account).push(true),
913            Err(InstructionError::AccountDataTooSmall),
914        );
915
916        // Finally provide the correct account setup.
917        let account = AccountSharedData::new_with_data(
918            rent_exempt_lamports,
919            vec![0; correct_space],
920            &solana_sdk_ids::sysvar::id(),
921        );
922        assert_eq!(build_transaction_context(account).push(true), Ok(()),);
923    }
924
925    #[test]
926    fn test_invalid_native_loader_index() {
927        let mut transaction_context = TransactionContext::new(
928            vec![(
929                Pubkey::new_unique(),
930                AccountSharedData::new_with_data(1, vec![0; 1], &Pubkey::new_unique()),
931            )],
932            Rent::default(),
933            20,
934            20,
935            1,
936        );
937
938        transaction_context
939            .configure_top_level_instruction_for_tests(
940                u16::MAX,
941                vec![InstructionAccount::new(0, false, false)],
942                vec![],
943            )
944            .unwrap();
945        let instruction_context = transaction_context.get_next_instruction_context().unwrap();
946
947        let result = instruction_context.get_index_of_program_account_in_transaction();
948        assert_eq!(result, Err(InstructionError::MissingAccount));
949
950        let result = instruction_context.get_program_key();
951        assert_eq!(result, Err(InstructionError::MissingAccount));
952
953        let result = instruction_context.get_program_owner();
954        assert_eq!(result.err(), Some(InstructionError::MissingAccount));
955    }
956
957    #[test]
958    fn test_instruction_shared_items() {
959        let transaction_accounts = vec![(Pubkey::new_unique(), AccountSharedData::default()); 11];
960        let mut transaction_context =
961            TransactionContext::new(transaction_accounts, Rent::default(), 20, 20, 3);
962
963        let instruction_accounts_1 = vec![
964            InstructionAccount::new(0, false, true),
965            InstructionAccount::new(3, true, false),
966        ];
967        transaction_context
968            .configure_top_level_instruction_for_tests(
969                1,
970                instruction_accounts_1.clone(),
971                vec![1, 2, 3, 4],
972            )
973            .unwrap();
974        transaction_context.push(true).unwrap();
975
976        let instruction_accounts_2 = vec![
977            InstructionAccount::new(0, false, true),
978            InstructionAccount::new(3, true, false),
979            InstructionAccount::new(5, false, false),
980        ];
981        transaction_context
982            .configure_top_level_instruction_for_tests(
983                1,
984                instruction_accounts_2.clone(),
985                vec![5, 6, 7, 8, 9],
986            )
987            .unwrap();
988        transaction_context.push(true).unwrap();
989
990        let instruction_accounts_3 = vec![
991            InstructionAccount::new(0, false, true),
992            InstructionAccount::new(3, true, false),
993            InstructionAccount::new(5, false, false),
994            InstructionAccount::new(3, false, false),
995            InstructionAccount::new(10, false, false),
996        ];
997        transaction_context
998            .configure_top_level_instruction_for_tests(
999                1,
1000                instruction_accounts_3.clone(),
1001                vec![10, 11],
1002            )
1003            .unwrap();
1004        transaction_context.push(true).unwrap();
1005
1006        let first_ix_context = transaction_context
1007            .get_instruction_context_at_index_in_trace(0)
1008            .unwrap();
1009        assert_eq!(
1010            instruction_accounts_1.as_slice(),
1011            first_ix_context.instruction_accounts
1012        );
1013        assert_eq!(
1014            *first_ix_context.instruction_data,
1015            **transaction_context.instruction_data.first().unwrap()
1016        );
1017        for (idx_in_ix, acc) in instruction_accounts_1.iter().enumerate() {
1018            assert_eq!(
1019                *first_ix_context
1020                    .dedup_map
1021                    .get(acc.index_in_transaction as usize)
1022                    .unwrap(),
1023                idx_in_ix as u8
1024            );
1025        }
1026
1027        let second_ix_context = transaction_context
1028            .get_instruction_context_at_index_in_trace(1)
1029            .unwrap();
1030        assert_eq!(
1031            instruction_accounts_2.as_slice(),
1032            second_ix_context.instruction_accounts
1033        );
1034        assert_eq!(
1035            *second_ix_context.instruction_data,
1036            **transaction_context.instruction_data.get(1).unwrap()
1037        );
1038        for (idx_in_ix, acc) in instruction_accounts_2.iter().enumerate() {
1039            assert_eq!(
1040                *second_ix_context
1041                    .dedup_map
1042                    .get(acc.index_in_transaction as usize)
1043                    .unwrap(),
1044                idx_in_ix as u8
1045            );
1046        }
1047
1048        let third_ix_context = transaction_context
1049            .get_instruction_context_at_index_in_trace(2)
1050            .unwrap();
1051        assert_eq!(
1052            vec![
1053                InstructionAccount::new(0, false, true),
1054                InstructionAccount::new(3, true, false),
1055                InstructionAccount::new(5, false, false),
1056                InstructionAccount::new(3, true, false),
1057                InstructionAccount::new(10, false, false),
1058            ]
1059            .as_slice(),
1060            third_ix_context.instruction_accounts
1061        );
1062
1063        assert_eq!(
1064            *third_ix_context.instruction_data,
1065            **transaction_context.instruction_data.get(2).unwrap()
1066        );
1067        for (idx_in_ix, acc) in instruction_accounts_3.iter().enumerate() {
1068            if idx_in_ix == 3 {
1069                assert_eq!(
1070                    *third_ix_context
1071                        .dedup_map
1072                        .get(acc.index_in_transaction as usize)
1073                        .unwrap(),
1074                    1
1075                );
1076            } else {
1077                assert_eq!(
1078                    *third_ix_context
1079                        .dedup_map
1080                        .get(acc.index_in_transaction as usize)
1081                        .unwrap(),
1082                    idx_in_ix as u8
1083                );
1084            }
1085        }
1086    }
1087
1088    #[test]
1089    fn test_number_of_instructions() {
1090        let transaction_accounts = vec![(Pubkey::new_unique(), AccountSharedData::default()); 3];
1091        let mut transaction_context =
1092            TransactionContext::new(transaction_accounts, Rent::default(), 20, 20, 2);
1093        assert_eq!(
1094            transaction_context
1095                .transaction_frame
1096                .number_of_cpis_in_trace,
1097            0
1098        );
1099
1100        // Instruction #0
1101        transaction_context
1102            .configure_instruction_at_index(
1103                0,
1104                0,
1105                vec![InstructionAccount::new(1, false, false)],
1106                vec![0; 3],
1107                Vec::new().into(),
1108                None,
1109            )
1110            .unwrap();
1111
1112        // Instruction #1
1113        transaction_context
1114            .configure_instruction_at_index(
1115                1,
1116                0,
1117                vec![InstructionAccount::new(1, false, false)],
1118                vec![0; 3],
1119                Vec::new().into(),
1120                None,
1121            )
1122            .unwrap();
1123
1124        // Executing instruction #0
1125        transaction_context.push(true).unwrap();
1126        assert_eq!(
1127            transaction_context
1128                .transaction_frame
1129                .current_executing_instruction,
1130            0
1131        );
1132        assert_eq!(
1133            transaction_context.number_of_called_instructions_in_trace(),
1134            1
1135        );
1136
1137        assert_eq!(
1138            transaction_context
1139                .transaction_frame
1140                .total_number_of_instructions_in_trace,
1141            2
1142        );
1143
1144        assert_eq!(
1145            transaction_context
1146                .transaction_frame
1147                .number_of_cpis_in_trace,
1148            0
1149        );
1150
1151        assert_eq!(
1152            transaction_context
1153                .transaction_frame
1154                .cpi_data_scratchpad
1155                .ptr(),
1156            GUEST_INSTRUCTION_DATA_BASE_ADDRESS.saturating_add(GUEST_REGION_SIZE.saturating_mul(2))
1157        );
1158        assert_eq!(
1159            transaction_context
1160                .transaction_frame
1161                .cpi_data_scratchpad
1162                .len(),
1163            0,
1164        );
1165        assert_eq!(
1166            transaction_context
1167                .transaction_frame
1168                .cpi_accounts_scratchpad
1169                .ptr(),
1170            GUEST_INSTRUCTION_ACCOUNT_BASE_ADDRESS
1171                .saturating_add(GUEST_REGION_SIZE.saturating_mul(2))
1172        );
1173        assert_eq!(
1174            transaction_context
1175                .transaction_frame
1176                .cpi_data_scratchpad
1177                .len(),
1178            0,
1179        );
1180
1181        assert_eq!(
1182            transaction_context.number_of_called_instructions_in_trace(),
1183            1
1184        );
1185
1186        // Instruction #0 does a CPI.
1187        transaction_context
1188            .configure_next_cpi_for_tests(
1189                0,
1190                vec![InstructionAccount::new(2, false, true)],
1191                Vec::new(),
1192            )
1193            .unwrap();
1194
1195        transaction_context.push(true).unwrap();
1196        assert_eq!(
1197            transaction_context
1198                .transaction_frame
1199                .current_executing_instruction,
1200            2
1201        );
1202
1203        assert_eq!(
1204            transaction_context
1205                .transaction_frame
1206                .total_number_of_instructions_in_trace,
1207            3
1208        );
1209        assert_eq!(
1210            transaction_context
1211                .transaction_frame
1212                .number_of_cpis_in_trace,
1213            1
1214        );
1215        assert_eq!(
1216            transaction_context.number_of_called_instructions_in_trace(),
1217            2
1218        );
1219
1220        assert_eq!(
1221            transaction_context
1222                .transaction_frame
1223                .cpi_data_scratchpad
1224                .ptr(),
1225            GUEST_INSTRUCTION_DATA_BASE_ADDRESS.saturating_add(GUEST_REGION_SIZE.saturating_mul(3))
1226        );
1227        assert_eq!(
1228            transaction_context
1229                .transaction_frame
1230                .cpi_accounts_scratchpad
1231                .ptr(),
1232            GUEST_INSTRUCTION_ACCOUNT_BASE_ADDRESS
1233                .saturating_add(GUEST_REGION_SIZE.saturating_mul(3))
1234        );
1235
1236        // A nested CPI
1237        transaction_context
1238            .configure_next_cpi_for_tests(
1239                0,
1240                vec![InstructionAccount::new(2, false, true)],
1241                Vec::new(),
1242            )
1243            .unwrap();
1244
1245        transaction_context.push(true).unwrap();
1246        assert_eq!(
1247            transaction_context
1248                .transaction_frame
1249                .current_executing_instruction,
1250            3
1251        );
1252
1253        assert_eq!(
1254            transaction_context
1255                .transaction_frame
1256                .total_number_of_instructions_in_trace,
1257            4
1258        );
1259
1260        assert_eq!(
1261            transaction_context
1262                .transaction_frame
1263                .cpi_data_scratchpad
1264                .ptr(),
1265            GUEST_INSTRUCTION_DATA_BASE_ADDRESS.saturating_add(GUEST_REGION_SIZE.saturating_mul(4))
1266        );
1267        assert_eq!(
1268            transaction_context
1269                .transaction_frame
1270                .cpi_accounts_scratchpad
1271                .ptr(),
1272            GUEST_INSTRUCTION_ACCOUNT_BASE_ADDRESS
1273                .saturating_add(GUEST_REGION_SIZE.saturating_mul(4))
1274        );
1275
1276        assert_eq!(
1277            transaction_context
1278                .transaction_frame
1279                .number_of_cpis_in_trace,
1280            2
1281        );
1282
1283        assert_eq!(
1284            transaction_context.number_of_called_instructions_in_trace(),
1285            3
1286        );
1287        // Return from nested CPI
1288        transaction_context.pop().unwrap();
1289        assert_eq!(
1290            transaction_context.number_of_called_instructions_in_trace(),
1291            3
1292        );
1293
1294        assert_eq!(
1295            transaction_context
1296                .transaction_frame
1297                .total_number_of_instructions_in_trace,
1298            4
1299        );
1300        assert_eq!(
1301            transaction_context
1302                .transaction_frame
1303                .number_of_cpis_in_trace,
1304            2,
1305        );
1306        assert_eq!(
1307            transaction_context
1308                .transaction_frame
1309                .current_executing_instruction,
1310            2
1311        );
1312
1313        // A second nested CPI
1314        transaction_context
1315            .configure_next_cpi_for_tests(
1316                0,
1317                vec![InstructionAccount::new(2, false, true)],
1318                Vec::new(),
1319            )
1320            .unwrap();
1321
1322        transaction_context.push(true).unwrap();
1323        assert_eq!(
1324            transaction_context
1325                .transaction_frame
1326                .current_executing_instruction,
1327            4
1328        );
1329
1330        assert_eq!(
1331            transaction_context
1332                .transaction_frame
1333                .total_number_of_instructions_in_trace,
1334            5
1335        );
1336
1337        assert_eq!(
1338            transaction_context
1339                .transaction_frame
1340                .cpi_data_scratchpad
1341                .ptr(),
1342            GUEST_INSTRUCTION_DATA_BASE_ADDRESS.saturating_add(GUEST_REGION_SIZE.saturating_mul(5))
1343        );
1344        assert_eq!(
1345            transaction_context
1346                .transaction_frame
1347                .cpi_accounts_scratchpad
1348                .ptr(),
1349            GUEST_INSTRUCTION_ACCOUNT_BASE_ADDRESS
1350                .saturating_add(GUEST_REGION_SIZE.saturating_mul(5))
1351        );
1352
1353        assert_eq!(
1354            transaction_context
1355                .transaction_frame
1356                .number_of_cpis_in_trace,
1357            3
1358        );
1359        assert_eq!(
1360            transaction_context.number_of_called_instructions_in_trace(),
1361            4
1362        );
1363
1364        // Return from second nested CPI
1365        transaction_context.pop().unwrap();
1366
1367        assert_eq!(
1368            transaction_context
1369                .transaction_frame
1370                .current_executing_instruction,
1371            2
1372        );
1373
1374        assert_eq!(
1375            transaction_context
1376                .transaction_frame
1377                .total_number_of_instructions_in_trace,
1378            5
1379        );
1380
1381        assert_eq!(
1382            transaction_context
1383                .transaction_frame
1384                .cpi_data_scratchpad
1385                .ptr(),
1386            GUEST_INSTRUCTION_DATA_BASE_ADDRESS.saturating_add(GUEST_REGION_SIZE.saturating_mul(5))
1387        );
1388        assert_eq!(
1389            transaction_context
1390                .transaction_frame
1391                .cpi_accounts_scratchpad
1392                .ptr(),
1393            GUEST_INSTRUCTION_ACCOUNT_BASE_ADDRESS
1394                .saturating_add(GUEST_REGION_SIZE.saturating_mul(5))
1395        );
1396
1397        assert_eq!(
1398            transaction_context
1399                .transaction_frame
1400                .number_of_cpis_in_trace,
1401            3
1402        );
1403
1404        // Return from first CPI
1405        transaction_context.pop().unwrap();
1406        assert_eq!(
1407            transaction_context.number_of_called_instructions_in_trace(),
1408            4
1409        );
1410
1411        assert_eq!(
1412            transaction_context
1413                .transaction_frame
1414                .current_executing_instruction,
1415            0
1416        );
1417
1418        assert_eq!(
1419            transaction_context
1420                .transaction_frame
1421                .total_number_of_instructions_in_trace,
1422            5
1423        );
1424
1425        assert_eq!(
1426            transaction_context
1427                .transaction_frame
1428                .cpi_data_scratchpad
1429                .ptr(),
1430            GUEST_INSTRUCTION_DATA_BASE_ADDRESS.saturating_add(GUEST_REGION_SIZE.saturating_mul(5))
1431        );
1432        assert_eq!(
1433            transaction_context
1434                .transaction_frame
1435                .cpi_accounts_scratchpad
1436                .ptr(),
1437            GUEST_INSTRUCTION_ACCOUNT_BASE_ADDRESS
1438                .saturating_add(GUEST_REGION_SIZE.saturating_mul(5))
1439        );
1440
1441        assert_eq!(
1442            transaction_context
1443                .transaction_frame
1444                .number_of_cpis_in_trace,
1445            3,
1446        );
1447
1448        // Let's go to Instruction #1 (top level)
1449        transaction_context.pop().unwrap();
1450        transaction_context.push(true).unwrap();
1451        assert_eq!(
1452            transaction_context
1453                .transaction_frame
1454                .current_executing_instruction,
1455            1,
1456        );
1457        assert_eq!(
1458            transaction_context
1459                .transaction_frame
1460                .number_of_cpis_in_trace,
1461            3
1462        );
1463
1464        // Instruction #1 will do a CPI.
1465        transaction_context
1466            .configure_next_cpi_for_tests(
1467                0,
1468                vec![InstructionAccount::new(2, false, true)],
1469                Vec::new(),
1470            )
1471            .unwrap();
1472
1473        transaction_context.push(true).unwrap();
1474
1475        assert_eq!(
1476            transaction_context
1477                .transaction_frame
1478                .current_executing_instruction,
1479            5,
1480        );
1481
1482        assert_eq!(
1483            transaction_context
1484                .transaction_frame
1485                .total_number_of_instructions_in_trace,
1486            6
1487        );
1488
1489        assert_eq!(
1490            transaction_context
1491                .transaction_frame
1492                .cpi_data_scratchpad
1493                .ptr(),
1494            GUEST_INSTRUCTION_DATA_BASE_ADDRESS.saturating_add(GUEST_REGION_SIZE.saturating_mul(6))
1495        );
1496        assert_eq!(
1497            transaction_context
1498                .transaction_frame
1499                .cpi_accounts_scratchpad
1500                .ptr(),
1501            GUEST_INSTRUCTION_ACCOUNT_BASE_ADDRESS
1502                .saturating_add(GUEST_REGION_SIZE.saturating_mul(6))
1503        );
1504
1505        assert_eq!(
1506            transaction_context
1507                .transaction_frame
1508                .number_of_cpis_in_trace,
1509            4
1510        );
1511        assert_eq!(
1512            transaction_context.number_of_called_instructions_in_trace(),
1513            6
1514        );
1515
1516        // Return from CPI
1517        transaction_context.pop().unwrap();
1518        assert_eq!(
1519            transaction_context
1520                .transaction_frame
1521                .number_of_cpis_in_trace,
1522            4
1523        );
1524        assert_eq!(
1525            transaction_context
1526                .transaction_frame
1527                .current_executing_instruction,
1528            1,
1529        );
1530
1531        transaction_context.pop().unwrap();
1532    }
1533
1534    #[test]
1535    fn test_get_current_instruction_index() {
1536        let transaction_accounts = vec![(Pubkey::new_unique(), AccountSharedData::default()); 3];
1537        let mut transaction_context =
1538            TransactionContext::new(transaction_accounts, Rent::default(), 20, 20, 2);
1539
1540        // First top level instruction
1541        transaction_context
1542            .configure_instruction_at_index(
1543                0,
1544                1,
1545                vec![
1546                    InstructionAccount::new(0, false, false),
1547                    InstructionAccount::new(1, false, false),
1548                ],
1549                vec![u8::MAX; 3],
1550                Cow::Owned(Vec::new()),
1551                None,
1552            )
1553            .unwrap();
1554
1555        // Second top-level instruction
1556        transaction_context
1557            .configure_instruction_at_index(
1558                1,
1559                1,
1560                vec![
1561                    InstructionAccount::new(0, false, false),
1562                    InstructionAccount::new(1, false, true),
1563                ],
1564                vec![u8::MAX; 3],
1565                Cow::Owned(Vec::new()),
1566                None,
1567            )
1568            .unwrap();
1569
1570        transaction_context.push(true).unwrap();
1571        assert_eq!(
1572            transaction_context.get_current_instruction_index().unwrap(),
1573            0
1574        );
1575
1576        transaction_context.pop().unwrap();
1577
1578        transaction_context.push(true).unwrap();
1579        assert_eq!(
1580            transaction_context.get_current_instruction_index().unwrap(),
1581            1
1582        );
1583
1584        // Simulating a CPI
1585        transaction_context
1586            .configure_next_cpi_for_tests(
1587                1,
1588                vec![
1589                    InstructionAccount::new(0, false, true),
1590                    InstructionAccount::new(1, false, false),
1591                ],
1592                Vec::new(),
1593            )
1594            .unwrap();
1595        transaction_context.push(true).unwrap();
1596        assert_eq!(
1597            transaction_context.get_current_instruction_index().unwrap(),
1598            2
1599        );
1600
1601        // Yet another CPI
1602        transaction_context
1603            .configure_next_cpi_for_tests(
1604                1,
1605                vec![
1606                    InstructionAccount::new(0, false, true),
1607                    InstructionAccount::new(1, false, false),
1608                ],
1609                Vec::new(),
1610            )
1611            .unwrap();
1612        transaction_context.push(true).unwrap();
1613        assert_eq!(
1614            transaction_context.get_current_instruction_index().unwrap(),
1615            3
1616        );
1617
1618        // CPI return
1619        transaction_context.pop().unwrap();
1620        assert_eq!(
1621            transaction_context.get_current_instruction_index().unwrap(),
1622            2
1623        );
1624
1625        // CPI return 2
1626        transaction_context.pop().unwrap();
1627        assert_eq!(
1628            transaction_context.get_current_instruction_index().unwrap(),
1629            1
1630        );
1631    }
1632
1633    #[test]
1634    fn test_deduplicate_accounts() {
1635        let mut instruction_accounts = vec![
1636            InstructionAccount::new(0, false, true), // Account 0, writable
1637            InstructionAccount::new(1, true, false), // Account 1, signer
1638            InstructionAccount::new(0, false, false), // Account 0 again, not writable
1639            InstructionAccount::new(2, false, true), // Account 2, writable
1640            InstructionAccount::new(1, true, false), // Account 1 again, signer
1641        ];
1642
1643        let dedup_map = TransactionContext::deduplicate_accounts(
1644            instruction_accounts.len(),
1645            &mut instruction_accounts,
1646        );
1647
1648        // Check that the dedup_map correctly maps duplicate accounts
1649        assert_eq!(
1650            *dedup_map.first().unwrap(),
1651            0,
1652            "account must be a duplicate of itself"
1653        );
1654        assert_eq!(
1655            *dedup_map.get(1).unwrap(),
1656            1,
1657            "account must be a duplicate of itself"
1658        );
1659        assert_eq!(
1660            *dedup_map.get(2).unwrap(),
1661            3,
1662            "account must be a duplicate of itself"
1663        );
1664
1665        // Check that duplicate accounts are properly merged
1666        let acc = instruction_accounts.first().unwrap();
1667        assert_eq!(acc.index_in_transaction, 0);
1668        assert!(
1669            !acc.is_signer(),
1670            "Must not be a signer because account 1 is not signer"
1671        );
1672        assert!(
1673            acc.is_writable(),
1674            "Must be writable because account 0 is writable"
1675        );
1676
1677        let acc = instruction_accounts.get(1).unwrap();
1678        assert_eq!(acc.index_in_transaction, 1);
1679        assert!(
1680            acc.is_signer(),
1681            "Must be signer because account 1 is signer"
1682        );
1683        assert!(
1684            !acc.is_writable(),
1685            "Must not be writable because account 1 is not writable"
1686        );
1687
1688        let acc = instruction_accounts.get(2).unwrap();
1689        assert_eq!(acc.index_in_transaction, 0);
1690        assert!(!acc.is_signer(), "Should be merged from account 1");
1691        assert!(acc.is_writable(), "Should be merged from account 0");
1692
1693        let acc = instruction_accounts.get(3).unwrap();
1694        assert_eq!(acc.index_in_transaction, 2);
1695        assert!(!acc.is_signer());
1696        assert!(acc.is_writable());
1697
1698        let acc = instruction_accounts.get(4).unwrap();
1699        assert_eq!(acc.index_in_transaction, 1);
1700        assert!(
1701            acc.is_signer(),
1702            "Must be signer because account 1 is signer"
1703        );
1704        assert!(
1705            !acc.is_writable(),
1706            "Must not be writable because account 1 is not writable"
1707        );
1708
1709        // Verify that the deduplication map correctly identifies duplicates
1710        assert_eq!(
1711            *dedup_map.first().unwrap(),
1712            0,
1713            "account must be a duplicate of itself"
1714        );
1715        assert_eq!(
1716            *dedup_map.get(1).unwrap(),
1717            1,
1718            "account must be a duplicate of itself"
1719        );
1720        assert_eq!(
1721            *dedup_map.get(2).unwrap(),
1722            3,
1723            "account must be a duplicate of itself"
1724        );
1725    }
1726
1727    #[test]
1728    fn test_deduplicate_accounts_no_duplicates() {
1729        let mut instruction_accounts = vec![
1730            InstructionAccount::new(0, false, true),
1731            InstructionAccount::new(1, true, false),
1732            InstructionAccount::new(2, false, false),
1733        ];
1734
1735        let dedup_map = TransactionContext::deduplicate_accounts(
1736            instruction_accounts.len(),
1737            &mut instruction_accounts,
1738        );
1739
1740        // Check that the dedup_map correctly maps each account to itself
1741        assert_eq!(
1742            *dedup_map.first().unwrap(),
1743            0,
1744            "account must be a duplicate of itself"
1745        );
1746        assert_eq!(
1747            *dedup_map.get(1).unwrap(),
1748            1,
1749            "account must be a duplicate of itself"
1750        );
1751        assert_eq!(
1752            *dedup_map.get(2).unwrap(),
1753            2,
1754            "account must be a duplicate of itself"
1755        );
1756
1757        // Check that accounts are not modified
1758        let acc = instruction_accounts.first().unwrap();
1759        assert_eq!(acc.index_in_transaction, 0);
1760        assert!(!acc.is_signer());
1761        assert!(acc.is_writable());
1762
1763        let acc = instruction_accounts.get(1).unwrap();
1764        assert_eq!(acc.index_in_transaction, 1);
1765        assert!(acc.is_signer());
1766        assert!(!acc.is_writable());
1767
1768        let acc = instruction_accounts.get(2).unwrap();
1769        assert_eq!(acc.index_in_transaction, 2);
1770        assert!(!acc.is_signer());
1771        assert!(!acc.is_writable());
1772    }
1773
1774    #[test]
1775    fn test_deduplicate_accounts_all_duplicates() {
1776        let mut instruction_accounts = vec![
1777            InstructionAccount::new(0, false, true),
1778            InstructionAccount::new(0, true, false),
1779            InstructionAccount::new(0, false, false),
1780        ];
1781
1782        let dedup_map = TransactionContext::deduplicate_accounts(
1783            instruction_accounts.len(),
1784            &mut instruction_accounts,
1785        );
1786
1787        // Check that all accounts map to the first occurrence (index 0)
1788        assert_eq!(
1789            *dedup_map.first().unwrap(),
1790            0,
1791            "account must be a duplicate of itself"
1792        );
1793        for idx in dedup_map.iter().skip(1) {
1794            assert_eq!(*idx, u8::MAX);
1795        }
1796
1797        // Check that the first account has combined flags
1798        let acc = instruction_accounts.first().unwrap();
1799        assert_eq!(acc.index_in_transaction, 0);
1800        assert!(
1801            acc.is_signer(),
1802            "Should be signer because of second account"
1803        );
1804        assert!(
1805            acc.is_writable(),
1806            "Should be writable because of first account"
1807        );
1808
1809        // Check that the other accounts have the same flags as the first
1810        let acc = instruction_accounts.get(1).unwrap();
1811        assert_eq!(acc.index_in_transaction, 0);
1812        assert!(acc.is_signer());
1813        assert!(acc.is_writable());
1814
1815        let acc = instruction_accounts.get(2).unwrap();
1816        assert_eq!(acc.index_in_transaction, 0);
1817        assert!(acc.is_signer());
1818        assert!(acc.is_writable());
1819    }
1820
1821    #[test_case(false; "simd_582_disabled")]
1822    #[test_case(true; "simd_582_enabled")]
1823    fn test_max_instruction_trace_len_exceeded(fail_early: bool) {
1824        const IX_TRACE_CAPACITY: usize = 5;
1825        let transaction_accounts = vec![(Pubkey::new_unique(), AccountSharedData::default()); 3];
1826
1827        for number_of_top_level_instructions in 4..=5 {
1828            // Simulate a trace capacity of 5
1829            let mut transaction_context = TransactionContext::new(
1830                transaction_accounts.clone(),
1831                Rent::default(),
1832                6,
1833                IX_TRACE_CAPACITY,
1834                number_of_top_level_instructions,
1835            );
1836
1837            // Configure top-level instructions
1838            for idx_to_configure in 0..number_of_top_level_instructions {
1839                transaction_context
1840                    .configure_instruction_at_index(
1841                        idx_to_configure,
1842                        0,
1843                        vec![InstructionAccount::new(1, false, false)],
1844                        vec![0; 3],
1845                        Vec::new().into(),
1846                        None,
1847                    )
1848                    .unwrap();
1849            }
1850
1851            // Execute instructions
1852            let mut pushed_ixs: usize = 0;
1853            let mut ix_in_trace = number_of_top_level_instructions;
1854            for ix_num in 0..number_of_top_level_instructions {
1855                let result = transaction_context.push(fail_early);
1856                pushed_ixs = pushed_ixs.saturating_add(1);
1857                if !fail_early && pushed_ixs > IX_TRACE_CAPACITY {
1858                    assert_eq!(pushed_ixs, IX_TRACE_CAPACITY.saturating_add(1));
1859                    assert_eq!(
1860                        transaction_context.number_of_called_instructions_in_trace(),
1861                        IX_TRACE_CAPACITY
1862                    );
1863                    assert_eq!(
1864                        result,
1865                        Err(InstructionError::MaxInstructionTraceLengthExceeded)
1866                    );
1867                    break;
1868                } else {
1869                    assert!(result.is_ok());
1870                }
1871
1872                // Two first ixs perform a CPI
1873                if ix_num < 2 {
1874                    transaction_context
1875                        .configure_next_cpi_for_tests(
1876                            0,
1877                            vec![InstructionAccount::new(2, false, false)],
1878                            Vec::new(),
1879                        )
1880                        .unwrap();
1881
1882                    ix_in_trace = ix_in_trace.saturating_add(1);
1883                    pushed_ixs = pushed_ixs.saturating_add(1);
1884                    let result = transaction_context.push(fail_early);
1885                    if fail_early && ix_in_trace > IX_TRACE_CAPACITY {
1886                        assert_eq!(ix_in_trace, IX_TRACE_CAPACITY.saturating_add(1));
1887                        assert_eq!(
1888                            transaction_context
1889                                .transaction_frame
1890                                .total_number_of_instructions_in_trace
1891                                as usize,
1892                            IX_TRACE_CAPACITY.saturating_add(1)
1893                        );
1894                        assert_eq!(
1895                            result,
1896                            Err(InstructionError::MaxInstructionTraceLengthExceeded)
1897                        );
1898                        break;
1899                    } else {
1900                        assert!(result.is_ok());
1901                    }
1902                    transaction_context.pop().unwrap();
1903                }
1904                transaction_context.pop().unwrap();
1905            }
1906        }
1907    }
1908
1909    #[test_case(false; "simd_582_disabled")]
1910    #[test_case(true; "simd_582_enabled")]
1911    fn test_max_instruction_trace_len_exceeded_64_ixs(fail_early: bool) {
1912        let transaction_accounts = vec![(Pubkey::new_unique(), AccountSharedData::default()); 3];
1913
1914        // Simulate a trace capacity of 5
1915        let mut transaction_context = TransactionContext::new(
1916            transaction_accounts.clone(),
1917            Rent::default(),
1918            6,
1919            MAX_INSTRUCTION_TRACE_LENGTH,
1920            MAX_INSTRUCTION_TRACE_LENGTH,
1921        );
1922
1923        // Configure top-level instructions
1924        for idx_to_configure in 0..MAX_INSTRUCTION_TRACE_LENGTH {
1925            transaction_context
1926                .configure_instruction_at_index(
1927                    idx_to_configure,
1928                    0,
1929                    vec![InstructionAccount::new(1, false, false)],
1930                    vec![0; 3],
1931                    Vec::new().into(),
1932                    None,
1933                )
1934                .unwrap();
1935        }
1936
1937        // Execute first top level instruction
1938        transaction_context.push(fail_early).unwrap();
1939        // It invokes a program
1940        transaction_context
1941            .configure_next_cpi_for_tests(
1942                0,
1943                vec![InstructionAccount::new(2, false, false)],
1944                Vec::new(),
1945            )
1946            .unwrap();
1947
1948        let result = transaction_context.push(fail_early);
1949        if fail_early {
1950            assert_eq!(
1951                result,
1952                Err(InstructionError::MaxInstructionTraceLengthExceeded)
1953            );
1954        } else {
1955            assert!(result.is_ok());
1956        }
1957    }
1958}