-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
Copy pathinvoke_context.rs
1898 lines (1769 loc) · 70.5 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
#[allow(deprecated)]
use solana_sdk::keyed_account::{create_keyed_accounts_unified, KeyedAccount};
use {
crate::{
accounts_data_meter::AccountsDataMeter,
compute_budget::ComputeBudget,
ic_logger_msg, ic_msg,
log_collector::LogCollector,
pre_account::PreAccount,
sysvar_cache::SysvarCache,
timings::{ExecuteDetailsTimings, ExecuteTimings},
},
solana_measure::measure::Measure,
solana_sdk::{
account::{AccountSharedData, ReadableAccount},
bpf_loader_upgradeable::{self, UpgradeableLoaderState},
feature_set::{
cap_accounts_data_len, do_support_realloc, neon_evm_compute_budget,
record_instruction_in_transaction_context_push,
reject_empty_instruction_without_program, requestable_heap_size, tx_wide_compute_cap,
FeatureSet,
},
hash::Hash,
instruction::{AccountMeta, Instruction, InstructionError},
native_loader,
pubkey::Pubkey,
rent::Rent,
saturating_add_assign,
transaction_context::{
InstructionAccount, InstructionContext, TransactionAccount, TransactionContext,
},
},
std::{
alloc::Layout,
borrow::Cow,
cell::RefCell,
collections::HashMap,
fmt::{self, Debug},
rc::Rc,
sync::Arc,
},
};
pub type ProcessInstructionWithContext =
fn(usize, &mut InvokeContext) -> Result<(), InstructionError>;
#[derive(Clone)]
pub struct BuiltinProgram {
pub program_id: Pubkey,
pub process_instruction: ProcessInstructionWithContext,
}
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(usize, &'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}", self.program_id, erased_instruction)
}
}
/// Program executor
pub trait Executor: Debug + Send + Sync {
/// Execute the program
fn execute(
&self,
first_instruction_account: usize,
invoke_context: &mut InvokeContext,
) -> Result<(), InstructionError>;
}
pub type Executors = HashMap<Pubkey, TransactionExecutor>;
/// Tracks whether a given executor is "dirty" and needs to updated in the
/// executors cache
#[derive(Debug)]
pub struct TransactionExecutor {
executor: Arc<dyn Executor>,
is_miss: bool,
is_updated: bool,
}
impl TransactionExecutor {
/// Wraps an executor and tracks that it doesn't need to be updated in the
/// executors cache.
pub fn new_cached(executor: Arc<dyn Executor>) -> Self {
Self {
executor,
is_miss: false,
is_updated: false,
}
}
/// Wraps an executor and tracks that it needs to be updated in the
/// executors cache.
pub fn new_miss(executor: Arc<dyn Executor>) -> Self {
Self {
executor,
is_miss: true,
is_updated: false,
}
}
/// Wraps an executor and tracks that it needs to be updated in the
/// executors cache only if the transaction succeeded.
pub fn new_updated(executor: Arc<dyn Executor>) -> Self {
Self {
executor,
is_miss: false,
is_updated: true,
}
}
pub fn is_dirty(&self, include_updates: bool) -> bool {
self.is_miss || (include_updates && self.is_updated)
}
pub fn get(&self) -> Arc<dyn Executor> {
self.executor.clone()
}
pub fn clear_miss_for_test(&mut self) {
self.is_miss = false;
}
}
/// Compute meter
pub struct ComputeMeter {
remaining: u64,
}
impl ComputeMeter {
/// Consume compute units
pub fn consume(&mut self, amount: u64) -> Result<(), InstructionError> {
let exceeded = self.remaining < amount;
self.remaining = self.remaining.saturating_sub(amount);
if exceeded {
return Err(InstructionError::ComputationalBudgetExceeded);
}
Ok(())
}
/// Get the number of remaining compute units
pub fn get_remaining(&self) -> u64 {
self.remaining
}
/// Set compute units
///
/// Only use for tests and benchmarks
pub fn mock_set_remaining(&mut self, remaining: u64) {
self.remaining = remaining;
}
/// Construct a new one with the given remaining units
pub fn new_ref(remaining: u64) -> Rc<RefCell<Self>> {
Rc::new(RefCell::new(Self { remaining }))
}
}
/// 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")
}
}
#[deprecated(
since = "1.11.0",
note = "Please use InstructionContext instead of StackFrame"
)]
#[allow(deprecated)]
pub struct StackFrame<'a> {
pub number_of_program_accounts: usize,
pub keyed_accounts: Vec<KeyedAccount<'a>>,
pub keyed_accounts_range: std::ops::Range<usize>,
}
#[allow(deprecated)]
impl<'a> StackFrame<'a> {
pub fn new(number_of_program_accounts: usize, keyed_accounts: Vec<KeyedAccount<'a>>) -> Self {
let keyed_accounts_range = std::ops::Range {
start: 0,
end: keyed_accounts.len(),
};
Self {
number_of_program_accounts,
keyed_accounts,
keyed_accounts_range,
}
}
pub fn program_id(&self) -> Option<&Pubkey> {
self.keyed_accounts
.get(self.number_of_program_accounts.saturating_sub(1))
.map(|keyed_account| keyed_account.unsigned_key())
}
}
pub struct InvokeContext<'a> {
pub transaction_context: &'a mut TransactionContext,
#[allow(deprecated)]
invoke_stack: Vec<StackFrame<'a>>,
rent: Rent,
pre_accounts: Vec<PreAccount>,
builtin_programs: &'a [BuiltinProgram],
pub sysvar_cache: Cow<'a, SysvarCache>,
log_collector: Option<Rc<RefCell<LogCollector>>>,
compute_budget: ComputeBudget,
current_compute_budget: ComputeBudget,
compute_meter: Rc<RefCell<ComputeMeter>>,
accounts_data_meter: AccountsDataMeter,
executors: Rc<RefCell<Executors>>,
pub feature_set: Arc<FeatureSet>,
pub timings: ExecuteDetailsTimings,
pub blockhash: Hash,
pub lamports_per_signature: u64,
check_aligned: bool,
check_size: bool,
orig_account_lengths: Vec<Option<Vec<usize>>>,
allocators: Vec<Option<Rc<RefCell<dyn Alloc>>>>,
}
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,
executors: Rc<RefCell<Executors>>,
feature_set: Arc<FeatureSet>,
blockhash: Hash,
lamports_per_signature: u64,
initial_accounts_data_len: u64,
) -> Self {
Self {
transaction_context,
invoke_stack: Vec::with_capacity(compute_budget.max_invoke_depth),
rent,
pre_accounts: Vec::new(),
builtin_programs,
sysvar_cache,
log_collector,
current_compute_budget: compute_budget,
compute_budget,
compute_meter: ComputeMeter::new_ref(compute_budget.max_units),
accounts_data_meter: AccountsDataMeter::new(initial_accounts_data_len),
executors,
feature_set,
timings: ExecuteDetailsTimings::default(),
blockhash,
lamports_per_signature,
check_aligned: true,
check_size: true,
orig_account_lengths: Vec::new(),
allocators: Vec::new(),
}
}
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| {
(0..transaction_context.get_number_of_accounts()).find_map(|index| {
if transaction_context
.get_key_of_account_at_index(index)
.unwrap()
== pubkey
{
Some(
transaction_context
.get_account_at_index(index)
.unwrap()
.borrow()
.clone(),
)
} else {
None
}
})
});
Self::new(
transaction_context,
Rent::default(),
builtin_programs,
Cow::Owned(sysvar_cache),
Some(LogCollector::new_ref()),
ComputeBudget::default(),
Rc::new(RefCell::new(Executors::default())),
Arc::new(FeatureSet::all_enabled()),
Hash::default(),
0,
0,
)
}
/// Push a stack frame onto the invocation stack
pub fn push(
&mut self,
instruction_accounts: &[InstructionAccount],
program_indices: &[usize],
instruction_data: &[u8],
) -> Result<(), InstructionError> {
if !self
.feature_set
.is_active(&record_instruction_in_transaction_context_push::id())
&& self
.transaction_context
.get_instruction_context_stack_height()
> self.compute_budget.max_invoke_depth
{
return Err(InstructionError::CallDepth);
}
let program_id = program_indices
.last()
.map(|account_index| {
self.transaction_context
.get_key_of_account_at_index(*account_index)
})
.transpose()?;
if program_id.is_none()
&& self
.feature_set
.is_active(&reject_empty_instruction_without_program::id())
{
return Err(InstructionError::UnsupportedProgramId);
}
if self
.transaction_context
.get_instruction_context_stack_height()
== 0
{
let mut compute_budget = self.compute_budget;
if !self.feature_set.is_active(&tx_wide_compute_cap::id())
&& self.feature_set.is_active(&neon_evm_compute_budget::id())
&& program_id == Some(&crate::neon_evm_program::id())
{
// Bump the compute budget for neon_evm
compute_budget.max_units = compute_budget.max_units.max(500_000);
}
if !self.feature_set.is_active(&requestable_heap_size::id())
&& self.feature_set.is_active(&neon_evm_compute_budget::id())
&& program_id == Some(&crate::neon_evm_program::id())
{
// Bump the compute budget for neon_evm
compute_budget.heap_size = Some(256_usize.saturating_mul(1024));
}
self.current_compute_budget = compute_budget;
if !self.feature_set.is_active(&tx_wide_compute_cap::id()) {
self.compute_meter = ComputeMeter::new_ref(self.current_compute_budget.max_units);
}
self.pre_accounts = Vec::with_capacity(instruction_accounts.len());
let mut work = |_index_in_instruction: usize,
instruction_account: &InstructionAccount| {
if instruction_account.index_in_transaction
< self.transaction_context.get_number_of_accounts()
{
let account = self
.transaction_context
.get_account_at_index(instruction_account.index_in_transaction)?
.borrow()
.clone();
self.pre_accounts.push(PreAccount::new(
self.transaction_context.get_key_of_account_at_index(
instruction_account.index_in_transaction,
)?,
account,
));
return Ok(());
}
Err(InstructionError::MissingAccount)
};
visit_each_account_once(
instruction_accounts,
&mut work,
InstructionError::NotEnoughAccountKeys,
)?;
} else {
let contains = (0..self
.transaction_context
.get_instruction_context_stack_height())
.any(|level| {
self.transaction_context
.get_instruction_context_at(level)
.and_then(|instruction_context| {
instruction_context.try_borrow_program_account(self.transaction_context)
})
.map(|program_account| Some(program_account.get_key()) == program_id)
.unwrap_or_else(|_| program_id.is_none())
});
let is_last = self
.transaction_context
.get_current_instruction_context()
.and_then(|instruction_context| {
instruction_context.try_borrow_program_account(self.transaction_context)
})
.map(|program_account| Some(program_account.get_key()) == program_id)
.unwrap_or_else(|_| program_id.is_none());
if contains && !is_last {
// Reentrancy not allowed unless caller is calling itself
return Err(InstructionError::ReentrancyNotAllowed);
}
}
// Create the KeyedAccounts that will be passed to the program
#[allow(deprecated)]
let keyed_accounts = program_indices
.iter()
.map(|account_index| {
Ok((
false,
false,
self.transaction_context
.get_key_of_account_at_index(*account_index)?,
self.transaction_context
.get_account_at_index(*account_index)?,
))
})
.chain(instruction_accounts.iter().map(|instruction_account| {
Ok((
instruction_account.is_signer,
instruction_account.is_writable,
self.transaction_context
.get_key_of_account_at_index(instruction_account.index_in_transaction)?,
self.transaction_context
.get_account_at_index(instruction_account.index_in_transaction)?,
))
}))
.collect::<Result<Vec<_>, InstructionError>>()?;
// Unsafe will be removed together with the keyed_accounts
#[allow(deprecated)]
self.invoke_stack.push(StackFrame::new(
program_indices.len(),
create_keyed_accounts_unified(unsafe {
std::mem::transmute(keyed_accounts.as_slice())
}),
));
self.orig_account_lengths.push(None);
self.allocators.push(None);
self.transaction_context.push(
program_indices,
instruction_accounts,
instruction_data,
self.feature_set
.is_active(&record_instruction_in_transaction_context_push::id()),
)
}
/// Pop a stack frame from the invocation stack
pub fn pop(&mut self) -> Result<(), InstructionError> {
self.orig_account_lengths.pop();
self.allocators.pop();
self.invoke_stack.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
fn verify(
&mut self,
instruction_accounts: &[InstructionAccount],
program_indices: &[usize],
) -> Result<(), InstructionError> {
let do_support_realloc = self.feature_set.is_active(&do_support_realloc::id());
let cap_accounts_data_len = self.feature_set.is_active(&cap_accounts_data_len::id());
let instruction_context = self
.transaction_context
.get_current_instruction_context()
.map_err(|_| InstructionError::CallDepth)?;
let program_id = instruction_context
.get_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;
let mut work = |_index_in_instruction: usize, instruction_account: &InstructionAccount| {
{
// 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,
do_support_realloc,
)
.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);
if cap_accounts_data_len {
self.accounts_data_meter.adjust_delta(data_len_delta)?;
} else {
self.accounts_data_meter
.adjust_delta_unchecked(data_len_delta);
}
Ok(())
};
visit_each_account_once(
instruction_accounts,
&mut work,
InstructionError::NotEnoughAccountKeys,
)?;
// 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
fn verify_and_update(
&mut self,
instruction_accounts: &[InstructionAccount],
before_instruction_context_push: bool,
) -> Result<(), InstructionError> {
let do_support_realloc = self.feature_set.is_active(&do_support_realloc::id());
let cap_accounts_data_len = self.feature_set.is_active(&cap_accounts_data_len::id());
let transaction_context = &self.transaction_context;
let instruction_context = transaction_context.get_current_instruction_context()?;
let program_id = instruction_context
.get_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);
let mut work = |_index_in_instruction: usize, instruction_account: &InstructionAccount| {
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
.try_borrow_account(
self.transaction_context,
instruction_account.index_in_caller,
)?
.is_writable()
} 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,
do_support_realloc,
)
.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);
if cap_accounts_data_len {
self.accounts_data_meter.adjust_delta(data_len_delta)?;
} else {
self.accounts_data_meter
.adjust_delta_unchecked(data_len_delta);
}
return Ok(());
}
}
}
Err(InstructionError::MissingAccount)
};
visit_each_account_once(
instruction_accounts,
&mut work,
InstructionError::NotEnoughAccountKeys,
)?;
// 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: Instruction,
signers: &[Pubkey],
) -> Result<(), InstructionError> {
let (instruction_accounts, program_indices) =
self.prepare_instruction(&instruction, signers)?;
let mut prev_account_sizes = Vec::with_capacity(instruction_accounts.len());
for instruction_account in instruction_accounts.iter() {
let account_length = self
.transaction_context
.get_account_at_index(instruction_account.index_in_transaction)?
.borrow()
.data()
.len();
prev_account_sizes.push((instruction_account.index_in_transaction, account_length));
}
let mut compute_units_consumed = 0;
self.process_instruction(
&instruction.data,
&instruction_accounts,
&program_indices,
&mut compute_units_consumed,
&mut ExecuteTimings::default(),
)?;
// Verify the called program has not misbehaved
let do_support_realloc = self.feature_set.is_active(&do_support_realloc::id());
for (account_index, prev_size) in prev_account_sizes.into_iter() {
if !do_support_realloc
&& prev_size
!= self
.transaction_context
.get_account_at_index(account_index)?
.borrow()
.data()
.len()
&& prev_size != 0
{
// Only support for `CreateAccount` at this time.
// Need a way to limit total realloc size across multiple CPI calls
ic_msg!(
self,
"Inner instructions do not support realloc, only SystemProgram::CreateAccount",
);
return Err(InstructionError::InvalidRealloc);
}
}
Ok(())
}
/// Helper to prepare for process_instruction()
#[allow(clippy::type_complexity)]
pub fn prepare_instruction(
&mut self,
instruction: &Instruction,
signers: &[Pubkey],
) -> Result<(Vec<InstructionAccount>, Vec<usize>), InstructionError> {
// Finds the index of each account in the instruction by its pubkey.
// Then normalizes / unifies the privileges of duplicate accounts.
// Note: This works like visit_each_account_once() and is an O(n^2) algorithm too.
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 account_meta in instruction.accounts.iter() {
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_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,
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_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_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_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: &[usize],
compute_units_consumed: &mut u64,
timings: &mut ExecuteTimings,
) -> Result<(), InstructionError> {
*compute_units_consumed = 0;
let program_id = program_indices
.last()
.map(|index| {
self.transaction_context
.get_key_of_account_at_index(*index)
.map(|pubkey| *pubkey)
})
.unwrap_or_else(|| Ok(native_loader::id()))?;
let nesting_level = self
.transaction_context
.get_instruction_context_stack_height();
let is_top_level_instruction = nesting_level == 0;
if !is_top_level_instruction {
// 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?;
if !self
.feature_set
.is_active(&record_instruction_in_transaction_context_push::id())
{
self.transaction_context
.record_instruction(InstructionContext::new(
nesting_level,
program_indices,
instruction_accounts,
instruction_data,
));
}
}
let result = self
.push(instruction_accounts, program_indices, instruction_data)
.and_then(|_| {
let mut process_executable_chain_time =
Measure::start("process_executable_chain_time");
self.transaction_context
.set_return_data(program_id, Vec::new())?;
let pre_remaining_units = self.compute_meter.borrow().get_remaining();
let execution_result = self.process_executable_chain();
let post_remaining_units = self.compute_meter.borrow().get_remaining();
*compute_units_consumed = pre_remaining_units.saturating_sub(post_remaining_units);
process_executable_chain_time.stop();
// Verify the called program has not misbehaved
let mut verify_callee_time = Measure::start("verify_callee_time");
let result = execution_result.and_then(|_| {
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
.process_executable_chain_us,
process_executable_chain_time.as_us()
);
saturating_add_assign!(
timings
.execute_accessories
.process_instructions
.verify_callee_us,
verify_callee_time.as_us()
);
result
});
// Pop the invoke_stack to restore previous state
let _ = self.pop();
result
}
/// Calls the instruction's program entrypoint method
fn process_executable_chain(&mut self) -> Result<(), InstructionError> {
let instruction_context = self.transaction_context.get_current_instruction_context()?;
let borrowed_root_account = instruction_context
.try_borrow_account(self.transaction_context, 0)
.map_err(|_| InstructionError::UnsupportedProgramId)?;
let root_id = borrowed_root_account.get_key();
let owner_id = borrowed_root_account.get_owner();
if solana_sdk::native_loader::check_id(owner_id) {
for entry in self.builtin_programs {
if entry.program_id == *root_id {
drop(borrowed_root_account);
// Call the builtin program
return (entry.process_instruction)(
1, // root_id to be skipped
self,
);
}
}
} else {
for entry in self.builtin_programs {
if entry.program_id == *owner_id {
drop(borrowed_root_account);
// Call the program via a builtin loader
return (entry.process_instruction)(