-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
Copy pathinvoke_context.rs
1531 lines (1438 loc) · 59.2 KB
/
invoke_context.rs
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
use {
crate::{
accounts_data_meter::AccountsDataMeter,
compute_budget::ComputeBudget,
executor_cache::TransactionExecutorCache,
ic_logger_msg, ic_msg,
log_collector::LogCollector,
pre_account::PreAccount,
stable_log,
sysvar_cache::SysvarCache,
timings::{ExecuteDetailsTimings, ExecuteTimings},
},
solana_measure::measure::Measure,
solana_rbpf::vm::ContextObject,
solana_sdk::{
account::{AccountSharedData, ReadableAccount},
bpf_loader_upgradeable::{self, UpgradeableLoaderState},
feature_set::{enable_early_verification_of_account_modifications, FeatureSet},
hash::Hash,
instruction::{AccountMeta, InstructionError},
native_loader,
pubkey::Pubkey,
rent::Rent,
saturating_add_assign,
stable_layout::stable_instruction::StableInstruction,
transaction_context::{
IndexOfAccount, InstructionAccount, TransactionAccount, TransactionContext,
},
},
std::{
alloc::Layout,
borrow::Cow,
cell::RefCell,
fmt::{self, Debug},
rc::Rc,
sync::Arc,
},
};
pub type ProcessInstructionWithContext = fn(&mut InvokeContext) -> Result<(), InstructionError>;
#[derive(Clone)]
pub struct BuiltinProgram {
pub program_id: Pubkey,
pub process_instruction: ProcessInstructionWithContext,
pub default_compute_unit_cost: u64,
}
impl std::fmt::Debug for BuiltinProgram {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
// These are just type aliases for work around of Debug-ing above pointers
type ErasedProcessInstructionWithContext =
fn(&'static mut InvokeContext<'static>) -> Result<(), InstructionError>;
// rustc doesn't compile due to bug without this work around
// https://github.com/rust-lang/rust/issues/50280
// https://users.rust-lang.org/t/display-function-pointer/17073/2
let erased_instruction: ErasedProcessInstructionWithContext = self.process_instruction;
write!(
f,
"{}: {:p} CUs: {}",
self.program_id, erased_instruction, self.default_compute_unit_cost
)
}
}
impl<'a> ContextObject for InvokeContext<'a> {
fn trace(&mut self, state: [u64; 12]) {
self.trace_log_stack
.last_mut()
.expect("Inconsistent trace log stack")
.trace_log
.push(state);
}
fn consume(&mut self, amount: u64) {
self.log_consumed_bpf_units(amount);
// 1 to 1 instruction to compute unit mapping
// ignore overflow, Ebpf will bail if exceeded
let mut compute_meter = self.compute_meter.borrow_mut();
*compute_meter = compute_meter.saturating_sub(amount);
}
fn get_remaining(&self) -> u64 {
*self.compute_meter.borrow()
}
}
/// Based loosely on the unstable std::alloc::Alloc trait
pub trait Alloc {
fn alloc(&mut self, layout: Layout) -> Result<u64, AllocErr>;
fn dealloc(&mut self, addr: u64, layout: Layout);
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct AllocErr;
impl fmt::Display for AllocErr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("Error: Memory allocation failed")
}
}
struct SyscallContext {
check_aligned: bool,
check_size: bool,
orig_account_lengths: Vec<usize>,
allocator: Rc<RefCell<dyn Alloc>>,
}
#[derive(Default)]
pub struct TraceLogStackFrame {
pub trace_log: Vec<[u64; 12]>,
pub consumed_bpf_units: RefCell<Vec<(usize, u64)>>,
}
pub struct InvokeContext<'a> {
pub transaction_context: &'a mut TransactionContext,
rent: Rent,
pre_accounts: Vec<PreAccount>,
builtin_programs: &'a [BuiltinProgram],
pub sysvar_cache: Cow<'a, SysvarCache>,
pub trace_log_stack: Vec<TraceLogStackFrame>,
log_collector: Option<Rc<RefCell<LogCollector>>>,
compute_budget: ComputeBudget,
current_compute_budget: ComputeBudget,
compute_meter: RefCell<u64>,
accounts_data_meter: AccountsDataMeter,
pub tx_executor_cache: Rc<RefCell<TransactionExecutorCache>>,
pub feature_set: Arc<FeatureSet>,
pub timings: ExecuteDetailsTimings,
pub blockhash: Hash,
pub lamports_per_signature: u64,
syscall_context: Vec<Option<SyscallContext>>,
pub enable_instruction_tracing: bool,
}
impl<'a> InvokeContext<'a> {
#[allow(clippy::too_many_arguments)]
pub fn new(
transaction_context: &'a mut TransactionContext,
rent: Rent,
builtin_programs: &'a [BuiltinProgram],
sysvar_cache: Cow<'a, SysvarCache>,
log_collector: Option<Rc<RefCell<LogCollector>>>,
compute_budget: ComputeBudget,
tx_executor_cache: Rc<RefCell<TransactionExecutorCache>>,
feature_set: Arc<FeatureSet>,
blockhash: Hash,
lamports_per_signature: u64,
prev_accounts_data_len: u64,
) -> Self {
Self {
transaction_context,
rent,
pre_accounts: Vec::new(),
builtin_programs,
sysvar_cache,
trace_log_stack: vec![TraceLogStackFrame::default()],
log_collector,
current_compute_budget: compute_budget,
compute_budget,
compute_meter: RefCell::new(compute_budget.compute_unit_limit),
accounts_data_meter: AccountsDataMeter::new(prev_accounts_data_len),
tx_executor_cache,
feature_set,
timings: ExecuteDetailsTimings::default(),
blockhash,
lamports_per_signature,
syscall_context: Vec::new(),
enable_instruction_tracing: false,
}
}
pub fn new_mock(
transaction_context: &'a mut TransactionContext,
builtin_programs: &'a [BuiltinProgram],
) -> Self {
let mut sysvar_cache = SysvarCache::default();
sysvar_cache.fill_missing_entries(|pubkey, callback| {
for index in 0..transaction_context.get_number_of_accounts() {
if transaction_context
.get_key_of_account_at_index(index)
.unwrap()
== pubkey
{
callback(
transaction_context
.get_account_at_index(index)
.unwrap()
.borrow()
.data(),
);
}
}
});
Self::new(
transaction_context,
Rent::default(),
builtin_programs,
Cow::Owned(sysvar_cache),
Some(LogCollector::new_ref()),
ComputeBudget::default(),
Rc::new(RefCell::new(TransactionExecutorCache::default())),
Arc::new(FeatureSet::all_enabled()),
Hash::default(),
0,
0,
)
}
/// Push a stack frame onto the invocation stack
pub fn push(&mut self) -> Result<(), InstructionError> {
let instruction_context = self
.transaction_context
.get_instruction_context_at_index_in_trace(
self.transaction_context.get_instruction_trace_length(),
)?;
let program_id = instruction_context
.get_last_program_key(self.transaction_context)
.map_err(|_| InstructionError::UnsupportedProgramId)?;
if self
.transaction_context
.get_instruction_context_stack_height()
== 0
{
self.current_compute_budget = self.compute_budget;
if !self
.feature_set
.is_active(&enable_early_verification_of_account_modifications::id())
{
self.pre_accounts = Vec::with_capacity(
instruction_context.get_number_of_instruction_accounts() as usize,
);
for instruction_account_index in
0..instruction_context.get_number_of_instruction_accounts()
{
if instruction_context
.is_instruction_account_duplicate(instruction_account_index)?
.is_some()
{
continue; // Skip duplicate account
}
let index_in_transaction = instruction_context
.get_index_of_instruction_account_in_transaction(
instruction_account_index,
)?;
if index_in_transaction >= self.transaction_context.get_number_of_accounts() {
return Err(InstructionError::MissingAccount);
}
let account = self
.transaction_context
.get_account_at_index(index_in_transaction)?
.borrow()
.clone();
self.pre_accounts.push(PreAccount::new(
self.transaction_context
.get_key_of_account_at_index(index_in_transaction)?,
account,
));
}
}
} else {
let contains = (0..self
.transaction_context
.get_instruction_context_stack_height())
.any(|level| {
self.transaction_context
.get_instruction_context_at_nesting_level(level)
.and_then(|instruction_context| {
instruction_context
.try_borrow_last_program_account(self.transaction_context)
})
.map(|program_account| program_account.get_key() == program_id)
.unwrap_or(false)
});
let is_last = self
.transaction_context
.get_current_instruction_context()
.and_then(|instruction_context| {
instruction_context.try_borrow_last_program_account(self.transaction_context)
})
.map(|program_account| program_account.get_key() == program_id)
.unwrap_or(false);
if contains && !is_last {
// Reentrancy not allowed unless caller is calling itself
return Err(InstructionError::ReentrancyNotAllowed);
}
}
self.trace_log_stack.push(TraceLogStackFrame::default());
self.syscall_context.push(None);
self.transaction_context.push()
}
/// Pop a stack frame from the invocation stack
pub fn pop(&mut self) -> Result<(), InstructionError> {
self.trace_log_stack.pop();
self.syscall_context.pop();
self.transaction_context.pop()
}
/// Current height of the invocation stack, top level instructions are height
/// `solana_sdk::instruction::TRANSACTION_LEVEL_STACK_HEIGHT`
pub fn get_stack_height(&self) -> usize {
self.transaction_context
.get_instruction_context_stack_height()
}
/// Verify the results of an instruction
///
/// Note: `instruction_accounts` must be the same as passed to `InvokeContext::push()`,
/// so that they match the order of `pre_accounts`.
fn verify(
&mut self,
instruction_accounts: &[InstructionAccount],
program_indices: &[IndexOfAccount],
) -> Result<(), InstructionError> {
let instruction_context = self
.transaction_context
.get_current_instruction_context()
.map_err(|_| InstructionError::CallDepth)?;
let program_id = instruction_context
.get_last_program_key(self.transaction_context)
.map_err(|_| InstructionError::CallDepth)?;
// Verify all executable accounts have zero outstanding refs
for account_index in program_indices.iter() {
self.transaction_context
.get_account_at_index(*account_index)?
.try_borrow_mut()
.map_err(|_| InstructionError::AccountBorrowOutstanding)?;
}
// Verify the per-account instruction results
let (mut pre_sum, mut post_sum) = (0_u128, 0_u128);
let mut pre_account_index = 0;
for (instruction_account_index, instruction_account) in
instruction_accounts.iter().enumerate()
{
if instruction_account_index as IndexOfAccount != instruction_account.index_in_callee {
continue; // Skip duplicate account
}
{
// Verify account has no outstanding references
let _ = self
.transaction_context
.get_account_at_index(instruction_account.index_in_transaction)?
.try_borrow_mut()
.map_err(|_| InstructionError::AccountBorrowOutstanding)?;
}
let pre_account = &self
.pre_accounts
.get(pre_account_index)
.ok_or(InstructionError::NotEnoughAccountKeys)?;
pre_account_index = pre_account_index.saturating_add(1);
let account = self
.transaction_context
.get_account_at_index(instruction_account.index_in_transaction)?
.borrow();
pre_account
.verify(
program_id,
instruction_account.is_writable,
&self.rent,
&account,
&mut self.timings,
true,
)
.map_err(|err| {
ic_logger_msg!(
self.log_collector,
"failed to verify account {}: {}",
pre_account.key(),
err
);
err
})?;
pre_sum = pre_sum
.checked_add(u128::from(pre_account.lamports()))
.ok_or(InstructionError::UnbalancedInstruction)?;
post_sum = post_sum
.checked_add(u128::from(account.lamports()))
.ok_or(InstructionError::UnbalancedInstruction)?;
let pre_data_len = pre_account.data().len() as i64;
let post_data_len = account.data().len() as i64;
let data_len_delta = post_data_len.saturating_sub(pre_data_len);
self.accounts_data_meter
.adjust_delta_unchecked(data_len_delta);
}
// Verify that the total sum of all the lamports did not change
if pre_sum != post_sum {
return Err(InstructionError::UnbalancedInstruction);
}
Ok(())
}
/// Verify and update PreAccount state based on program execution
///
/// Note: `instruction_accounts` must be the same as passed to `InvokeContext::push()`,
/// so that they match the order of `pre_accounts`.
fn verify_and_update(
&mut self,
instruction_accounts: &[InstructionAccount],
before_instruction_context_push: bool,
) -> Result<(), InstructionError> {
let transaction_context = &self.transaction_context;
let instruction_context = transaction_context.get_current_instruction_context()?;
let program_id = instruction_context
.get_last_program_key(transaction_context)
.map_err(|_| InstructionError::CallDepth)?;
// Verify the per-account instruction results
let (mut pre_sum, mut post_sum) = (0_u128, 0_u128);
for (instruction_account_index, instruction_account) in
instruction_accounts.iter().enumerate()
{
if instruction_account_index as IndexOfAccount != instruction_account.index_in_callee {
continue; // Skip duplicate account
}
if instruction_account.index_in_transaction
< transaction_context.get_number_of_accounts()
{
let key = transaction_context
.get_key_of_account_at_index(instruction_account.index_in_transaction)?;
let account = transaction_context
.get_account_at_index(instruction_account.index_in_transaction)?;
let is_writable = if before_instruction_context_push {
instruction_context
.is_instruction_account_writable(instruction_account.index_in_caller)?
} else {
instruction_account.is_writable
};
// Find the matching PreAccount
for pre_account in self.pre_accounts.iter_mut() {
if key == pre_account.key() {
{
// Verify account has no outstanding references
let _ = account
.try_borrow_mut()
.map_err(|_| InstructionError::AccountBorrowOutstanding)?;
}
let account = account.borrow();
pre_account
.verify(
program_id,
is_writable,
&self.rent,
&account,
&mut self.timings,
false,
)
.map_err(|err| {
ic_logger_msg!(
self.log_collector,
"failed to verify account {}: {}",
key,
err
);
err
})?;
pre_sum = pre_sum
.checked_add(u128::from(pre_account.lamports()))
.ok_or(InstructionError::UnbalancedInstruction)?;
post_sum = post_sum
.checked_add(u128::from(account.lamports()))
.ok_or(InstructionError::UnbalancedInstruction)?;
if is_writable && !pre_account.executable() {
pre_account.update(account.clone());
}
let pre_data_len = pre_account.data().len() as i64;
let post_data_len = account.data().len() as i64;
let data_len_delta = post_data_len.saturating_sub(pre_data_len);
self.accounts_data_meter
.adjust_delta_unchecked(data_len_delta);
break;
}
}
}
}
// Verify that the total sum of all the lamports did not change
if pre_sum != post_sum {
return Err(InstructionError::UnbalancedInstruction);
}
Ok(())
}
/// Entrypoint for a cross-program invocation from a builtin program
pub fn native_invoke(
&mut self,
instruction: StableInstruction,
signers: &[Pubkey],
) -> Result<(), InstructionError> {
let (instruction_accounts, program_indices) =
self.prepare_instruction(&instruction, signers)?;
let mut compute_units_consumed = 0;
self.process_instruction(
&instruction.data,
&instruction_accounts,
&program_indices,
&mut compute_units_consumed,
&mut ExecuteTimings::default(),
)?;
Ok(())
}
/// Helper to prepare for process_instruction()
#[allow(clippy::type_complexity)]
pub fn prepare_instruction(
&mut self,
instruction: &StableInstruction,
signers: &[Pubkey],
) -> Result<(Vec<InstructionAccount>, Vec<IndexOfAccount>), InstructionError> {
// Finds the index of each account in the instruction by its pubkey.
// Then normalizes / unifies the privileges of duplicate accounts.
// Note: This is an O(n^2) algorithm,
// but performed on a very small slice and requires no heap allocations.
let instruction_context = self.transaction_context.get_current_instruction_context()?;
let mut deduplicated_instruction_accounts: Vec<InstructionAccount> = Vec::new();
let mut duplicate_indicies = Vec::with_capacity(instruction.accounts.len());
for (instruction_account_index, account_meta) in instruction.accounts.iter().enumerate() {
let index_in_transaction = self
.transaction_context
.find_index_of_account(&account_meta.pubkey)
.ok_or_else(|| {
ic_msg!(
self,
"Instruction references an unknown account {}",
account_meta.pubkey,
);
InstructionError::MissingAccount
})?;
if let Some(duplicate_index) =
deduplicated_instruction_accounts
.iter()
.position(|instruction_account| {
instruction_account.index_in_transaction == index_in_transaction
})
{
duplicate_indicies.push(duplicate_index);
let instruction_account = deduplicated_instruction_accounts
.get_mut(duplicate_index)
.ok_or(InstructionError::NotEnoughAccountKeys)?;
instruction_account.is_signer |= account_meta.is_signer;
instruction_account.is_writable |= account_meta.is_writable;
} else {
let index_in_caller = instruction_context
.find_index_of_instruction_account(
self.transaction_context,
&account_meta.pubkey,
)
.ok_or_else(|| {
ic_msg!(
self,
"Instruction references an unknown account {}",
account_meta.pubkey,
);
InstructionError::MissingAccount
})?;
duplicate_indicies.push(deduplicated_instruction_accounts.len());
deduplicated_instruction_accounts.push(InstructionAccount {
index_in_transaction,
index_in_caller,
index_in_callee: instruction_account_index as IndexOfAccount,
is_signer: account_meta.is_signer,
is_writable: account_meta.is_writable,
});
}
}
for instruction_account in deduplicated_instruction_accounts.iter() {
let borrowed_account = instruction_context.try_borrow_instruction_account(
self.transaction_context,
instruction_account.index_in_caller,
)?;
// Readonly in caller cannot become writable in callee
if instruction_account.is_writable && !borrowed_account.is_writable() {
ic_msg!(
self,
"{}'s writable privilege escalated",
borrowed_account.get_key(),
);
return Err(InstructionError::PrivilegeEscalation);
}
// To be signed in the callee,
// it must be either signed in the caller or by the program
if instruction_account.is_signer
&& !(borrowed_account.is_signer() || signers.contains(borrowed_account.get_key()))
{
ic_msg!(
self,
"{}'s signer privilege escalated",
borrowed_account.get_key()
);
return Err(InstructionError::PrivilegeEscalation);
}
}
let instruction_accounts = duplicate_indicies
.into_iter()
.map(|duplicate_index| {
Ok(deduplicated_instruction_accounts
.get(duplicate_index)
.ok_or(InstructionError::NotEnoughAccountKeys)?
.clone())
})
.collect::<Result<Vec<InstructionAccount>, InstructionError>>()?;
// Find and validate executables / program accounts
let callee_program_id = instruction.program_id;
let program_account_index = instruction_context
.find_index_of_instruction_account(self.transaction_context, &callee_program_id)
.ok_or_else(|| {
ic_msg!(self, "Unknown program {}", callee_program_id);
InstructionError::MissingAccount
})?;
let borrowed_program_account = instruction_context
.try_borrow_instruction_account(self.transaction_context, program_account_index)?;
if !borrowed_program_account.is_executable() {
ic_msg!(self, "Account {} is not executable", callee_program_id);
return Err(InstructionError::AccountNotExecutable);
}
let mut program_indices = vec![];
if borrowed_program_account.get_owner() == &bpf_loader_upgradeable::id() {
if let UpgradeableLoaderState::Program {
programdata_address,
} = borrowed_program_account.get_state()?
{
if let Some(programdata_account_index) = self
.transaction_context
.find_index_of_program_account(&programdata_address)
{
program_indices.push(programdata_account_index);
} else {
ic_msg!(
self,
"Unknown upgradeable programdata account {}",
programdata_address,
);
return Err(InstructionError::MissingAccount);
}
} else {
ic_msg!(
self,
"Invalid upgradeable program account {}",
callee_program_id,
);
return Err(InstructionError::MissingAccount);
}
}
program_indices.push(borrowed_program_account.get_index_in_transaction());
Ok((instruction_accounts, program_indices))
}
/// Processes an instruction and returns how many compute units were used
pub fn process_instruction(
&mut self,
instruction_data: &[u8],
instruction_accounts: &[InstructionAccount],
program_indices: &[IndexOfAccount],
compute_units_consumed: &mut u64,
timings: &mut ExecuteTimings,
) -> Result<(), InstructionError> {
*compute_units_consumed = 0;
let nesting_level = self
.transaction_context
.get_instruction_context_stack_height();
let is_top_level_instruction = nesting_level == 0;
if !is_top_level_instruction
&& !self
.feature_set
.is_active(&enable_early_verification_of_account_modifications::id())
{
// Verify the calling program hasn't misbehaved
let mut verify_caller_time = Measure::start("verify_caller_time");
let verify_caller_result = self.verify_and_update(instruction_accounts, true);
verify_caller_time.stop();
saturating_add_assign!(
timings
.execute_accessories
.process_instructions
.verify_caller_us,
verify_caller_time.as_us()
);
verify_caller_result?;
}
self.transaction_context
.get_next_instruction_context()?
.configure(program_indices, instruction_accounts, instruction_data);
self.push()?;
self.process_executable_chain(compute_units_consumed, timings)
.and_then(|_| {
if self
.feature_set
.is_active(&enable_early_verification_of_account_modifications::id())
{
Ok(())
} else {
// Verify the called program has not misbehaved
let mut verify_callee_time = Measure::start("verify_callee_time");
let result = if is_top_level_instruction {
self.verify(instruction_accounts, program_indices)
} else {
self.verify_and_update(instruction_accounts, false)
};
verify_callee_time.stop();
saturating_add_assign!(
timings
.execute_accessories
.process_instructions
.verify_callee_us,
verify_callee_time.as_us()
);
result
}
})
// MUST pop if and only if `push` succeeded, independent of `result`.
// Thus, the `.and()` instead of an `.and_then()`.
.and(self.pop())
}
/// Calls the instruction's program entrypoint method
fn process_executable_chain(
&mut self,
compute_units_consumed: &mut u64,
timings: &mut ExecuteTimings,
) -> Result<(), InstructionError> {
let instruction_context = self.transaction_context.get_current_instruction_context()?;
let mut process_executable_chain_time = Measure::start("process_executable_chain_time");
let builtin_id = {
let borrowed_root_account = instruction_context
.try_borrow_program_account(self.transaction_context, 0)
.map_err(|_| InstructionError::UnsupportedProgramId)?;
let owner_id = borrowed_root_account.get_owner();
if native_loader::check_id(owner_id) {
*borrowed_root_account.get_key()
} else {
*owner_id
}
};
for entry in self.builtin_programs {
if entry.program_id == builtin_id {
let program_id =
*instruction_context.get_last_program_key(self.transaction_context)?;
self.transaction_context
.set_return_data(program_id, Vec::new())?;
let pre_remaining_units = self.get_remaining();
let result = if builtin_id == program_id {
let logger = self.get_log_collector();
stable_log::program_invoke(&logger, &program_id, self.get_stack_height());
(entry.process_instruction)(self)
.map(|()| {
stable_log::program_success(&logger, &program_id);
})
.map_err(|err| {
stable_log::program_failure(&logger, &program_id, &err);
err
})
} else {
(entry.process_instruction)(self)
};
let post_remaining_units = self.get_remaining();
*compute_units_consumed = pre_remaining_units.saturating_sub(post_remaining_units);
process_executable_chain_time.stop();
saturating_add_assign!(
timings
.execute_accessories
.process_instructions
.process_executable_chain_us,
process_executable_chain_time.as_us()
);
return result;
}
}
Err(InstructionError::UnsupportedProgramId)
}
/// Get this invocation's LogCollector
pub fn get_log_collector(&self) -> Option<Rc<RefCell<LogCollector>>> {
self.log_collector.clone()
}
/// Consume compute units
pub fn consume_checked(&self, amount: u64) -> Result<(), InstructionError> {
self.log_consumed_bpf_units(amount);
let mut compute_meter = self.compute_meter.borrow_mut();
let exceeded = *compute_meter < amount;
*compute_meter = compute_meter.saturating_sub(amount);
if exceeded {
return Err(InstructionError::ComputationalBudgetExceeded);
}
Ok(())
}
/// Set compute units
///
/// Only use for tests and benchmarks
pub fn mock_set_remaining(&self, remaining: u64) {
*self.compute_meter.borrow_mut() = remaining;
}
/// Get this invocation's AccountsDataMeter
pub fn get_accounts_data_meter(&self) -> &AccountsDataMeter {
&self.accounts_data_meter
}
/// Get this invocation's compute budget
pub fn get_compute_budget(&self) -> &ComputeBudget {
&self.current_compute_budget
}
/// Get cached sysvars
pub fn get_sysvar_cache(&self) -> &SysvarCache {
&self.sysvar_cache
}
// Set this instruction syscall context
pub fn set_syscall_context(
&mut self,
check_aligned: bool,
check_size: bool,
orig_account_lengths: Vec<usize>,
allocator: Rc<RefCell<dyn Alloc>>,
) -> Result<(), InstructionError> {
*self
.syscall_context
.last_mut()
.ok_or(InstructionError::CallDepth)? = Some(SyscallContext {
check_aligned,
check_size,
orig_account_lengths,
allocator,
});
Ok(())
}
// Should alignment be enforced during user pointer translation
pub fn get_check_aligned(&self) -> bool {
self.syscall_context
.last()
.and_then(|context| context.as_ref())
.map(|context| context.check_aligned)
.unwrap_or(true)
}
// Set should type size be checked during user pointer translation
pub fn get_check_size(&self) -> bool {
self.syscall_context
.last()
.and_then(|context| context.as_ref())
.map(|context| context.check_size)
.unwrap_or(true)
}
/// Get the original account lengths
pub fn get_orig_account_lengths(&self) -> Result<&[usize], InstructionError> {
self.syscall_context
.last()
.and_then(|context| context.as_ref())
.map(|context| context.orig_account_lengths.as_slice())
.ok_or(InstructionError::CallDepth)
}
// Get this instruction's memory allocator
pub fn get_allocator(&self) -> Result<Rc<RefCell<dyn Alloc>>, InstructionError> {
self.syscall_context
.last()
.and_then(|context| context.as_ref())
.map(|context| context.allocator.clone())
.ok_or(InstructionError::CallDepth)
}
fn log_consumed_bpf_units(&self, amount: u64) {
if self.enable_instruction_tracing && amount != 0 {
let trace_log_stack_frame = self
.trace_log_stack
.last()
.expect("Inconsistent trace log stack");
trace_log_stack_frame.consumed_bpf_units.borrow_mut().push((
trace_log_stack_frame.trace_log.len().saturating_sub(1),
amount,
));
}
}
}
pub struct MockInvokeContextPreparation {
pub transaction_accounts: Vec<TransactionAccount>,
pub instruction_accounts: Vec<InstructionAccount>,
}
pub fn prepare_mock_invoke_context(
transaction_accounts: Vec<TransactionAccount>,
instruction_account_metas: Vec<AccountMeta>,
_program_indices: &[IndexOfAccount],
) -> MockInvokeContextPreparation {
let mut instruction_accounts: Vec<InstructionAccount> =
Vec::with_capacity(instruction_account_metas.len());
for (instruction_account_index, account_meta) in instruction_account_metas.iter().enumerate() {
let index_in_transaction = transaction_accounts
.iter()
.position(|(key, _account)| *key == account_meta.pubkey)
.unwrap_or(transaction_accounts.len())
as IndexOfAccount;
let index_in_callee = instruction_accounts
.get(0..instruction_account_index)
.unwrap()
.iter()
.position(|instruction_account| {
instruction_account.index_in_transaction == index_in_transaction
})
.unwrap_or(instruction_account_index) as IndexOfAccount;
instruction_accounts.push(InstructionAccount {
index_in_transaction,
index_in_caller: index_in_transaction,
index_in_callee,
is_signer: account_meta.is_signer,
is_writable: account_meta.is_writable,
});
}
MockInvokeContextPreparation {
transaction_accounts,
instruction_accounts,
}
}
pub fn with_mock_invoke_context<R, F: FnMut(&mut InvokeContext) -> R>(
loader_id: Pubkey,
account_size: usize,
is_writable: bool,
mut callback: F,
) -> R {
let program_indices = vec![0, 1];
let program_key = Pubkey::new_unique();
let transaction_accounts = vec![
(
loader_id,
AccountSharedData::new(0, 0, &native_loader::id()),
),
(program_key, AccountSharedData::new(1, 0, &loader_id)),
(
Pubkey::new_unique(),
AccountSharedData::new(2, account_size, &program_key),
),
];
let instruction_accounts = vec![AccountMeta {
pubkey: transaction_accounts.get(2).unwrap().0,
is_signer: false,
is_writable,
}];
let preparation =
prepare_mock_invoke_context(transaction_accounts, instruction_accounts, &program_indices);
let compute_budget = ComputeBudget::default();
let mut transaction_context = TransactionContext::new(
preparation.transaction_accounts,
Some(Rent::default()),
compute_budget.max_invoke_stack_height,
compute_budget.max_instruction_trace_length,
);
transaction_context.enable_cap_accounts_data_allocations_per_transaction();
let mut invoke_context = InvokeContext::new_mock(&mut transaction_context, &[]);
invoke_context
.transaction_context
.get_next_instruction_context()
.unwrap()
.configure(&program_indices, &preparation.instruction_accounts, &[]);
invoke_context.push().unwrap();
callback(&mut invoke_context)
}
pub fn mock_process_instruction(
loader_id: &Pubkey,
mut program_indices: Vec<IndexOfAccount>,
instruction_data: &[u8],
transaction_accounts: Vec<TransactionAccount>,
instruction_accounts: Vec<AccountMeta>,
sysvar_cache_override: Option<&SysvarCache>,
feature_set_override: Option<Arc<FeatureSet>>,
expected_result: Result<(), InstructionError>,
process_instruction: ProcessInstructionWithContext,
) -> Vec<AccountSharedData> {
program_indices.insert(0, transaction_accounts.len() as IndexOfAccount);
let mut preparation =
prepare_mock_invoke_context(transaction_accounts, instruction_accounts, &program_indices);
let processor_account = AccountSharedData::new(0, 0, &native_loader::id());