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
715                let remaining_allowed_growth = MAX_ACCOUNT_DATA_GROWTH_PER_TRANSACTION
716                    .saturating_sub(accounts.resize_delta())
717                    .max(0) as usize;
718
719                let new_len = if requested_length > region.len() {
720                    // Realloc immediately here to fit the requested access,
721                    // then later in CPI or deserialization realloc again to the
722                    // account length the program stored in AccountInfo.
723                    let old_len = account.data().len();
724                    let new_len = (address_space_reserved_for_account as usize)
725                        .min(MAX_ACCOUNT_DATA_LEN as usize)
726                        .min(old_len.saturating_add(remaining_allowed_growth));
727                    // The last two min operations ensure the following:
728                    debug_assert!(accounts.can_data_be_resized(old_len, new_len).is_ok());
729                    if requested_length > new_len
730                        || accounts
731                            .update_accounts_resize_delta(old_len, new_len)
732                            .is_err()
733                    {
734                        return;
735                    }
736                    Some(new_len)
737                } else {
738                    None
739                };
740
741                if accounts.touch(index_in_transaction).is_err() {
742                    debug_assert!(false);
743                    return;
744                }
745
746                if let Some(new_len) = new_len {
747                    account.resize(new_len, 0);
748                    let data_ptr = region.host_buffer().ptr() as *mut u8;
749                    let new_buffer = std::ptr::slice_from_raw_parts_mut(data_ptr, new_len);
750                    unsafe {
751                        // SAFETY:
752                        //
753                        // Contract from `MemoryRegion::redirect`: MemoryRegion must point to a
754                        // valid object live for the duration of this `MemoryMapping`.
755                        //
756                        // Evidence: There are two distinct cases, when the account buffer is
757                        // serialized and when the account buffer is directly mapped.
758                        // * In the serialization case we continue pointing at the same buffer as
759                        // before, and the original buffer must have satisfied the liveness
760                        // condition before.
761                        // * In the direct mapping case `account.resize` invalidates the buffer this
762                        // region has been pointing at, but this is fixed up later in the "unshare"
763                        // branch later.
764                        // * In the serialization case the section of serialized buffer has the
765                        // necessary padding after the account payload proper for resize. This
766                        // padding is a part of the originally constructed `MemoryRegion` and is
767                        // only later subsliced to not expose it before the first access to the
768                        // area (which invokes this handler.)
769                        //
770                        // Contract from `MemoryRegion::redirect`: For `MemoryRegion`s marked
771                        // writable, the host buffer must accept arbitrary bytes being overwritten
772                        // without it resulting in unsoundness.
773                        //
774                        // Evidence: The account payloads dont have any internal soundness
775                        // invariants. The buffer in the serialization case starts off and remains
776                        // writable (even though the HostBuffer might have been initially created as
777                        // immutable.) In the direct mapping case we redirect the region to the
778                        // buffer stored in the account later on.
779                        region.redirect(new_buffer);
780                    }
781                }
782
783                // Potentially unshare / make the account shared data unique (CoW logic).
784                if virtual_address_space_adjustments && account_data_direct_mapping {
785                    unsafe {
786                        // SAFETY: refer to the comment above.
787                        region.redirect(account.raw_mut_data_slice());
788                    }
789                }
790            },
791        )
792    }
793
794    /// Take ownership of the instruction trace
795    pub fn take_instruction_trace(&mut self) -> InstructionTrace<'_> {
796        // The last frame is a placeholder for the next instruction to be executed, so it
797        // is empty.
798        self.instruction_trace.pop();
799        (
800            std::mem::take(&mut self.instruction_trace),
801            std::mem::take(&mut self.instruction_accounts),
802            std::mem::take(&mut self.instruction_data),
803        )
804    }
805
806    /// Called instruction are those that the program runtime has already called into. It
807    /// encompasses instructions under execution (e.g. all nested CPIs are already called) and
808    /// finished ones.
809    ///
810    /// Top level instructions that have not yet been executed aren't considered called.
811    pub fn number_of_called_instructions_in_trace(&self) -> usize {
812        self.next_top_level_instruction_index
813            .saturating_add(self.transaction_frame.number_of_cpis_in_trace as usize)
814    }
815
816    /// Return next top level instruction to execute
817    pub fn next_top_level_instruction_index(&self) -> usize {
818        self.next_top_level_instruction_index
819    }
820
821    /// Return number of CPIs in instruction trace
822    pub fn number_of_cpis_in_trace(&self) -> usize {
823        self.transaction_frame.number_of_cpis_in_trace as usize
824    }
825}
826
827/// Return data at the end of a transaction
828#[cfg(not(any(target_arch = "bpf", target_arch = "sbf")))]
829#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
830#[cfg_attr(feature = "wincode", derive(wincode::SchemaRead, wincode::SchemaWrite))]
831#[derive(Clone, Debug, Default, PartialEq, Eq)]
832pub struct TransactionReturnData {
833    pub program_id: Pubkey,
834    pub data: Vec<u8>,
835}
836
837/// Everything that needs to be recorded from a TransactionContext after execution
838#[cfg(not(any(target_arch = "bpf", target_arch = "sbf")))]
839pub struct ExecutionRecord {
840    pub accounts: Vec<KeyedAccountSharedData>,
841    pub return_data: TransactionReturnData,
842    /// Parallel to `accounts`: whether each account was modified by the VM.
843    pub touched_flags: Box<[bool]>,
844    pub accounts_resize_delta: i64,
845}
846
847/// Used by the bank in the runtime to write back the processed accounts and recorded instructions
848#[cfg(not(any(target_arch = "bpf", target_arch = "sbf")))]
849impl From<TransactionContext<'_>> for ExecutionRecord {
850    fn from(context: TransactionContext) -> Self {
851        let (accounts, touched_flags, resize_delta) = Rc::try_unwrap(context.accounts)
852            .expect("transaction_context.accounts has unexpected outstanding refs")
853            .take();
854
855        // The flags only needed interior mutability while the VM was running.
856        // Now that we own them, unwrap the per-element `Cell`s into a plain
857        // `Box<[bool]>`. `Vec::from` reuses the box's allocation and the mapped
858        // collect reuses that same buffer in place (`Cell<bool>` and `bool` have
859        // identical layout), so no reallocation occurs.
860        let touched_flags: Box<[bool]> = Vec::from(touched_flags)
861            .into_iter()
862            .map(|flag| flag.into_inner())
863            .collect();
864
865        let return_data = TransactionReturnData {
866            program_id: context.transaction_frame.return_data_pubkey,
867            data: context.return_data_bytes,
868        };
869
870        Self {
871            accounts,
872            return_data,
873            touched_flags,
874            accounts_resize_delta: Cell::into_inner(resize_delta),
875        }
876    }
877}
878
879#[cfg(all(test, not(target_arch = "sbf"), not(target_arch = "bpf")))]
880mod tests {
881    use {super::*, crate::MAX_INSTRUCTION_TRACE_LENGTH, test_case::test_case};
882
883    #[test]
884    fn test_instructions_sysvar_store_index_checked() {
885        let build_transaction_context = |account: AccountSharedData| {
886            TransactionContext::new(
887                vec![
888                    (Pubkey::new_unique(), AccountSharedData::default()),
889                    (instructions::id(), account),
890                ],
891                Rent::default(),
892                /* max_instruction_stack_depth */ 2,
893                /* max_instruction_trace_length */ 2,
894                /* number_of_top_level_instructions */ 1,
895            )
896        };
897
898        let correct_space = 2;
899        let rent_exempt_lamports = Rent::default().minimum_balance(correct_space);
900
901        // First try it with the wrong owner.
902        let account = AccountSharedData::new_with_data(
903            rent_exempt_lamports,
904            vec![0; correct_space],
905            &Pubkey::new_unique(),
906        );
907        assert_eq!(
908            build_transaction_context(account).push(true),
909            Err(InstructionError::InvalidAccountOwner),
910        );
911
912        // Now with the wrong data length.
913        let account =
914            AccountSharedData::new(rent_exempt_lamports, 0, &solana_sdk_ids::sysvar::id());
915        assert_eq!(
916            build_transaction_context(account).push(true),
917            Err(InstructionError::AccountDataTooSmall),
918        );
919
920        // Finally provide the correct account setup.
921        let account = AccountSharedData::new_with_data(
922            rent_exempt_lamports,
923            vec![0; correct_space],
924            &solana_sdk_ids::sysvar::id(),
925        );
926        assert_eq!(build_transaction_context(account).push(true), Ok(()),);
927    }
928
929    #[test]
930    fn test_invalid_native_loader_index() {
931        let mut transaction_context = TransactionContext::new(
932            vec![(
933                Pubkey::new_unique(),
934                AccountSharedData::new_with_data(1, vec![0; 1], &Pubkey::new_unique()),
935            )],
936            Rent::default(),
937            20,
938            20,
939            1,
940        );
941
942        transaction_context
943            .configure_top_level_instruction_for_tests(
944                u16::MAX,
945                vec![InstructionAccount::new(0, false, false)],
946                vec![],
947            )
948            .unwrap();
949        let instruction_context = transaction_context.get_next_instruction_context().unwrap();
950
951        let result = instruction_context.get_index_of_program_account_in_transaction();
952        assert_eq!(result, Err(InstructionError::MissingAccount));
953
954        let result = instruction_context.get_program_key();
955        assert_eq!(result, Err(InstructionError::MissingAccount));
956
957        let result = instruction_context.get_program_owner();
958        assert_eq!(result.err(), Some(InstructionError::MissingAccount));
959    }
960
961    #[test]
962    fn test_instruction_shared_items() {
963        let transaction_accounts = vec![(Pubkey::new_unique(), AccountSharedData::default()); 11];
964        let mut transaction_context =
965            TransactionContext::new(transaction_accounts, Rent::default(), 20, 20, 3);
966
967        let instruction_accounts_1 = vec![
968            InstructionAccount::new(0, false, true),
969            InstructionAccount::new(3, true, false),
970        ];
971        transaction_context
972            .configure_top_level_instruction_for_tests(
973                1,
974                instruction_accounts_1.clone(),
975                vec![1, 2, 3, 4],
976            )
977            .unwrap();
978        transaction_context.push(true).unwrap();
979
980        let instruction_accounts_2 = vec![
981            InstructionAccount::new(0, false, true),
982            InstructionAccount::new(3, true, false),
983            InstructionAccount::new(5, false, false),
984        ];
985        transaction_context
986            .configure_top_level_instruction_for_tests(
987                1,
988                instruction_accounts_2.clone(),
989                vec![5, 6, 7, 8, 9],
990            )
991            .unwrap();
992        transaction_context.push(true).unwrap();
993
994        let instruction_accounts_3 = vec![
995            InstructionAccount::new(0, false, true),
996            InstructionAccount::new(3, true, false),
997            InstructionAccount::new(5, false, false),
998            InstructionAccount::new(3, false, false),
999            InstructionAccount::new(10, false, false),
1000        ];
1001        transaction_context
1002            .configure_top_level_instruction_for_tests(
1003                1,
1004                instruction_accounts_3.clone(),
1005                vec![10, 11],
1006            )
1007            .unwrap();
1008        transaction_context.push(true).unwrap();
1009
1010        let first_ix_context = transaction_context
1011            .get_instruction_context_at_index_in_trace(0)
1012            .unwrap();
1013        assert_eq!(
1014            instruction_accounts_1.as_slice(),
1015            first_ix_context.instruction_accounts
1016        );
1017        assert_eq!(
1018            *first_ix_context.instruction_data,
1019            **transaction_context.instruction_data.first().unwrap()
1020        );
1021        for (idx_in_ix, acc) in instruction_accounts_1.iter().enumerate() {
1022            assert_eq!(
1023                *first_ix_context
1024                    .dedup_map
1025                    .get(acc.index_in_transaction as usize)
1026                    .unwrap(),
1027                idx_in_ix as u8
1028            );
1029        }
1030
1031        let second_ix_context = transaction_context
1032            .get_instruction_context_at_index_in_trace(1)
1033            .unwrap();
1034        assert_eq!(
1035            instruction_accounts_2.as_slice(),
1036            second_ix_context.instruction_accounts
1037        );
1038        assert_eq!(
1039            *second_ix_context.instruction_data,
1040            **transaction_context.instruction_data.get(1).unwrap()
1041        );
1042        for (idx_in_ix, acc) in instruction_accounts_2.iter().enumerate() {
1043            assert_eq!(
1044                *second_ix_context
1045                    .dedup_map
1046                    .get(acc.index_in_transaction as usize)
1047                    .unwrap(),
1048                idx_in_ix as u8
1049            );
1050        }
1051
1052        let third_ix_context = transaction_context
1053            .get_instruction_context_at_index_in_trace(2)
1054            .unwrap();
1055        assert_eq!(
1056            vec![
1057                InstructionAccount::new(0, false, true),
1058                InstructionAccount::new(3, true, false),
1059                InstructionAccount::new(5, false, false),
1060                InstructionAccount::new(3, true, false),
1061                InstructionAccount::new(10, false, false),
1062            ]
1063            .as_slice(),
1064            third_ix_context.instruction_accounts
1065        );
1066
1067        assert_eq!(
1068            *third_ix_context.instruction_data,
1069            **transaction_context.instruction_data.get(2).unwrap()
1070        );
1071        for (idx_in_ix, acc) in instruction_accounts_3.iter().enumerate() {
1072            if idx_in_ix == 3 {
1073                assert_eq!(
1074                    *third_ix_context
1075                        .dedup_map
1076                        .get(acc.index_in_transaction as usize)
1077                        .unwrap(),
1078                    1
1079                );
1080            } else {
1081                assert_eq!(
1082                    *third_ix_context
1083                        .dedup_map
1084                        .get(acc.index_in_transaction as usize)
1085                        .unwrap(),
1086                    idx_in_ix as u8
1087                );
1088            }
1089        }
1090    }
1091
1092    #[test]
1093    fn test_number_of_instructions() {
1094        let transaction_accounts = vec![(Pubkey::new_unique(), AccountSharedData::default()); 3];
1095        let mut transaction_context =
1096            TransactionContext::new(transaction_accounts, Rent::default(), 20, 20, 2);
1097        assert_eq!(
1098            transaction_context
1099                .transaction_frame
1100                .number_of_cpis_in_trace,
1101            0
1102        );
1103
1104        // Instruction #0
1105        transaction_context
1106            .configure_instruction_at_index(
1107                0,
1108                0,
1109                vec![InstructionAccount::new(1, false, false)],
1110                vec![0; 3],
1111                Vec::new().into(),
1112                None,
1113            )
1114            .unwrap();
1115
1116        // Instruction #1
1117        transaction_context
1118            .configure_instruction_at_index(
1119                1,
1120                0,
1121                vec![InstructionAccount::new(1, false, false)],
1122                vec![0; 3],
1123                Vec::new().into(),
1124                None,
1125            )
1126            .unwrap();
1127
1128        // Executing instruction #0
1129        transaction_context.push(true).unwrap();
1130        assert_eq!(
1131            transaction_context
1132                .transaction_frame
1133                .current_executing_instruction,
1134            0
1135        );
1136        assert_eq!(
1137            transaction_context.number_of_called_instructions_in_trace(),
1138            1
1139        );
1140
1141        assert_eq!(
1142            transaction_context
1143                .transaction_frame
1144                .total_number_of_instructions_in_trace,
1145            2
1146        );
1147
1148        assert_eq!(
1149            transaction_context
1150                .transaction_frame
1151                .number_of_cpis_in_trace,
1152            0
1153        );
1154
1155        assert_eq!(
1156            transaction_context
1157                .transaction_frame
1158                .cpi_data_scratchpad
1159                .ptr(),
1160            GUEST_INSTRUCTION_DATA_BASE_ADDRESS.saturating_add(GUEST_REGION_SIZE.saturating_mul(2))
1161        );
1162        assert_eq!(
1163            transaction_context
1164                .transaction_frame
1165                .cpi_data_scratchpad
1166                .len(),
1167            0,
1168        );
1169        assert_eq!(
1170            transaction_context
1171                .transaction_frame
1172                .cpi_accounts_scratchpad
1173                .ptr(),
1174            GUEST_INSTRUCTION_ACCOUNT_BASE_ADDRESS
1175                .saturating_add(GUEST_REGION_SIZE.saturating_mul(2))
1176        );
1177        assert_eq!(
1178            transaction_context
1179                .transaction_frame
1180                .cpi_data_scratchpad
1181                .len(),
1182            0,
1183        );
1184
1185        assert_eq!(
1186            transaction_context.number_of_called_instructions_in_trace(),
1187            1
1188        );
1189
1190        // Instruction #0 does a CPI.
1191        transaction_context
1192            .configure_next_cpi_for_tests(
1193                0,
1194                vec![InstructionAccount::new(2, false, true)],
1195                Vec::new(),
1196            )
1197            .unwrap();
1198
1199        transaction_context.push(true).unwrap();
1200        assert_eq!(
1201            transaction_context
1202                .transaction_frame
1203                .current_executing_instruction,
1204            2
1205        );
1206
1207        assert_eq!(
1208            transaction_context
1209                .transaction_frame
1210                .total_number_of_instructions_in_trace,
1211            3
1212        );
1213        assert_eq!(
1214            transaction_context
1215                .transaction_frame
1216                .number_of_cpis_in_trace,
1217            1
1218        );
1219        assert_eq!(
1220            transaction_context.number_of_called_instructions_in_trace(),
1221            2
1222        );
1223
1224        assert_eq!(
1225            transaction_context
1226                .transaction_frame
1227                .cpi_data_scratchpad
1228                .ptr(),
1229            GUEST_INSTRUCTION_DATA_BASE_ADDRESS.saturating_add(GUEST_REGION_SIZE.saturating_mul(3))
1230        );
1231        assert_eq!(
1232            transaction_context
1233                .transaction_frame
1234                .cpi_accounts_scratchpad
1235                .ptr(),
1236            GUEST_INSTRUCTION_ACCOUNT_BASE_ADDRESS
1237                .saturating_add(GUEST_REGION_SIZE.saturating_mul(3))
1238        );
1239
1240        // A nested CPI
1241        transaction_context
1242            .configure_next_cpi_for_tests(
1243                0,
1244                vec![InstructionAccount::new(2, false, true)],
1245                Vec::new(),
1246            )
1247            .unwrap();
1248
1249        transaction_context.push(true).unwrap();
1250        assert_eq!(
1251            transaction_context
1252                .transaction_frame
1253                .current_executing_instruction,
1254            3
1255        );
1256
1257        assert_eq!(
1258            transaction_context
1259                .transaction_frame
1260                .total_number_of_instructions_in_trace,
1261            4
1262        );
1263
1264        assert_eq!(
1265            transaction_context
1266                .transaction_frame
1267                .cpi_data_scratchpad
1268                .ptr(),
1269            GUEST_INSTRUCTION_DATA_BASE_ADDRESS.saturating_add(GUEST_REGION_SIZE.saturating_mul(4))
1270        );
1271        assert_eq!(
1272            transaction_context
1273                .transaction_frame
1274                .cpi_accounts_scratchpad
1275                .ptr(),
1276            GUEST_INSTRUCTION_ACCOUNT_BASE_ADDRESS
1277                .saturating_add(GUEST_REGION_SIZE.saturating_mul(4))
1278        );
1279
1280        assert_eq!(
1281            transaction_context
1282                .transaction_frame
1283                .number_of_cpis_in_trace,
1284            2
1285        );
1286
1287        assert_eq!(
1288            transaction_context.number_of_called_instructions_in_trace(),
1289            3
1290        );
1291        // Return from nested CPI
1292        transaction_context.pop().unwrap();
1293        assert_eq!(
1294            transaction_context.number_of_called_instructions_in_trace(),
1295            3
1296        );
1297
1298        assert_eq!(
1299            transaction_context
1300                .transaction_frame
1301                .total_number_of_instructions_in_trace,
1302            4
1303        );
1304        assert_eq!(
1305            transaction_context
1306                .transaction_frame
1307                .number_of_cpis_in_trace,
1308            2,
1309        );
1310        assert_eq!(
1311            transaction_context
1312                .transaction_frame
1313                .current_executing_instruction,
1314            2
1315        );
1316
1317        // A second nested CPI
1318        transaction_context
1319            .configure_next_cpi_for_tests(
1320                0,
1321                vec![InstructionAccount::new(2, false, true)],
1322                Vec::new(),
1323            )
1324            .unwrap();
1325
1326        transaction_context.push(true).unwrap();
1327        assert_eq!(
1328            transaction_context
1329                .transaction_frame
1330                .current_executing_instruction,
1331            4
1332        );
1333
1334        assert_eq!(
1335            transaction_context
1336                .transaction_frame
1337                .total_number_of_instructions_in_trace,
1338            5
1339        );
1340
1341        assert_eq!(
1342            transaction_context
1343                .transaction_frame
1344                .cpi_data_scratchpad
1345                .ptr(),
1346            GUEST_INSTRUCTION_DATA_BASE_ADDRESS.saturating_add(GUEST_REGION_SIZE.saturating_mul(5))
1347        );
1348        assert_eq!(
1349            transaction_context
1350                .transaction_frame
1351                .cpi_accounts_scratchpad
1352                .ptr(),
1353            GUEST_INSTRUCTION_ACCOUNT_BASE_ADDRESS
1354                .saturating_add(GUEST_REGION_SIZE.saturating_mul(5))
1355        );
1356
1357        assert_eq!(
1358            transaction_context
1359                .transaction_frame
1360                .number_of_cpis_in_trace,
1361            3
1362        );
1363        assert_eq!(
1364            transaction_context.number_of_called_instructions_in_trace(),
1365            4
1366        );
1367
1368        // Return from second nested CPI
1369        transaction_context.pop().unwrap();
1370
1371        assert_eq!(
1372            transaction_context
1373                .transaction_frame
1374                .current_executing_instruction,
1375            2
1376        );
1377
1378        assert_eq!(
1379            transaction_context
1380                .transaction_frame
1381                .total_number_of_instructions_in_trace,
1382            5
1383        );
1384
1385        assert_eq!(
1386            transaction_context
1387                .transaction_frame
1388                .cpi_data_scratchpad
1389                .ptr(),
1390            GUEST_INSTRUCTION_DATA_BASE_ADDRESS.saturating_add(GUEST_REGION_SIZE.saturating_mul(5))
1391        );
1392        assert_eq!(
1393            transaction_context
1394                .transaction_frame
1395                .cpi_accounts_scratchpad
1396                .ptr(),
1397            GUEST_INSTRUCTION_ACCOUNT_BASE_ADDRESS
1398                .saturating_add(GUEST_REGION_SIZE.saturating_mul(5))
1399        );
1400
1401        assert_eq!(
1402            transaction_context
1403                .transaction_frame
1404                .number_of_cpis_in_trace,
1405            3
1406        );
1407
1408        // Return from first CPI
1409        transaction_context.pop().unwrap();
1410        assert_eq!(
1411            transaction_context.number_of_called_instructions_in_trace(),
1412            4
1413        );
1414
1415        assert_eq!(
1416            transaction_context
1417                .transaction_frame
1418                .current_executing_instruction,
1419            0
1420        );
1421
1422        assert_eq!(
1423            transaction_context
1424                .transaction_frame
1425                .total_number_of_instructions_in_trace,
1426            5
1427        );
1428
1429        assert_eq!(
1430            transaction_context
1431                .transaction_frame
1432                .cpi_data_scratchpad
1433                .ptr(),
1434            GUEST_INSTRUCTION_DATA_BASE_ADDRESS.saturating_add(GUEST_REGION_SIZE.saturating_mul(5))
1435        );
1436        assert_eq!(
1437            transaction_context
1438                .transaction_frame
1439                .cpi_accounts_scratchpad
1440                .ptr(),
1441            GUEST_INSTRUCTION_ACCOUNT_BASE_ADDRESS
1442                .saturating_add(GUEST_REGION_SIZE.saturating_mul(5))
1443        );
1444
1445        assert_eq!(
1446            transaction_context
1447                .transaction_frame
1448                .number_of_cpis_in_trace,
1449            3,
1450        );
1451
1452        // Let's go to Instruction #1 (top level)
1453        transaction_context.pop().unwrap();
1454        transaction_context.push(true).unwrap();
1455        assert_eq!(
1456            transaction_context
1457                .transaction_frame
1458                .current_executing_instruction,
1459            1,
1460        );
1461        assert_eq!(
1462            transaction_context
1463                .transaction_frame
1464                .number_of_cpis_in_trace,
1465            3
1466        );
1467
1468        // Instruction #1 will do a CPI.
1469        transaction_context
1470            .configure_next_cpi_for_tests(
1471                0,
1472                vec![InstructionAccount::new(2, false, true)],
1473                Vec::new(),
1474            )
1475            .unwrap();
1476
1477        transaction_context.push(true).unwrap();
1478
1479        assert_eq!(
1480            transaction_context
1481                .transaction_frame
1482                .current_executing_instruction,
1483            5,
1484        );
1485
1486        assert_eq!(
1487            transaction_context
1488                .transaction_frame
1489                .total_number_of_instructions_in_trace,
1490            6
1491        );
1492
1493        assert_eq!(
1494            transaction_context
1495                .transaction_frame
1496                .cpi_data_scratchpad
1497                .ptr(),
1498            GUEST_INSTRUCTION_DATA_BASE_ADDRESS.saturating_add(GUEST_REGION_SIZE.saturating_mul(6))
1499        );
1500        assert_eq!(
1501            transaction_context
1502                .transaction_frame
1503                .cpi_accounts_scratchpad
1504                .ptr(),
1505            GUEST_INSTRUCTION_ACCOUNT_BASE_ADDRESS
1506                .saturating_add(GUEST_REGION_SIZE.saturating_mul(6))
1507        );
1508
1509        assert_eq!(
1510            transaction_context
1511                .transaction_frame
1512                .number_of_cpis_in_trace,
1513            4
1514        );
1515        assert_eq!(
1516            transaction_context.number_of_called_instructions_in_trace(),
1517            6
1518        );
1519
1520        // Return from CPI
1521        transaction_context.pop().unwrap();
1522        assert_eq!(
1523            transaction_context
1524                .transaction_frame
1525                .number_of_cpis_in_trace,
1526            4
1527        );
1528        assert_eq!(
1529            transaction_context
1530                .transaction_frame
1531                .current_executing_instruction,
1532            1,
1533        );
1534
1535        transaction_context.pop().unwrap();
1536    }
1537
1538    #[test]
1539    fn test_get_current_instruction_index() {
1540        let transaction_accounts = vec![(Pubkey::new_unique(), AccountSharedData::default()); 3];
1541        let mut transaction_context =
1542            TransactionContext::new(transaction_accounts, Rent::default(), 20, 20, 2);
1543
1544        // First top level instruction
1545        transaction_context
1546            .configure_instruction_at_index(
1547                0,
1548                1,
1549                vec![
1550                    InstructionAccount::new(0, false, false),
1551                    InstructionAccount::new(1, false, false),
1552                ],
1553                vec![u8::MAX; 3],
1554                Cow::Owned(Vec::new()),
1555                None,
1556            )
1557            .unwrap();
1558
1559        // Second top-level instruction
1560        transaction_context
1561            .configure_instruction_at_index(
1562                1,
1563                1,
1564                vec![
1565                    InstructionAccount::new(0, false, false),
1566                    InstructionAccount::new(1, false, true),
1567                ],
1568                vec![u8::MAX; 3],
1569                Cow::Owned(Vec::new()),
1570                None,
1571            )
1572            .unwrap();
1573
1574        transaction_context.push(true).unwrap();
1575        assert_eq!(
1576            transaction_context.get_current_instruction_index().unwrap(),
1577            0
1578        );
1579
1580        transaction_context.pop().unwrap();
1581
1582        transaction_context.push(true).unwrap();
1583        assert_eq!(
1584            transaction_context.get_current_instruction_index().unwrap(),
1585            1
1586        );
1587
1588        // Simulating a CPI
1589        transaction_context
1590            .configure_next_cpi_for_tests(
1591                1,
1592                vec![
1593                    InstructionAccount::new(0, false, true),
1594                    InstructionAccount::new(1, false, false),
1595                ],
1596                Vec::new(),
1597            )
1598            .unwrap();
1599        transaction_context.push(true).unwrap();
1600        assert_eq!(
1601            transaction_context.get_current_instruction_index().unwrap(),
1602            2
1603        );
1604
1605        // Yet another CPI
1606        transaction_context
1607            .configure_next_cpi_for_tests(
1608                1,
1609                vec![
1610                    InstructionAccount::new(0, false, true),
1611                    InstructionAccount::new(1, false, false),
1612                ],
1613                Vec::new(),
1614            )
1615            .unwrap();
1616        transaction_context.push(true).unwrap();
1617        assert_eq!(
1618            transaction_context.get_current_instruction_index().unwrap(),
1619            3
1620        );
1621
1622        // CPI return
1623        transaction_context.pop().unwrap();
1624        assert_eq!(
1625            transaction_context.get_current_instruction_index().unwrap(),
1626            2
1627        );
1628
1629        // CPI return 2
1630        transaction_context.pop().unwrap();
1631        assert_eq!(
1632            transaction_context.get_current_instruction_index().unwrap(),
1633            1
1634        );
1635    }
1636
1637    #[test]
1638    fn test_deduplicate_accounts() {
1639        let mut instruction_accounts = vec![
1640            InstructionAccount::new(0, false, true), // Account 0, writable
1641            InstructionAccount::new(1, true, false), // Account 1, signer
1642            InstructionAccount::new(0, false, false), // Account 0 again, not writable
1643            InstructionAccount::new(2, false, true), // Account 2, writable
1644            InstructionAccount::new(1, true, false), // Account 1 again, signer
1645        ];
1646
1647        let dedup_map = TransactionContext::deduplicate_accounts(
1648            instruction_accounts.len(),
1649            &mut instruction_accounts,
1650        );
1651
1652        // Check that the dedup_map correctly maps duplicate accounts
1653        assert_eq!(
1654            *dedup_map.first().unwrap(),
1655            0,
1656            "account must be a duplicate of itself"
1657        );
1658        assert_eq!(
1659            *dedup_map.get(1).unwrap(),
1660            1,
1661            "account must be a duplicate of itself"
1662        );
1663        assert_eq!(
1664            *dedup_map.get(2).unwrap(),
1665            3,
1666            "account must be a duplicate of itself"
1667        );
1668
1669        // Check that duplicate accounts are properly merged
1670        let acc = instruction_accounts.first().unwrap();
1671        assert_eq!(acc.index_in_transaction, 0);
1672        assert!(
1673            !acc.is_signer(),
1674            "Must not be a signer because account 1 is not signer"
1675        );
1676        assert!(
1677            acc.is_writable(),
1678            "Must be writable because account 0 is writable"
1679        );
1680
1681        let acc = instruction_accounts.get(1).unwrap();
1682        assert_eq!(acc.index_in_transaction, 1);
1683        assert!(
1684            acc.is_signer(),
1685            "Must be signer because account 1 is signer"
1686        );
1687        assert!(
1688            !acc.is_writable(),
1689            "Must not be writable because account 1 is not writable"
1690        );
1691
1692        let acc = instruction_accounts.get(2).unwrap();
1693        assert_eq!(acc.index_in_transaction, 0);
1694        assert!(!acc.is_signer(), "Should be merged from account 1");
1695        assert!(acc.is_writable(), "Should be merged from account 0");
1696
1697        let acc = instruction_accounts.get(3).unwrap();
1698        assert_eq!(acc.index_in_transaction, 2);
1699        assert!(!acc.is_signer());
1700        assert!(acc.is_writable());
1701
1702        let acc = instruction_accounts.get(4).unwrap();
1703        assert_eq!(acc.index_in_transaction, 1);
1704        assert!(
1705            acc.is_signer(),
1706            "Must be signer because account 1 is signer"
1707        );
1708        assert!(
1709            !acc.is_writable(),
1710            "Must not be writable because account 1 is not writable"
1711        );
1712
1713        // Verify that the deduplication map correctly identifies duplicates
1714        assert_eq!(
1715            *dedup_map.first().unwrap(),
1716            0,
1717            "account must be a duplicate of itself"
1718        );
1719        assert_eq!(
1720            *dedup_map.get(1).unwrap(),
1721            1,
1722            "account must be a duplicate of itself"
1723        );
1724        assert_eq!(
1725            *dedup_map.get(2).unwrap(),
1726            3,
1727            "account must be a duplicate of itself"
1728        );
1729    }
1730
1731    #[test]
1732    fn test_deduplicate_accounts_no_duplicates() {
1733        let mut instruction_accounts = vec![
1734            InstructionAccount::new(0, false, true),
1735            InstructionAccount::new(1, true, false),
1736            InstructionAccount::new(2, false, false),
1737        ];
1738
1739        let dedup_map = TransactionContext::deduplicate_accounts(
1740            instruction_accounts.len(),
1741            &mut instruction_accounts,
1742        );
1743
1744        // Check that the dedup_map correctly maps each account to itself
1745        assert_eq!(
1746            *dedup_map.first().unwrap(),
1747            0,
1748            "account must be a duplicate of itself"
1749        );
1750        assert_eq!(
1751            *dedup_map.get(1).unwrap(),
1752            1,
1753            "account must be a duplicate of itself"
1754        );
1755        assert_eq!(
1756            *dedup_map.get(2).unwrap(),
1757            2,
1758            "account must be a duplicate of itself"
1759        );
1760
1761        // Check that accounts are not modified
1762        let acc = instruction_accounts.first().unwrap();
1763        assert_eq!(acc.index_in_transaction, 0);
1764        assert!(!acc.is_signer());
1765        assert!(acc.is_writable());
1766
1767        let acc = instruction_accounts.get(1).unwrap();
1768        assert_eq!(acc.index_in_transaction, 1);
1769        assert!(acc.is_signer());
1770        assert!(!acc.is_writable());
1771
1772        let acc = instruction_accounts.get(2).unwrap();
1773        assert_eq!(acc.index_in_transaction, 2);
1774        assert!(!acc.is_signer());
1775        assert!(!acc.is_writable());
1776    }
1777
1778    #[test]
1779    fn test_deduplicate_accounts_all_duplicates() {
1780        let mut instruction_accounts = vec![
1781            InstructionAccount::new(0, false, true),
1782            InstructionAccount::new(0, true, false),
1783            InstructionAccount::new(0, false, false),
1784        ];
1785
1786        let dedup_map = TransactionContext::deduplicate_accounts(
1787            instruction_accounts.len(),
1788            &mut instruction_accounts,
1789        );
1790
1791        // Check that all accounts map to the first occurrence (index 0)
1792        assert_eq!(
1793            *dedup_map.first().unwrap(),
1794            0,
1795            "account must be a duplicate of itself"
1796        );
1797        for idx in dedup_map.iter().skip(1) {
1798            assert_eq!(*idx, u8::MAX);
1799        }
1800
1801        // Check that the first account has combined flags
1802        let acc = instruction_accounts.first().unwrap();
1803        assert_eq!(acc.index_in_transaction, 0);
1804        assert!(
1805            acc.is_signer(),
1806            "Should be signer because of second account"
1807        );
1808        assert!(
1809            acc.is_writable(),
1810            "Should be writable because of first account"
1811        );
1812
1813        // Check that the other accounts have the same flags as the first
1814        let acc = instruction_accounts.get(1).unwrap();
1815        assert_eq!(acc.index_in_transaction, 0);
1816        assert!(acc.is_signer());
1817        assert!(acc.is_writable());
1818
1819        let acc = instruction_accounts.get(2).unwrap();
1820        assert_eq!(acc.index_in_transaction, 0);
1821        assert!(acc.is_signer());
1822        assert!(acc.is_writable());
1823    }
1824
1825    #[test_case(false; "simd_582_disabled")]
1826    #[test_case(true; "simd_582_enabled")]
1827    fn test_max_instruction_trace_len_exceeded(fail_early: bool) {
1828        const IX_TRACE_CAPACITY: usize = 5;
1829        let transaction_accounts = vec![(Pubkey::new_unique(), AccountSharedData::default()); 3];
1830
1831        for number_of_top_level_instructions in 4..=5 {
1832            // Simulate a trace capacity of 5
1833            let mut transaction_context = TransactionContext::new(
1834                transaction_accounts.clone(),
1835                Rent::default(),
1836                6,
1837                IX_TRACE_CAPACITY,
1838                number_of_top_level_instructions,
1839            );
1840
1841            // Configure top-level instructions
1842            for idx_to_configure in 0..number_of_top_level_instructions {
1843                transaction_context
1844                    .configure_instruction_at_index(
1845                        idx_to_configure,
1846                        0,
1847                        vec![InstructionAccount::new(1, false, false)],
1848                        vec![0; 3],
1849                        Vec::new().into(),
1850                        None,
1851                    )
1852                    .unwrap();
1853            }
1854
1855            // Execute instructions
1856            let mut pushed_ixs: usize = 0;
1857            let mut ix_in_trace = number_of_top_level_instructions;
1858            for ix_num in 0..number_of_top_level_instructions {
1859                let result = transaction_context.push(fail_early);
1860                pushed_ixs = pushed_ixs.saturating_add(1);
1861                if !fail_early && pushed_ixs > IX_TRACE_CAPACITY {
1862                    assert_eq!(pushed_ixs, IX_TRACE_CAPACITY.saturating_add(1));
1863                    assert_eq!(
1864                        transaction_context.number_of_called_instructions_in_trace(),
1865                        IX_TRACE_CAPACITY
1866                    );
1867                    assert_eq!(
1868                        result,
1869                        Err(InstructionError::MaxInstructionTraceLengthExceeded)
1870                    );
1871                    break;
1872                } else {
1873                    assert!(result.is_ok());
1874                }
1875
1876                // Two first ixs perform a CPI
1877                if ix_num < 2 {
1878                    transaction_context
1879                        .configure_next_cpi_for_tests(
1880                            0,
1881                            vec![InstructionAccount::new(2, false, false)],
1882                            Vec::new(),
1883                        )
1884                        .unwrap();
1885
1886                    ix_in_trace = ix_in_trace.saturating_add(1);
1887                    pushed_ixs = pushed_ixs.saturating_add(1);
1888                    let result = transaction_context.push(fail_early);
1889                    if fail_early && ix_in_trace > IX_TRACE_CAPACITY {
1890                        assert_eq!(ix_in_trace, IX_TRACE_CAPACITY.saturating_add(1));
1891                        assert_eq!(
1892                            transaction_context
1893                                .transaction_frame
1894                                .total_number_of_instructions_in_trace
1895                                as usize,
1896                            IX_TRACE_CAPACITY.saturating_add(1)
1897                        );
1898                        assert_eq!(
1899                            result,
1900                            Err(InstructionError::MaxInstructionTraceLengthExceeded)
1901                        );
1902                        break;
1903                    } else {
1904                        assert!(result.is_ok());
1905                    }
1906                    transaction_context.pop().unwrap();
1907                }
1908                transaction_context.pop().unwrap();
1909            }
1910        }
1911    }
1912
1913    #[test_case(false; "simd_582_disabled")]
1914    #[test_case(true; "simd_582_enabled")]
1915    fn test_max_instruction_trace_len_exceeded_64_ixs(fail_early: bool) {
1916        let transaction_accounts = vec![(Pubkey::new_unique(), AccountSharedData::default()); 3];
1917
1918        // Simulate a trace capacity of 5
1919        let mut transaction_context = TransactionContext::new(
1920            transaction_accounts.clone(),
1921            Rent::default(),
1922            6,
1923            MAX_INSTRUCTION_TRACE_LENGTH,
1924            MAX_INSTRUCTION_TRACE_LENGTH,
1925        );
1926
1927        // Configure top-level instructions
1928        for idx_to_configure in 0..MAX_INSTRUCTION_TRACE_LENGTH {
1929            transaction_context
1930                .configure_instruction_at_index(
1931                    idx_to_configure,
1932                    0,
1933                    vec![InstructionAccount::new(1, false, false)],
1934                    vec![0; 3],
1935                    Vec::new().into(),
1936                    None,
1937                )
1938                .unwrap();
1939        }
1940
1941        // Execute first top level instruction
1942        transaction_context.push(fail_early).unwrap();
1943        // It invokes a program
1944        transaction_context
1945            .configure_next_cpi_for_tests(
1946                0,
1947                vec![InstructionAccount::new(2, false, false)],
1948                Vec::new(),
1949            )
1950            .unwrap();
1951
1952        let result = transaction_context.push(fail_early);
1953        if fail_early {
1954            assert_eq!(
1955                result,
1956                Err(InstructionError::MaxInstructionTraceLengthExceeded)
1957            );
1958        } else {
1959            assert!(result.is_ok());
1960        }
1961    }
1962}
1963
1964/// Tests for account growth through the access violation handler.
1965///
1966/// The handler is driven as during program execution, through sbpf's
1967/// `map_with_access_violation_handler`, which calls the handler on a copy of the region, retries
1968/// the access once, and installs the copy in the mapping if the retry succeeds.
1969///
1970/// After every access, the account's region in the mapping is expected to cover exactly the
1971/// account's current data (same length and, with direct mapping, the same host buffer).
1972#[cfg(all(test, not(target_arch = "sbf"), not(target_arch = "bpf")))]
1973#[expect(clippy::arithmetic_side_effects, clippy::indexing_slicing)]
1974mod access_violation_handler_tests {
1975    use {
1976        super::*,
1977        crate::MAX_ACCOUNT_DATA_GROWTH_PER_INSTRUCTION,
1978        solana_sbpf::{
1979            ebpf::MM_INPUT_START,
1980            memory_region::MemoryMapping,
1981            program::SBPFVersion,
1982            vm::{Config, ContextObject},
1983        },
1984        std::ptr::NonNull,
1985        test_case::test_case,
1986    };
1987
1988    /// Address space reserved past an account's data for it to grow into (ABI V1).
1989    const REALLOC_PADDING: usize = MAX_ACCOUNT_DATA_GROWTH_PER_INSTRUCTION;
1990    const MAX_LEN: usize = MAX_ACCOUNT_DATA_LEN as usize;
1991    const VADDR: u64 = MM_INPUT_START;
1992
1993    struct MockVm {
1994        mapping: Option<MemoryMapping>,
1995    }
1996
1997    impl ContextObject for MockVm {
1998        fn consume(&mut self, _amount: u64) {}
1999        fn get_remaining(&self) -> u64 {
2000            u64::MAX
2001        }
2002        fn active_mapping_ptr(&mut self) -> NonNull<MemoryMapping> {
2003            NonNull::from(self.mapping.as_mut().unwrap())
2004        }
2005    }
2006
2007    struct Setup {
2008        transaction_context: TransactionContext<'static>,
2009        vm: MockVm,
2010        direct_mapping: bool,
2011        /// Keeps the account's buffer shared, if requested.
2012        _other_owner: Option<AccountSharedData>,
2013        /// Backing memory of the serialized region (without direct mapping) and of the next region.
2014        _serialized: Vec<u8>,
2015        _next: Box<[u8; 16]>,
2016    }
2017
2018    #[derive(Debug, PartialEq, Eq)]
2019    struct State {
2020        data_ptr: *const u8,
2021        data_len: usize,
2022        is_shared: bool,
2023        resize_delta: i64,
2024    }
2025
2026    impl Setup {
2027        /// One writable account of `len` bytes, mapped at `VADDR` with a reserved window of
2028        /// `len + REALLOC_PADDING`, followed by the next region.
2029        fn new(len: usize, shared: bool, direct_mapping: bool, resize_delta: i64) -> Self {
2030            let account =
2031                AccountSharedData::new_with_data(1, vec![0xAB_u8; len], &Pubkey::new_unique());
2032            let other_owner = shared.then(|| account.clone());
2033            let transaction_context = TransactionContext::new(
2034                vec![(Pubkey::new_unique(), account)],
2035                Rent::default(),
2036                1,
2037                1,
2038                1,
2039            );
2040            let accounts = transaction_context.accounts();
2041            accounts
2042                .update_accounts_resize_delta(0, resize_delta as usize)
2043                .unwrap();
2044
2045            let mut serialized = Vec::new();
2046            let mut region = if direct_mapping {
2047                // As `create_memory_region_of_account` in program-runtime.
2048                let account = accounts.try_borrow(0).unwrap();
2049                if shared {
2050                    MemoryRegion::new(&raw const account.data()[..], VADDR)
2051                } else {
2052                    let data = account.data();
2053                    MemoryRegion::new(
2054                        std::ptr::slice_from_raw_parts_mut(data.as_ptr() as *mut u8, data.len()),
2055                        VADDR,
2056                    )
2057                }
2058            } else {
2059                // Serialized copy with the padding the handler may grow into.
2060                serialized = vec![0xAB_u8; len + REALLOC_PADDING];
2061                MemoryRegion::new(&raw mut serialized[..len], VADDR)
2062            };
2063            region.access_violation_handler_payload = Some(0);
2064            let mut next = Box::new([0_u8; 16]);
2065            let next_region =
2066                MemoryRegion::new(&raw mut next[..], VADDR + (len + REALLOC_PADDING) as u64);
2067
2068            let config = Config {
2069                aligned_memory_mapping: false,
2070                ..Config::default()
2071            };
2072            let handler = transaction_context.access_violation_handler(true, direct_mapping);
2073            let mapping = unsafe {
2074                MemoryMapping::new_with_access_violation_handler(
2075                    vec![MemoryRegion::new_empty(0), region, next_region],
2076                    &config,
2077                    SBPFVersion::V3,
2078                    handler,
2079                )
2080                .unwrap()
2081            };
2082            Self {
2083                transaction_context,
2084                vm: MockVm {
2085                    mapping: Some(mapping),
2086                },
2087                direct_mapping,
2088                _other_owner: other_owner,
2089                _serialized: serialized,
2090                _next: next,
2091            }
2092        }
2093
2094        /// A store of `len` bytes at offset `offset` of the account, as done by a program.
2095        fn store(&mut self, offset: usize, len: u64) -> bool {
2096            let memory_mapping = unsafe { self.vm.active_mapping_ptr().as_mut() };
2097            let result: Result<_, _> = memory_mapping
2098                .map_with_access_violation_handler(AccessType::Store, VADDR + offset as u64, len)
2099                .into();
2100            self.assert_region_matches_account();
2101            result.is_ok()
2102        }
2103
2104        fn state(&self) -> State {
2105            let accounts = self.transaction_context.accounts();
2106            let account = accounts.try_borrow_mut(0).unwrap();
2107            State {
2108                data_ptr: account.data().as_ptr(),
2109                data_len: account.data().len(),
2110                is_shared: account.is_shared(),
2111                resize_delta: accounts.resize_delta(),
2112            }
2113        }
2114
2115        fn assert_region_matches_account(&self) {
2116            let (_, region) = self
2117                .vm
2118                .mapping
2119                .as_ref()
2120                .unwrap()
2121                .find_region(VADDR)
2122                .unwrap();
2123            let accounts = self.transaction_context.accounts();
2124            let account = accounts.try_borrow(0).unwrap();
2125            assert_eq!(
2126                region.len(),
2127                account.data().len(),
2128                "region length differs from the account's data length",
2129            );
2130            if self.direct_mapping {
2131                assert_eq!(
2132                    region.host_buffer().ptr() as *const u8,
2133                    account.data().as_ptr(),
2134                    "region does not map the account's data buffer",
2135                );
2136            }
2137        }
2138
2139        fn into_touched(self) -> bool {
2140            drop(self.vm); // Drops the handler, which holds a reference to the accounts.
2141            ExecutionRecord::from(self.transaction_context).touched_flags[0]
2142        }
2143    }
2144
2145    /// How the account is mapped into the VM.
2146    #[derive(Clone, Copy, Debug)]
2147    enum Mapping {
2148        /// Direct mapping of the account's own (unique) buffer, writable.
2149        Direct,
2150        /// Direct mapping of a buffer shared with another owner (copy-on-write), read-only.
2151        DirectShared,
2152        /// No direct mapping: a serialized copy with padding to grow into.
2153        Serialized,
2154    }
2155
2156    impl Setup {
2157        fn with(len: usize, mapping: Mapping, resize_delta: i64) -> Self {
2158            match mapping {
2159                Mapping::Direct => Self::new(len, false, true, resize_delta),
2160                Mapping::DirectShared => Self::new(len, true, true, resize_delta),
2161                Mapping::Serialized => Self::new(len, false, false, resize_delta),
2162            }
2163        }
2164    }
2165
2166    /// Growth beyond the limits: the store is inside the reserved window but does not fit within
2167    /// `MAX_ACCOUNT_DATA_LEN` or the remaining growth budget of the transaction. The store fails,
2168    /// and the account, the budget and the touched flag are left as they were.
2169    #[test_case(MAX_LEN - 2, 0, MAX_LEN + 1, Mapping::Direct ; "max account len, direct")]
2170    #[test_case(MAX_LEN - 2, 0, MAX_LEN + 1, Mapping::DirectShared ; "max account len, direct shared")]
2171    #[test_case(MAX_LEN - 2, 0, MAX_LEN + 1, Mapping::Serialized ; "max account len, serialized")]
2172    #[test_case(0x100, MAX_ACCOUNT_DATA_GROWTH_PER_TRANSACTION - 0x10, 0x110, Mapping::Direct ; "budget partially left, direct")]
2173    #[test_case(0x100, MAX_ACCOUNT_DATA_GROWTH_PER_TRANSACTION - 0x10, 0x110, Mapping::DirectShared ; "budget partially left, direct shared")]
2174    #[test_case(0x100, MAX_ACCOUNT_DATA_GROWTH_PER_TRANSACTION - 0x10, 0x110, Mapping::Serialized ; "budget partially left, serialized")]
2175    #[test_case(0x100, MAX_ACCOUNT_DATA_GROWTH_PER_TRANSACTION, 0x100, Mapping::Direct ; "budget exhausted, direct")]
2176    #[test_case(0x100, MAX_ACCOUNT_DATA_GROWTH_PER_TRANSACTION, 0x100, Mapping::DirectShared ; "budget exhausted, direct shared")]
2177    #[test_case(0x100, MAX_ACCOUNT_DATA_GROWTH_PER_TRANSACTION, 0x100, Mapping::Serialized ; "budget exhausted, serialized")]
2178    fn test_growth_beyond_limits(len: usize, resize_delta: i64, offset: usize, mapping: Mapping) {
2179        assert!(offset < len + REALLOC_PADDING); // Inside the reserved window.
2180        let mut setup = Setup::with(len, mapping, resize_delta);
2181        let before = setup.state();
2182        assert!(!setup.store(offset, 1), "store at {offset:#x} must fail");
2183        assert_eq!(setup.state(), before, "account or budget changed");
2184        assert!(!setup.into_touched(), "account touched");
2185    }
2186
2187    /// Growth beyond the limits, for an account that a previous store has un-shared.
2188    #[test]
2189    fn test_growth_beyond_limits_after_unshare() {
2190        let mut setup = Setup::with(MAX_LEN - 2, Mapping::DirectShared, 0);
2191        assert!(setup.store(0, 1));
2192        let before = setup.state();
2193        assert!(!before.is_shared);
2194        assert!(!setup.store(MAX_LEN + 1, 1));
2195        assert_eq!(setup.state(), before);
2196    }
2197
2198    /// Growth within the limits: the account grows to the largest length the limits allow, the
2199    /// budget is charged, the account is touched, and the region in the mapping covers the grown
2200    /// data.
2201    #[test_case(0x100, 0, 0x100, 0x100 + REALLOC_PADDING, Mapping::Direct ; "to the window, direct")]
2202    #[test_case(0x100, 0, 0x100, 0x100 + REALLOC_PADDING, Mapping::DirectShared ; "to the window, direct shared")]
2203    #[test_case(0x100, 0, 0x100, 0x100 + REALLOC_PADDING, Mapping::Serialized ; "to the window, serialized")]
2204    #[test_case(0x100, MAX_ACCOUNT_DATA_GROWTH_PER_TRANSACTION - 0x10, 0x10F, 0x110, Mapping::Direct ; "to the budget, direct")]
2205    #[test_case(0x100, MAX_ACCOUNT_DATA_GROWTH_PER_TRANSACTION - 0x10, 0x10F, 0x110, Mapping::DirectShared ; "to the budget, direct shared")]
2206    #[test_case(0x100, MAX_ACCOUNT_DATA_GROWTH_PER_TRANSACTION - 0x10, 0x10F, 0x110, Mapping::Serialized ; "to the budget, serialized")]
2207    #[test_case(MAX_LEN - 2, 0, MAX_LEN - 1, MAX_LEN, Mapping::Direct ; "to max account len, direct")]
2208    #[test_case(MAX_LEN - 2, 0, MAX_LEN - 1, MAX_LEN, Mapping::DirectShared ; "to max account len, direct shared")]
2209    #[test_case(MAX_LEN - 2, 0, MAX_LEN - 1, MAX_LEN, Mapping::Serialized ; "to max account len, serialized")]
2210    fn test_growth_within_limits(
2211        len: usize,
2212        resize_delta: i64,
2213        offset: usize,
2214        grown_len: usize,
2215        mapping: Mapping,
2216    ) {
2217        let mut setup = Setup::with(len, mapping, resize_delta);
2218        assert!(setup.store(offset, 1), "store at {offset:#x} must succeed");
2219        let after = setup.state();
2220        assert_eq!(after.data_len, grown_len);
2221        assert_eq!(after.resize_delta, resize_delta + (grown_len - len) as i64);
2222        assert!(!after.is_shared);
2223        assert!(setup.into_touched());
2224    }
2225
2226    /// A store inside the current length of a shared account un-shares it and is served.
2227    #[test]
2228    fn test_store_to_shared_account_unshares() {
2229        let mut setup = Setup::with(0x100, Mapping::DirectShared, 0);
2230        assert!(setup.store(0x10, 8));
2231        let after = setup.state();
2232        assert_eq!(after.data_len, 0x100);
2233        assert_eq!(after.resize_delta, 0);
2234        assert!(!after.is_shared);
2235        assert!(setup.into_touched());
2236    }
2237}