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