solana-transaction-context 4.0.0

Solana data shared between program runtime and built-in programs as well as SBF programs.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
use {
    crate::{
        IndexOfAccount, MAX_ACCOUNT_DATA_GROWTH_PER_TRANSACTION, MAX_ACCOUNT_DATA_LEN,
        MAX_ACCOUNTS_PER_TRANSACTION,
        instruction::{InstructionContext, InstructionFrame},
        instruction_accounts::InstructionAccount,
        transaction_accounts::{KeyedAccountSharedData, TransactionAccounts},
        vm_addresses::{
            GUEST_INSTRUCTION_DATA_BASE_ADDRESS, GUEST_REGION_SIZE, RETURN_DATA_SCRATCHPAD,
        },
        vm_slice::VmSlice,
    },
    solana_account::{AccountSharedData, ReadableAccount, WritableAccount},
    solana_instruction::error::InstructionError,
    solana_instructions_sysvar as instructions,
    solana_pubkey::Pubkey,
    solana_rent::Rent,
    solana_sbpf::memory_region::{AccessType, AccessViolationHandler, MemoryRegion},
    std::{borrow::Cow, cell::Cell, rc::Rc},
};

/// Used only in fn `take_instruction_trace` for deconstructing TransactionContext
pub type InstructionTrace<'ix_data> = (
    Vec<InstructionFrame>,
    Vec<Box<[InstructionAccount]>>,
    Vec<Cow<'ix_data, [u8]>>,
);

/// This data structure is shared with programs in ABIv2, providing information about the
/// transaction metadata.
///
/// Modifications without a feature gate and proper versioning might break programs.
#[repr(C)]
#[derive(Debug)]
struct TransactionFrame {
    /// Pubkey of the last program to write to the return data scratchpad
    return_data_pubkey: Pubkey,
    return_data_scratchpad: VmSlice<u8>,
    /// Scratchpad for programs to write CPI instruction data
    cpi_scratchpad: VmSlice<u8>,
    /// Index of current executing instruction
    current_executing_instruction: u16,
    /// Number of instructions in the instruction trace (including top level and CPIs)
    total_number_of_instructions_in_trace: u16,
    /// Number of CPIs in the instruction trace
    number_of_cpis_in_trace: u16,
    /// Number of transaction accounts
    number_of_transaction_accounts: u16,
}

/// Loaded transaction shared between runtime and programs.
///
/// This context is valid for the entire duration of a transaction being processed.
#[derive(Debug)]
#[cfg(not(any(target_arch = "bpf", target_arch = "sbf")))]
pub struct TransactionContext<'ix_data> {
    pub(crate) accounts: Rc<TransactionAccounts>,
    instruction_stack_capacity: usize,
    instruction_trace_capacity: usize,
    instruction_stack: Vec<usize>,
    instruction_trace: Vec<InstructionFrame>,
    transaction_frame: TransactionFrame,
    return_data_bytes: Vec<u8>,
    next_top_level_instruction_index: usize,
    #[cfg(not(target_os = "solana"))]
    pub(crate) rent: Rent,
    /// This is an account deduplication map that maps index_in_transaction to index_in_instruction
    /// Usage: dedup_map[index_in_transaction] = index_in_instruction
    /// Each entry in `deduplication_maps` represents the deduplication map for each instruction.
    deduplication_maps: Vec<Box<[u16]>>,
    /// Each entry in `instruction_accounts` represents the array of accounts for each instruction.
    instruction_accounts: Vec<Box<[InstructionAccount]>>,
    /// Each entry in `instruction_data` represents the data for instruction at the corresponding
    /// index.
    instruction_data: Vec<Cow<'ix_data, [u8]>>,
}

#[cfg(not(any(target_arch = "bpf", target_arch = "sbf")))]
impl<'ix_data> TransactionContext<'ix_data> {
    /// Constructs a new TransactionContext
    pub fn new(
        transaction_accounts: Vec<KeyedAccountSharedData>,
        rent: Rent,
        instruction_stack_capacity: usize,
        instruction_trace_capacity: usize,
        number_of_top_level_instructions: usize,
    ) -> Self {
        let transaction_frame = TransactionFrame {
            return_data_pubkey: Pubkey::default(),
            return_data_scratchpad: VmSlice::new(RETURN_DATA_SCRATCHPAD, 0),
            cpi_scratchpad: VmSlice::new(0, 0),
            current_executing_instruction: 0,
            total_number_of_instructions_in_trace: number_of_top_level_instructions as u16,
            number_of_cpis_in_trace: 0,
            number_of_transaction_accounts: transaction_accounts.len() as u16,
        };

        Self {
            accounts: Rc::new(TransactionAccounts::new(transaction_accounts)),
            instruction_stack_capacity,
            instruction_trace_capacity,
            instruction_stack: Vec::with_capacity(instruction_stack_capacity),
            instruction_trace: vec![InstructionFrame::default()],
            return_data_bytes: Vec::new(),
            transaction_frame,
            next_top_level_instruction_index: 0,
            rent,
            instruction_accounts: Vec::with_capacity(instruction_trace_capacity),
            deduplication_maps: Vec::with_capacity(instruction_trace_capacity),
            instruction_data: Vec::with_capacity(instruction_trace_capacity),
        }
    }

    /// Used in mock_process_instruction
    pub fn deconstruct_without_keys(self) -> Result<Vec<AccountSharedData>, InstructionError> {
        if !self.instruction_stack.is_empty() {
            return Err(InstructionError::CallDepth);
        }

        let accounts = Rc::try_unwrap(self.accounts)
            .expect("transaction_context.accounts has unexpected outstanding refs")
            .deconstruct_into_account_shared_data();

        Ok(accounts)
    }

    pub fn accounts(&self) -> &Rc<TransactionAccounts> {
        &self.accounts
    }

    /// Returns the total number of accounts loaded in this Transaction
    pub fn get_number_of_accounts(&self) -> IndexOfAccount {
        self.accounts.len() as IndexOfAccount
    }

    /// Searches for an account by its key
    pub fn get_key_of_account_at_index(
        &self,
        index_in_transaction: IndexOfAccount,
    ) -> Result<&Pubkey, InstructionError> {
        self.accounts
            .account_key(index_in_transaction)
            .ok_or(InstructionError::MissingAccount)
    }

    /// Searches for an account by its key
    pub fn find_index_of_account(&self, pubkey: &Pubkey) -> Option<IndexOfAccount> {
        self.accounts
            .account_keys_iter()
            .position(|key| key == pubkey)
            .map(|index| index as IndexOfAccount)
    }

    /// Gets the max length of the instruction trace
    pub fn get_instruction_trace_capacity(&self) -> usize {
        self.instruction_trace_capacity
    }

    /// Returns the instruction trace length.
    ///
    /// Not counting the last empty instruction which is always pre-reserved for the next instruction.
    pub fn get_instruction_trace_length(&self) -> usize {
        self.instruction_trace.len().saturating_sub(1)
    }

    /// Gets a view on an instruction by its index in the trace
    pub fn get_instruction_context_at_index_in_trace(
        &self,
        index_in_trace: usize,
    ) -> Result<InstructionContext<'_, '_>, InstructionError> {
        let instruction = self
            .instruction_trace
            .get(index_in_trace)
            .ok_or(InstructionError::CallDepth)?;

        // These commands will return a default empty slice if we are retrieving an instruction
        // that hasn't been configured yet.
        let instruction_accounts = self
            .instruction_accounts
            .get(index_in_trace)
            .map(|item| item.as_ref())
            .unwrap_or_default();
        let dedup_map = self
            .deduplication_maps
            .get(index_in_trace)
            .map(|item| item.as_ref())
            .unwrap_or_default();
        let instruction_data = self
            .instruction_data
            .get(index_in_trace)
            .map(|item| item.as_ref())
            .unwrap_or_default();
        Ok(InstructionContext {
            transaction_context: self,
            index_in_trace,
            nesting_level: instruction.nesting_level as usize,
            program_account_index_in_tx: instruction.program_account_index_in_tx as IndexOfAccount,
            instruction_accounts,
            dedup_map,
            instruction_data,
            index_of_caller_instruction: instruction.index_of_caller_instruction as usize,
        })
    }

    /// Gets a view on the instruction by its nesting level in the stack
    pub fn get_instruction_context_at_nesting_level(
        &self,
        nesting_level: usize,
    ) -> Result<InstructionContext<'_, '_>, InstructionError> {
        let index_in_trace = *self
            .instruction_stack
            .get(nesting_level)
            .ok_or(InstructionError::CallDepth)?;
        let instruction_context = self.get_instruction_context_at_index_in_trace(index_in_trace)?;
        debug_assert_eq!(instruction_context.nesting_level, nesting_level);
        Ok(instruction_context)
    }

    /// Gets the max height of the instruction stack
    pub fn get_instruction_stack_capacity(&self) -> usize {
        self.instruction_stack_capacity
    }

    /// Gets instruction stack height, top-level instructions are height
    /// `solana_instruction::TRANSACTION_LEVEL_STACK_HEIGHT`
    pub fn get_instruction_stack_height(&self) -> usize {
        self.instruction_stack.len()
    }

    /// Returns the index in the instruction trace of the current executing instruction
    pub fn get_current_instruction_index(&self) -> Result<usize, InstructionError> {
        self.instruction_stack
            .last()
            .copied()
            .ok_or(InstructionError::CallDepth)
    }

    /// Returns a view on the current instruction
    pub fn get_current_instruction_context(
        &self,
    ) -> Result<InstructionContext<'_, '_>, InstructionError> {
        let index_in_trace = self.get_current_instruction_index()?;
        self.get_instruction_context_at_index_in_trace(index_in_trace)
    }

    /// Returns a view on the next instruction. This function assumes it has already been
    /// configured with the correct values in `prepare_next_instruction` or
    /// `prepare_next_top_level_instruction`
    pub fn get_next_instruction_context(
        &self,
    ) -> Result<InstructionContext<'_, '_>, InstructionError> {
        let index_in_trace = self
            .instruction_trace
            .len()
            .checked_sub(1)
            .ok_or(InstructionError::CallDepth)?;
        self.get_instruction_context_at_index_in_trace(index_in_trace)
    }

    /// Configures an instruction at a specific index in trace.
    pub fn configure_instruction_at_index(
        &mut self,
        instruction_index: usize,
        program_index: IndexOfAccount,
        instruction_accounts: Vec<InstructionAccount>,
        deduplication_map: Vec<u16>,
        instruction_data: Cow<'ix_data, [u8]>,
        caller_index: Option<u16>,
    ) -> Result<(), InstructionError> {
        debug_assert_eq!(deduplication_map.len(), MAX_ACCOUNTS_PER_TRANSACTION);

        let instruction = self
            .instruction_trace
            .get_mut(instruction_index)
            .ok_or(InstructionError::MaxInstructionTraceLengthExceeded)?;

        // If we have a parent index, then we are dealing with a CPI.
        if let Some(caller_index) = caller_index {
            self.transaction_frame.total_number_of_instructions_in_trace = self
                .transaction_frame
                .total_number_of_instructions_in_trace
                .saturating_add(1);
            instruction.index_of_caller_instruction = caller_index;
        }

        self.transaction_frame.cpi_scratchpad = VmSlice::new(
            GUEST_INSTRUCTION_DATA_BASE_ADDRESS.saturating_add(GUEST_REGION_SIZE.saturating_mul(
                self.transaction_frame.total_number_of_instructions_in_trace as u64,
            )),
            0,
        );

        instruction.program_account_index_in_tx = program_index;
        instruction.configure_vm_slices(
            instruction_index as u64,
            instruction_accounts.len(),
            instruction_data.len() as u64,
        );
        self.deduplication_maps
            .push(deduplication_map.into_boxed_slice());
        self.instruction_accounts
            .push(instruction_accounts.into_boxed_slice());
        self.instruction_data.push(instruction_data);
        Ok(())
    }

    /// For tests only
    fn deduplicate_accounts_for_tests(instruction_accounts: &[InstructionAccount]) -> Vec<u16> {
        let mut dedup_map = vec![u16::MAX; MAX_ACCOUNTS_PER_TRANSACTION];
        for (idx, account) in instruction_accounts.iter().enumerate() {
            let index_in_instruction = dedup_map
                .get_mut(account.index_in_transaction as usize)
                .unwrap();
            if *index_in_instruction == u16::MAX {
                *index_in_instruction = idx as u16;
            }
        }
        dedup_map
    }

    /// A version of `configure_top_level_instruction` to help creating the deduplication map in tests
    pub fn configure_top_level_instruction_for_tests(
        &mut self,
        program_index: IndexOfAccount,
        instruction_accounts: Vec<InstructionAccount>,
        instruction_data: Vec<u8>,
    ) -> Result<(), InstructionError> {
        debug_assert!(instruction_accounts.len() <= u16::MAX as usize);
        let dedup_map = Self::deduplicate_accounts_for_tests(&instruction_accounts);

        self.configure_instruction_at_index(
            self.get_instruction_trace_length(),
            program_index,
            instruction_accounts,
            dedup_map,
            Cow::Owned(instruction_data),
            None,
        )?;
        Ok(())
    }

    /// A helper function to facilitate creating a CPI in tests
    pub fn configure_next_cpi_for_tests(
        &mut self,
        program_index: IndexOfAccount,
        instruction_accounts: Vec<InstructionAccount>,
        instruction_data: Vec<u8>,
    ) -> Result<(), InstructionError> {
        debug_assert!(instruction_accounts.len() <= u16::MAX as usize);
        let dedup_map = Self::deduplicate_accounts_for_tests(&instruction_accounts);
        let caller_index = self.get_current_instruction_index()?;
        let cpi_index = self.get_instruction_trace_length();
        self.configure_instruction_at_index(
            cpi_index,
            program_index,
            instruction_accounts,
            dedup_map,
            Cow::Owned(instruction_data),
            Some(caller_index as u16),
        )?;
        Ok(())
    }

    /// Pushes the next instruction
    pub fn push(&mut self) -> Result<(), InstructionError> {
        let nesting_level = self.get_instruction_stack_height();
        if !self.instruction_stack.is_empty() && self.accounts.get_lamports_delta() != 0 {
            return Err(InstructionError::UnbalancedInstruction);
        }
        {
            let instruction = self
                .instruction_trace
                .last_mut()
                .ok_or(InstructionError::CallDepth)?;
            instruction.nesting_level = nesting_level as u16;
        }
        let index_in_trace = self.get_instruction_trace_length();
        if index_in_trace >= self.instruction_trace_capacity {
            return Err(InstructionError::MaxInstructionTraceLengthExceeded);
        }

        let current_top_level_instruction = if self.instruction_stack.is_empty() {
            let index = self.next_top_level_instruction_index;
            self.next_top_level_instruction_index =
                self.next_top_level_instruction_index.saturating_add(1);
            index
        } else {
            self.transaction_frame.number_of_cpis_in_trace = self
                .transaction_frame
                .number_of_cpis_in_trace
                .saturating_add(1);
            self.next_top_level_instruction_index.saturating_sub(1)
        };

        self.instruction_trace.push(InstructionFrame::default());
        if nesting_level >= self.instruction_stack_capacity {
            return Err(InstructionError::CallDepth);
        }
        self.transaction_frame.current_executing_instruction = index_in_trace as u16;
        self.instruction_stack.push(index_in_trace);
        if let Some(index_in_transaction) = self.find_index_of_account(&instructions::id()) {
            let mut mut_account_ref = self.accounts.try_borrow_mut(index_in_transaction)?;
            if mut_account_ref.owner() != &solana_sdk_ids::sysvar::id() {
                return Err(InstructionError::InvalidAccountOwner);
            }
            instructions::store_current_index_checked(
                mut_account_ref.data_as_mut_slice(),
                current_top_level_instruction as u16,
            )?;
        }
        Ok(())
    }

    /// Pops the current instruction
    pub fn pop(&mut self) -> Result<(), InstructionError> {
        if self.instruction_stack.is_empty() {
            return Err(InstructionError::CallDepth);
        }
        // Verify (before we pop) that the total sum of all lamports in this instruction did not change
        let detected_an_unbalanced_instruction =
            self.get_current_instruction_context()
                .and_then(|instruction_context| {
                    // Verify all executable accounts have no outstanding refs
                    self.accounts
                        .try_borrow_mut(
                            instruction_context.get_index_of_program_account_in_transaction()?,
                        )
                        .map_err(|err| {
                            if err == InstructionError::AccountBorrowFailed {
                                InstructionError::AccountBorrowOutstanding
                            } else {
                                err
                            }
                        })?;
                    Ok(self.accounts.get_lamports_delta() != 0)
                });
        // Always pop, even if we `detected_an_unbalanced_instruction`
        self.instruction_stack.pop();
        if let Some(instr_idx) = self.instruction_stack.last() {
            self.transaction_frame.current_executing_instruction = *instr_idx as u16;
        }
        if detected_an_unbalanced_instruction? {
            Err(InstructionError::UnbalancedInstruction)
        } else {
            Ok(())
        }
    }

    /// Gets the return data of the current instruction or any above
    pub fn get_return_data(&self) -> (&Pubkey, &[u8]) {
        (
            &self.transaction_frame.return_data_pubkey,
            &self.return_data_bytes,
        )
    }

    /// Set the return data of the current instruction
    pub fn set_return_data(
        &mut self,
        program_id: Pubkey,
        data: Vec<u8>,
    ) -> Result<(), InstructionError> {
        self.transaction_frame.return_data_pubkey = program_id;
        // SAFETY: `return_data_scratchpad` is backed by `self.return_data_bytes`
        // and `return_data_bytes` is being reset to `data`
        // in the next statement.
        unsafe {
            self.transaction_frame
                .return_data_scratchpad
                .set_len(data.len() as u64);
        }
        self.return_data_bytes = data;
        Ok(())
    }

    /// Returns a new account data write access handler
    pub fn access_violation_handler(
        &self,
        virtual_address_space_adjustments: bool,
        account_data_direct_mapping: bool,
    ) -> AccessViolationHandler {
        let accounts = Rc::clone(&self.accounts);
        Box::new(
            move |region: &mut MemoryRegion,
                  address_space_reserved_for_account: u64,
                  access_type: AccessType,
                  vm_addr: u64,
                  len: u64| {
                if access_type == AccessType::Load {
                    return;
                }
                let Some(index_in_transaction) = region.access_violation_handler_payload else {
                    // This region is not a writable account.
                    return;
                };
                let requested_length =
                    vm_addr.saturating_add(len).saturating_sub(region.vm_addr) as usize;
                if requested_length > address_space_reserved_for_account as usize {
                    // Requested access goes further than the account region.
                    return;
                }

                // The four calls below can't really fail. If they fail because of a bug,
                // whatever is writing will trigger an EbpfError::AccessViolation like
                // if the region was readonly, and the transaction will fail gracefully.
                let Ok(mut account) = accounts.try_borrow_mut(index_in_transaction) else {
                    debug_assert!(false);
                    return;
                };
                if accounts.touch(index_in_transaction).is_err() {
                    debug_assert!(false);
                    return;
                }

                let remaining_allowed_growth = MAX_ACCOUNT_DATA_GROWTH_PER_TRANSACTION
                    .saturating_sub(accounts.resize_delta())
                    .max(0) as usize;

                if requested_length > region.len as usize {
                    // Realloc immediately here to fit the requested access,
                    // then later in CPI or deserialization realloc again to the
                    // account length the program stored in AccountInfo.
                    let old_len = account.data().len();
                    let new_len = (address_space_reserved_for_account as usize)
                        .min(MAX_ACCOUNT_DATA_LEN as usize)
                        .min(old_len.saturating_add(remaining_allowed_growth));
                    // The last two min operations ensure the following:
                    debug_assert!(accounts.can_data_be_resized(old_len, new_len).is_ok());
                    if accounts
                        .update_accounts_resize_delta(old_len, new_len)
                        .is_err()
                    {
                        return;
                    }
                    account.resize(new_len, 0);
                    region.len = new_len as u64;
                }

                // Potentially unshare / make the account shared data unique (CoW logic).
                if virtual_address_space_adjustments && account_data_direct_mapping {
                    region.host_addr = account.data_as_mut_slice().as_mut_ptr() as u64;
                    region.writable = true;
                }
            },
        )
    }

    /// Take ownership of the instruction trace
    pub fn take_instruction_trace(&mut self) -> InstructionTrace<'_> {
        // The last frame is a placeholder for the next instruction to be executed, so it
        // is empty.
        self.instruction_trace.pop();
        (
            std::mem::take(&mut self.instruction_trace),
            std::mem::take(&mut self.instruction_accounts),
            std::mem::take(&mut self.instruction_data),
        )
    }

    /// An active instruction is either one that has already finished execution or that is
    /// under execution (e.g. all nested CPIs are active).
    /// For ABIv2 only.
    pub fn number_of_active_instructions_in_trace(&self) -> usize {
        self.next_top_level_instruction_index
            .saturating_add(self.transaction_frame.number_of_cpis_in_trace as usize)
    }

    /// Return next top level instruction to execute
    pub fn next_top_level_instruction_index(&self) -> usize {
        self.next_top_level_instruction_index
    }

    /// Return number of CPIs in instruction trace
    pub fn number_of_cpis_in_trace(&self) -> usize {
        self.transaction_frame.number_of_cpis_in_trace as usize
    }
}

/// Return data at the end of a transaction
#[cfg(not(any(target_arch = "bpf", target_arch = "sbf")))]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct TransactionReturnData {
    pub program_id: Pubkey,
    pub data: Vec<u8>,
}

/// Everything that needs to be recorded from a TransactionContext after execution
#[cfg(not(any(target_arch = "bpf", target_arch = "sbf")))]
pub struct ExecutionRecord {
    pub accounts: Vec<KeyedAccountSharedData>,
    pub return_data: TransactionReturnData,
    pub touched_account_count: u64,
    pub accounts_resize_delta: i64,
}

/// Used by the bank in the runtime to write back the processed accounts and recorded instructions
#[cfg(not(any(target_arch = "bpf", target_arch = "sbf")))]
impl From<TransactionContext<'_>> for ExecutionRecord {
    fn from(context: TransactionContext) -> Self {
        let (accounts, touched_flags, resize_delta) = Rc::try_unwrap(context.accounts)
            .expect("transaction_context.accounts has unexpected outstanding refs")
            .take();
        let touched_account_count = touched_flags
            .iter()
            .fold(0usize, |accumulator, was_touched| {
                accumulator.saturating_add(was_touched.get() as usize)
            }) as u64;

        let return_data = TransactionReturnData {
            program_id: context.transaction_frame.return_data_pubkey,
            data: context.return_data_bytes,
        };

        Self {
            accounts,
            return_data,
            touched_account_count,
            accounts_resize_delta: Cell::into_inner(resize_delta),
        }
    }
}

#[cfg(all(test, not(target_arch = "sbf"), not(target_arch = "bpf")))]
mod tests {
    use super::*;

    #[test]
    fn test_instructions_sysvar_store_index_checked() {
        let build_transaction_context = |account: AccountSharedData| {
            TransactionContext::new(
                vec![
                    (Pubkey::new_unique(), AccountSharedData::default()),
                    (instructions::id(), account),
                ],
                Rent::default(),
                /* max_instruction_stack_depth */ 2,
                /* max_instruction_trace_length */ 2,
                /* number_of_top_level_instructions */ 1,
            )
        };

        let correct_space = 2;
        let rent_exempt_lamports = Rent::default().minimum_balance(correct_space);

        // First try it with the wrong owner.
        let account =
            AccountSharedData::new(rent_exempt_lamports, correct_space, &Pubkey::new_unique());
        assert_eq!(
            build_transaction_context(account).push(),
            Err(InstructionError::InvalidAccountOwner),
        );

        // Now with the wrong data length.
        let account =
            AccountSharedData::new(rent_exempt_lamports, 0, &solana_sdk_ids::sysvar::id());
        assert_eq!(
            build_transaction_context(account).push(),
            Err(InstructionError::AccountDataTooSmall),
        );

        // Finally provide the correct account setup.
        let account = AccountSharedData::new(
            rent_exempt_lamports,
            correct_space,
            &solana_sdk_ids::sysvar::id(),
        );
        assert_eq!(build_transaction_context(account).push(), Ok(()),);
    }

    #[test]
    fn test_invalid_native_loader_index() {
        let mut transaction_context = TransactionContext::new(
            vec![(
                Pubkey::new_unique(),
                AccountSharedData::new(1, 1, &Pubkey::new_unique()),
            )],
            Rent::default(),
            20,
            20,
            1,
        );

        transaction_context
            .configure_top_level_instruction_for_tests(
                u16::MAX,
                vec![InstructionAccount::new(0, false, false)],
                vec![],
            )
            .unwrap();
        let instruction_context = transaction_context.get_next_instruction_context().unwrap();

        let result = instruction_context.get_index_of_program_account_in_transaction();
        assert_eq!(result, Err(InstructionError::MissingAccount));

        let result = instruction_context.get_program_key();
        assert_eq!(result, Err(InstructionError::MissingAccount));

        let result = instruction_context.get_program_owner();
        assert_eq!(result.err(), Some(InstructionError::MissingAccount));
    }

    #[test]
    fn test_instruction_shared_items() {
        let transaction_accounts = vec![(Pubkey::new_unique(), AccountSharedData::default()); 10];
        let mut transaction_context =
            TransactionContext::new(transaction_accounts, Rent::default(), 20, 20, 3);

        let instruction_accounts_1 = vec![
            InstructionAccount::new(0, false, true),
            InstructionAccount::new(3, true, false),
        ];
        transaction_context
            .configure_top_level_instruction_for_tests(
                1,
                instruction_accounts_1.clone(),
                vec![1, 2, 3, 4],
            )
            .unwrap();
        transaction_context.push().unwrap();

        let instruction_accounts_2 = vec![
            InstructionAccount::new(0, false, true),
            InstructionAccount::new(3, true, false),
            InstructionAccount::new(5, false, false),
        ];
        transaction_context
            .configure_top_level_instruction_for_tests(
                1,
                instruction_accounts_2.clone(),
                vec![5, 6, 7, 8, 9],
            )
            .unwrap();
        transaction_context.push().unwrap();

        let instruction_accounts_3 = vec![
            InstructionAccount::new(0, false, true),
            InstructionAccount::new(3, true, false),
            InstructionAccount::new(5, false, false),
            InstructionAccount::new(3, false, false),
            InstructionAccount::new(10, false, false),
        ];
        transaction_context
            .configure_top_level_instruction_for_tests(
                1,
                instruction_accounts_3.clone(),
                vec![10, 11],
            )
            .unwrap();
        transaction_context.push().unwrap();

        let first_ix_context = transaction_context
            .get_instruction_context_at_index_in_trace(0)
            .unwrap();
        assert_eq!(
            instruction_accounts_1.as_slice(),
            first_ix_context.instruction_accounts
        );
        assert_eq!(
            *first_ix_context.instruction_data,
            **transaction_context.instruction_data.first().unwrap()
        );
        for (idx_in_ix, acc) in instruction_accounts_1.iter().enumerate() {
            assert_eq!(
                *first_ix_context
                    .dedup_map
                    .get(acc.index_in_transaction as usize)
                    .unwrap(),
                idx_in_ix as u16
            );
        }

        let second_ix_context = transaction_context
            .get_instruction_context_at_index_in_trace(1)
            .unwrap();
        assert_eq!(
            instruction_accounts_2.as_slice(),
            second_ix_context.instruction_accounts
        );
        assert_eq!(
            *second_ix_context.instruction_data,
            **transaction_context.instruction_data.get(1).unwrap()
        );
        for (idx_in_ix, acc) in instruction_accounts_2.iter().enumerate() {
            assert_eq!(
                *second_ix_context
                    .dedup_map
                    .get(acc.index_in_transaction as usize)
                    .unwrap(),
                idx_in_ix as u16
            );
        }

        let third_ix_context = transaction_context
            .get_instruction_context_at_index_in_trace(2)
            .unwrap();
        assert_eq!(
            instruction_accounts_3.as_slice(),
            third_ix_context.instruction_accounts
        );
        assert_eq!(
            *third_ix_context.instruction_data,
            **transaction_context.instruction_data.get(2).unwrap()
        );
        for (idx_in_ix, acc) in instruction_accounts_3.iter().enumerate() {
            if idx_in_ix == 3 {
                assert_eq!(
                    *third_ix_context
                        .dedup_map
                        .get(acc.index_in_transaction as usize)
                        .unwrap(),
                    1
                );
            } else {
                assert_eq!(
                    *third_ix_context
                        .dedup_map
                        .get(acc.index_in_transaction as usize)
                        .unwrap(),
                    idx_in_ix as u16
                );
            }
        }
    }

    #[test]
    fn test_number_of_instructions() {
        let transaction_accounts = vec![(Pubkey::new_unique(), AccountSharedData::default()); 3];
        let mut transaction_context =
            TransactionContext::new(transaction_accounts, Rent::default(), 20, 20, 2);
        assert_eq!(
            transaction_context
                .transaction_frame
                .number_of_cpis_in_trace,
            0
        );

        // Instruction #0
        transaction_context
            .configure_instruction_at_index(
                0,
                0,
                vec![InstructionAccount::new(1, false, false)],
                vec![0; MAX_ACCOUNTS_PER_TRANSACTION],
                Vec::new().into(),
                None,
            )
            .unwrap();

        // Executing instruction #0
        transaction_context.push().unwrap();
        assert_eq!(
            transaction_context
                .transaction_frame
                .current_executing_instruction,
            0
        );

        assert_eq!(
            transaction_context
                .transaction_frame
                .total_number_of_instructions_in_trace,
            2
        );

        assert_eq!(
            transaction_context
                .transaction_frame
                .number_of_cpis_in_trace,
            0
        );

        assert_eq!(
            transaction_context.transaction_frame.cpi_scratchpad.ptr(),
            GUEST_INSTRUCTION_DATA_BASE_ADDRESS.saturating_add(GUEST_REGION_SIZE.saturating_mul(2))
        );
        assert_eq!(
            transaction_context.transaction_frame.cpi_scratchpad.len(),
            0,
        );
        assert_eq!(
            transaction_context.number_of_active_instructions_in_trace(),
            1
        );

        // Instruction #0 does a CPI.
        transaction_context
            .configure_next_cpi_for_tests(
                0,
                vec![InstructionAccount::new(2, false, true)],
                Vec::new(),
            )
            .unwrap();

        transaction_context.push().unwrap();
        assert_eq!(
            transaction_context
                .transaction_frame
                .current_executing_instruction,
            1,
        );

        assert_eq!(
            transaction_context
                .transaction_frame
                .total_number_of_instructions_in_trace,
            3
        );
        assert_eq!(
            transaction_context
                .transaction_frame
                .number_of_cpis_in_trace,
            1
        );
        assert_eq!(
            transaction_context.number_of_active_instructions_in_trace(),
            2
        );

        assert_eq!(
            transaction_context.transaction_frame.cpi_scratchpad.ptr(),
            GUEST_INSTRUCTION_DATA_BASE_ADDRESS.saturating_add(GUEST_REGION_SIZE.saturating_mul(3))
        );

        // A nested CPI
        transaction_context
            .configure_next_cpi_for_tests(
                0,
                vec![InstructionAccount::new(2, false, true)],
                Vec::new(),
            )
            .unwrap();

        transaction_context.push().unwrap();
        assert_eq!(
            transaction_context
                .transaction_frame
                .current_executing_instruction,
            2
        );

        assert_eq!(
            transaction_context
                .transaction_frame
                .total_number_of_instructions_in_trace,
            4
        );

        assert_eq!(
            transaction_context.transaction_frame.cpi_scratchpad.ptr(),
            GUEST_INSTRUCTION_DATA_BASE_ADDRESS.saturating_add(GUEST_REGION_SIZE.saturating_mul(4))
        );

        assert_eq!(
            transaction_context
                .transaction_frame
                .number_of_cpis_in_trace,
            2
        );

        assert_eq!(
            transaction_context.number_of_active_instructions_in_trace(),
            3
        );
        // Return from nested CPI
        transaction_context.pop().unwrap();
        assert_eq!(
            transaction_context.number_of_active_instructions_in_trace(),
            3
        );

        assert_eq!(
            transaction_context
                .transaction_frame
                .total_number_of_instructions_in_trace,
            4
        );
        assert_eq!(
            transaction_context
                .transaction_frame
                .number_of_cpis_in_trace,
            2,
        );
        assert_eq!(
            transaction_context
                .transaction_frame
                .current_executing_instruction,
            1
        );

        // A second nested CPI
        transaction_context
            .configure_next_cpi_for_tests(
                0,
                vec![InstructionAccount::new(2, false, true)],
                Vec::new(),
            )
            .unwrap();

        transaction_context.push().unwrap();
        assert_eq!(
            transaction_context
                .transaction_frame
                .current_executing_instruction,
            3
        );

        assert_eq!(
            transaction_context
                .transaction_frame
                .total_number_of_instructions_in_trace,
            5
        );

        assert_eq!(
            transaction_context.transaction_frame.cpi_scratchpad.ptr(),
            GUEST_INSTRUCTION_DATA_BASE_ADDRESS.saturating_add(GUEST_REGION_SIZE.saturating_mul(5))
        );
        assert_eq!(
            transaction_context
                .transaction_frame
                .number_of_cpis_in_trace,
            3
        );
        assert_eq!(
            transaction_context.number_of_active_instructions_in_trace(),
            4
        );

        // Return from second nested CPI
        transaction_context.pop().unwrap();

        assert_eq!(
            transaction_context
                .transaction_frame
                .current_executing_instruction,
            1
        );

        assert_eq!(
            transaction_context
                .transaction_frame
                .total_number_of_instructions_in_trace,
            5
        );

        assert_eq!(
            transaction_context.transaction_frame.cpi_scratchpad.ptr(),
            GUEST_INSTRUCTION_DATA_BASE_ADDRESS.saturating_add(GUEST_REGION_SIZE.saturating_mul(5))
        );

        assert_eq!(
            transaction_context
                .transaction_frame
                .number_of_cpis_in_trace,
            3
        );

        // Return from first CPI
        transaction_context.pop().unwrap();
        assert_eq!(
            transaction_context.number_of_active_instructions_in_trace(),
            4
        );

        assert_eq!(
            transaction_context
                .transaction_frame
                .current_executing_instruction,
            0
        );

        assert_eq!(
            transaction_context
                .transaction_frame
                .total_number_of_instructions_in_trace,
            5
        );

        assert_eq!(
            transaction_context.transaction_frame.cpi_scratchpad.ptr(),
            GUEST_INSTRUCTION_DATA_BASE_ADDRESS.saturating_add(GUEST_REGION_SIZE.saturating_mul(5))
        );

        assert_eq!(
            transaction_context
                .transaction_frame
                .number_of_cpis_in_trace,
            3,
        );

        // Let's go to Instruction #1 (top level)
        transaction_context.pop().unwrap();

        // Instruction #1
        transaction_context
            .configure_top_level_instruction_for_tests(
                0,
                vec![InstructionAccount::new(1, false, false)],
                Vec::new(),
            )
            .unwrap();
        transaction_context.push().unwrap();
        assert_eq!(
            transaction_context
                .transaction_frame
                .current_executing_instruction,
            4,
        );
        assert_eq!(
            transaction_context
                .transaction_frame
                .number_of_cpis_in_trace,
            3
        );

        // Instruction #1 will do a CPI.
        transaction_context
            .configure_next_cpi_for_tests(
                0,
                vec![InstructionAccount::new(2, false, true)],
                Vec::new(),
            )
            .unwrap();

        transaction_context.push().unwrap();

        assert_eq!(
            transaction_context
                .transaction_frame
                .current_executing_instruction,
            5,
        );

        assert_eq!(
            transaction_context
                .transaction_frame
                .total_number_of_instructions_in_trace,
            6
        );

        assert_eq!(
            transaction_context.transaction_frame.cpi_scratchpad.ptr(),
            GUEST_INSTRUCTION_DATA_BASE_ADDRESS.saturating_add(GUEST_REGION_SIZE.saturating_mul(6))
        );
        assert_eq!(
            transaction_context
                .transaction_frame
                .number_of_cpis_in_trace,
            4
        );
        assert_eq!(
            transaction_context.number_of_active_instructions_in_trace(),
            6
        );

        // Return from CPI
        transaction_context.pop().unwrap();
        assert_eq!(
            transaction_context
                .transaction_frame
                .number_of_cpis_in_trace,
            4
        );
        assert_eq!(
            transaction_context
                .transaction_frame
                .current_executing_instruction,
            4,
        );

        transaction_context.pop().unwrap();
    }

    #[test]
    fn test_get_current_instruction_index() {
        let transaction_accounts = vec![(Pubkey::new_unique(), AccountSharedData::default()); 3];
        let mut transaction_context =
            TransactionContext::new(transaction_accounts, Rent::default(), 20, 20, 2);

        // First top level instruction
        transaction_context
            .configure_instruction_at_index(
                0,
                1,
                vec![
                    InstructionAccount::new(0, false, false),
                    InstructionAccount::new(1, false, false),
                ],
                vec![u16::MAX; 256],
                Cow::Owned(Vec::new()),
                None,
            )
            .unwrap();
        transaction_context.push().unwrap();
        assert_eq!(
            transaction_context.get_current_instruction_index().unwrap(),
            0
        );
        transaction_context.pop().unwrap();

        // Second top-level instruction
        transaction_context
            .configure_instruction_at_index(
                1,
                1,
                vec![
                    InstructionAccount::new(0, false, false),
                    InstructionAccount::new(1, false, true),
                ],
                vec![u16::MAX; 256],
                Cow::Owned(Vec::new()),
                None,
            )
            .unwrap();
        transaction_context.push().unwrap();
        assert_eq!(
            transaction_context.get_current_instruction_index().unwrap(),
            1
        );

        // Simulating a CPI
        transaction_context
            .configure_next_cpi_for_tests(
                1,
                vec![
                    InstructionAccount::new(0, false, true),
                    InstructionAccount::new(1, false, false),
                ],
                Vec::new(),
            )
            .unwrap();
        transaction_context.push().unwrap();
        assert_eq!(
            transaction_context.get_current_instruction_index().unwrap(),
            2
        );

        // Yet another CPI
        transaction_context
            .configure_next_cpi_for_tests(
                1,
                vec![
                    InstructionAccount::new(0, false, true),
                    InstructionAccount::new(1, false, false),
                ],
                Vec::new(),
            )
            .unwrap();
        transaction_context.push().unwrap();
        assert_eq!(
            transaction_context.get_current_instruction_index().unwrap(),
            3
        );

        // CPI return
        transaction_context.pop().unwrap();
        assert_eq!(
            transaction_context.get_current_instruction_index().unwrap(),
            2
        );

        // CPI return 2
        transaction_context.pop().unwrap();
        assert_eq!(
            transaction_context.get_current_instruction_index().unwrap(),
            1
        );
    }
}