invoke_context.rs 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597
  1. use {
  2. crate::{
  3. execution_budget::{SVMTransactionExecutionBudget, SVMTransactionExecutionCost},
  4. loaded_programs::{
  5. ProgramCacheEntry, ProgramCacheEntryType, ProgramCacheForTxBatch,
  6. ProgramRuntimeEnvironments,
  7. },
  8. stable_log,
  9. sysvar_cache::SysvarCache,
  10. },
  11. solana_account::{create_account_shared_data_for_test, AccountSharedData},
  12. solana_epoch_schedule::EpochSchedule,
  13. solana_hash::Hash,
  14. solana_instruction::{error::InstructionError, AccountMeta, Instruction},
  15. solana_pubkey::Pubkey,
  16. solana_sbpf::{
  17. ebpf::MM_HEAP_START,
  18. elf::Executable as GenericExecutable,
  19. error::{EbpfError, ProgramResult},
  20. memory_region::MemoryMapping,
  21. program::{BuiltinFunction, SBPFVersion},
  22. vm::{Config, ContextObject, EbpfVm},
  23. },
  24. solana_sdk_ids::{
  25. bpf_loader, bpf_loader_deprecated, bpf_loader_upgradeable, loader_v4, native_loader, sysvar,
  26. },
  27. solana_svm_callback::InvokeContextCallback,
  28. solana_svm_feature_set::SVMFeatureSet,
  29. solana_svm_log_collector::{ic_msg, LogCollector},
  30. solana_svm_measure::measure::Measure,
  31. solana_svm_timings::{ExecuteDetailsTimings, ExecuteTimings},
  32. solana_svm_transaction::{instruction::SVMInstruction, svm_message::SVMMessage},
  33. solana_svm_type_overrides::sync::Arc,
  34. solana_transaction_context::{
  35. transaction_accounts::KeyedAccountSharedData, IndexOfAccount, InstructionAccount,
  36. InstructionContext, TransactionContext, MAX_ACCOUNTS_PER_TRANSACTION,
  37. },
  38. std::{
  39. alloc::Layout,
  40. cell::RefCell,
  41. fmt::{self, Debug},
  42. rc::Rc,
  43. },
  44. };
  45. pub type BuiltinFunctionWithContext = BuiltinFunction<InvokeContext<'static>>;
  46. pub type Executable = GenericExecutable<InvokeContext<'static>>;
  47. pub type RegisterTrace<'a> = &'a [[u64; 12]];
  48. /// Adapter so we can unify the interfaces of built-in programs and syscalls
  49. #[macro_export]
  50. macro_rules! declare_process_instruction {
  51. ($process_instruction:ident, $cu_to_consume:expr, |$invoke_context:ident| $inner:tt) => {
  52. $crate::solana_sbpf::declare_builtin_function!(
  53. $process_instruction,
  54. fn rust(
  55. invoke_context: &mut $crate::invoke_context::InvokeContext,
  56. _arg0: u64,
  57. _arg1: u64,
  58. _arg2: u64,
  59. _arg3: u64,
  60. _arg4: u64,
  61. _memory_mapping: &mut $crate::solana_sbpf::memory_region::MemoryMapping,
  62. ) -> std::result::Result<u64, Box<dyn std::error::Error>> {
  63. fn process_instruction_inner(
  64. $invoke_context: &mut $crate::invoke_context::InvokeContext,
  65. ) -> std::result::Result<(), $crate::__private::InstructionError>
  66. $inner
  67. let consumption_result = if $cu_to_consume > 0
  68. {
  69. invoke_context.consume_checked($cu_to_consume)
  70. } else {
  71. Ok(())
  72. };
  73. consumption_result
  74. .and_then(|_| {
  75. process_instruction_inner(invoke_context)
  76. .map(|_| 0)
  77. .map_err(|err| Box::new(err) as Box<dyn std::error::Error>)
  78. })
  79. .into()
  80. }
  81. );
  82. };
  83. }
  84. impl ContextObject for InvokeContext<'_> {
  85. fn consume(&mut self, amount: u64) {
  86. // 1 to 1 instruction to compute unit mapping
  87. // ignore overflow, Ebpf will bail if exceeded
  88. let mut compute_meter = self.compute_meter.borrow_mut();
  89. *compute_meter = compute_meter.saturating_sub(amount);
  90. }
  91. fn get_remaining(&self) -> u64 {
  92. *self.compute_meter.borrow()
  93. }
  94. }
  95. #[derive(Clone, PartialEq, Eq, Debug)]
  96. pub struct AllocErr;
  97. impl fmt::Display for AllocErr {
  98. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  99. f.write_str("Error: Memory allocation failed")
  100. }
  101. }
  102. pub struct BpfAllocator {
  103. len: u64,
  104. pos: u64,
  105. }
  106. impl BpfAllocator {
  107. pub fn new(len: u64) -> Self {
  108. Self { len, pos: 0 }
  109. }
  110. pub fn alloc(&mut self, layout: Layout) -> Result<u64, AllocErr> {
  111. let bytes_to_align = (self.pos as *const u8).align_offset(layout.align()) as u64;
  112. if self
  113. .pos
  114. .saturating_add(bytes_to_align)
  115. .saturating_add(layout.size() as u64)
  116. <= self.len
  117. {
  118. self.pos = self.pos.saturating_add(bytes_to_align);
  119. let addr = MM_HEAP_START.saturating_add(self.pos);
  120. self.pos = self.pos.saturating_add(layout.size() as u64);
  121. Ok(addr)
  122. } else {
  123. Err(AllocErr)
  124. }
  125. }
  126. }
  127. pub struct EnvironmentConfig<'a> {
  128. pub blockhash: Hash,
  129. pub blockhash_lamports_per_signature: u64,
  130. epoch_stake_callback: &'a dyn InvokeContextCallback,
  131. feature_set: &'a SVMFeatureSet,
  132. pub program_runtime_environments_for_execution: &'a ProgramRuntimeEnvironments,
  133. pub program_runtime_environments_for_deployment: &'a ProgramRuntimeEnvironments,
  134. sysvar_cache: &'a SysvarCache,
  135. }
  136. impl<'a> EnvironmentConfig<'a> {
  137. pub fn new(
  138. blockhash: Hash,
  139. blockhash_lamports_per_signature: u64,
  140. epoch_stake_callback: &'a dyn InvokeContextCallback,
  141. feature_set: &'a SVMFeatureSet,
  142. program_runtime_environments_for_execution: &'a ProgramRuntimeEnvironments,
  143. program_runtime_environments_for_deployment: &'a ProgramRuntimeEnvironments,
  144. sysvar_cache: &'a SysvarCache,
  145. ) -> Self {
  146. Self {
  147. blockhash,
  148. blockhash_lamports_per_signature,
  149. epoch_stake_callback,
  150. feature_set,
  151. program_runtime_environments_for_execution,
  152. program_runtime_environments_for_deployment,
  153. sysvar_cache,
  154. }
  155. }
  156. }
  157. pub struct SyscallContext {
  158. pub allocator: BpfAllocator,
  159. pub accounts_metadata: Vec<SerializedAccountMetadata>,
  160. }
  161. #[derive(Debug, Clone)]
  162. pub struct SerializedAccountMetadata {
  163. pub original_data_len: usize,
  164. pub vm_data_addr: u64,
  165. pub vm_key_addr: u64,
  166. pub vm_lamports_addr: u64,
  167. pub vm_owner_addr: u64,
  168. }
  169. /// Main pipeline from runtime to program execution.
  170. pub struct InvokeContext<'a> {
  171. /// Information about the currently executing transaction.
  172. pub transaction_context: &'a mut TransactionContext,
  173. /// The local program cache for the transaction batch.
  174. pub program_cache_for_tx_batch: &'a mut ProgramCacheForTxBatch,
  175. /// Runtime configurations used to provision the invocation environment.
  176. pub environment_config: EnvironmentConfig<'a>,
  177. /// The compute budget for the current invocation.
  178. compute_budget: SVMTransactionExecutionBudget,
  179. /// The compute cost for the current invocation.
  180. execution_cost: SVMTransactionExecutionCost,
  181. /// Instruction compute meter, for tracking compute units consumed against
  182. /// the designated compute budget during program execution.
  183. compute_meter: RefCell<u64>,
  184. log_collector: Option<Rc<RefCell<LogCollector>>>,
  185. /// Latest measurement not yet accumulated in [ExecuteDetailsTimings::execute_us]
  186. pub execute_time: Option<Measure>,
  187. pub timings: ExecuteDetailsTimings,
  188. pub syscall_context: Vec<Option<SyscallContext>>,
  189. /// Pairs of index in TX instruction trace and VM register trace
  190. register_traces: Vec<(usize, Vec<[u64; 12]>)>,
  191. }
  192. impl<'a> InvokeContext<'a> {
  193. #[allow(clippy::too_many_arguments)]
  194. pub fn new(
  195. transaction_context: &'a mut TransactionContext,
  196. program_cache_for_tx_batch: &'a mut ProgramCacheForTxBatch,
  197. environment_config: EnvironmentConfig<'a>,
  198. log_collector: Option<Rc<RefCell<LogCollector>>>,
  199. compute_budget: SVMTransactionExecutionBudget,
  200. execution_cost: SVMTransactionExecutionCost,
  201. ) -> Self {
  202. Self {
  203. transaction_context,
  204. program_cache_for_tx_batch,
  205. environment_config,
  206. log_collector,
  207. compute_budget,
  208. execution_cost,
  209. compute_meter: RefCell::new(compute_budget.compute_unit_limit),
  210. execute_time: None,
  211. timings: ExecuteDetailsTimings::default(),
  212. syscall_context: Vec::new(),
  213. register_traces: Vec::new(),
  214. }
  215. }
  216. /// Push a stack frame onto the invocation stack
  217. pub fn push(&mut self) -> Result<(), InstructionError> {
  218. let instruction_context = self
  219. .transaction_context
  220. .get_instruction_context_at_index_in_trace(
  221. self.transaction_context.get_instruction_trace_length(),
  222. )?;
  223. let program_id = instruction_context
  224. .get_program_key()
  225. .map_err(|_| InstructionError::UnsupportedProgramId)?;
  226. if self.transaction_context.get_instruction_stack_height() != 0 {
  227. let contains =
  228. (0..self.transaction_context.get_instruction_stack_height()).any(|level| {
  229. self.transaction_context
  230. .get_instruction_context_at_nesting_level(level)
  231. .and_then(|instruction_context| instruction_context.get_program_key())
  232. .map(|program_key| program_key == program_id)
  233. .unwrap_or(false)
  234. });
  235. let is_last = self
  236. .transaction_context
  237. .get_current_instruction_context()
  238. .and_then(|instruction_context| instruction_context.get_program_key())
  239. .map(|program_key| program_key == program_id)
  240. .unwrap_or(false);
  241. if contains && !is_last {
  242. // Reentrancy not allowed unless caller is calling itself
  243. return Err(InstructionError::ReentrancyNotAllowed);
  244. }
  245. }
  246. self.syscall_context.push(None);
  247. self.transaction_context.push()
  248. }
  249. /// Pop a stack frame from the invocation stack
  250. fn pop(&mut self) -> Result<(), InstructionError> {
  251. self.syscall_context.pop();
  252. self.transaction_context.pop()
  253. }
  254. /// Current height of the invocation stack, top level instructions are height
  255. /// `solana_instruction::TRANSACTION_LEVEL_STACK_HEIGHT`
  256. pub fn get_stack_height(&self) -> usize {
  257. self.transaction_context.get_instruction_stack_height()
  258. }
  259. /// Entrypoint for a cross-program invocation from a builtin program
  260. pub fn native_invoke(
  261. &mut self,
  262. instruction: Instruction,
  263. signers: &[Pubkey],
  264. ) -> Result<(), InstructionError> {
  265. self.prepare_next_instruction(instruction, signers)?;
  266. let mut compute_units_consumed = 0;
  267. self.process_instruction(&mut compute_units_consumed, &mut ExecuteTimings::default())?;
  268. Ok(())
  269. }
  270. /// Helper to prepare for process_instruction() when the instruction is not a top level one,
  271. /// and depends on `AccountMeta`s
  272. pub fn prepare_next_instruction(
  273. &mut self,
  274. instruction: Instruction,
  275. signers: &[Pubkey],
  276. ) -> Result<(), InstructionError> {
  277. // We reference accounts by an u8 index, so we have a total of 256 accounts.
  278. // This algorithm allocates the array on the stack for speed.
  279. // On AArch64 in release mode, this function only consumes 640 bytes of stack.
  280. let mut transaction_callee_map: Vec<u8> = vec![u8::MAX; MAX_ACCOUNTS_PER_TRANSACTION];
  281. let mut instruction_accounts: Vec<InstructionAccount> =
  282. Vec::with_capacity(instruction.accounts.len());
  283. // This code block is necessary to restrict the scope of the immutable borrow of
  284. // transaction context (the `instruction_context` variable). At the end of this
  285. // function, we must borrow it again as mutable.
  286. let program_account_index = {
  287. let instruction_context = self.transaction_context.get_current_instruction_context()?;
  288. debug_assert!(instruction.accounts.len() <= transaction_callee_map.len());
  289. for account_meta in instruction.accounts.iter() {
  290. let index_in_transaction = self
  291. .transaction_context
  292. .find_index_of_account(&account_meta.pubkey)
  293. .ok_or_else(|| {
  294. ic_msg!(
  295. self,
  296. "Instruction references an unknown account {}",
  297. account_meta.pubkey,
  298. );
  299. InstructionError::MissingAccount
  300. })?;
  301. debug_assert!((index_in_transaction as usize) < transaction_callee_map.len());
  302. let index_in_callee = transaction_callee_map
  303. .get_mut(index_in_transaction as usize)
  304. .unwrap();
  305. if (*index_in_callee as usize) < instruction_accounts.len() {
  306. let cloned_account = {
  307. let instruction_account = instruction_accounts
  308. .get_mut(*index_in_callee as usize)
  309. .ok_or(InstructionError::MissingAccount)?;
  310. instruction_account.set_is_signer(
  311. instruction_account.is_signer() || account_meta.is_signer,
  312. );
  313. instruction_account.set_is_writable(
  314. instruction_account.is_writable() || account_meta.is_writable,
  315. );
  316. *instruction_account
  317. };
  318. instruction_accounts.push(cloned_account);
  319. } else {
  320. *index_in_callee = instruction_accounts.len() as u8;
  321. instruction_accounts.push(InstructionAccount::new(
  322. index_in_transaction,
  323. account_meta.is_signer,
  324. account_meta.is_writable,
  325. ));
  326. }
  327. }
  328. for current_index in 0..instruction_accounts.len() {
  329. let instruction_account = instruction_accounts.get(current_index).unwrap();
  330. let index_in_callee = *transaction_callee_map
  331. .get(instruction_account.index_in_transaction as usize)
  332. .unwrap() as usize;
  333. if current_index != index_in_callee {
  334. let (is_signer, is_writable) = {
  335. let reference_account = instruction_accounts
  336. .get(index_in_callee)
  337. .ok_or(InstructionError::MissingAccount)?;
  338. (
  339. reference_account.is_signer(),
  340. reference_account.is_writable(),
  341. )
  342. };
  343. let current_account = instruction_accounts.get_mut(current_index).unwrap();
  344. current_account.set_is_signer(current_account.is_signer() || is_signer);
  345. current_account.set_is_writable(current_account.is_writable() || is_writable);
  346. // This account is repeated, so there is no need to check for permissions
  347. continue;
  348. }
  349. let index_in_caller = instruction_context.get_index_of_account_in_instruction(
  350. instruction_account.index_in_transaction,
  351. )?;
  352. // This unwrap is safe because instruction.accounts.len() == instruction_accounts.len()
  353. let account_key = &instruction.accounts.get(current_index).unwrap().pubkey;
  354. // get_index_of_account_in_instruction has already checked if the index is valid.
  355. let caller_instruction_account = instruction_context
  356. .instruction_accounts()
  357. .get(index_in_caller as usize)
  358. .unwrap();
  359. // Readonly in caller cannot become writable in callee
  360. if instruction_account.is_writable() && !caller_instruction_account.is_writable() {
  361. ic_msg!(self, "{}'s writable privilege escalated", account_key,);
  362. return Err(InstructionError::PrivilegeEscalation);
  363. }
  364. // To be signed in the callee,
  365. // it must be either signed in the caller or by the program
  366. if instruction_account.is_signer()
  367. && !(caller_instruction_account.is_signer() || signers.contains(account_key))
  368. {
  369. ic_msg!(self, "{}'s signer privilege escalated", account_key,);
  370. return Err(InstructionError::PrivilegeEscalation);
  371. }
  372. }
  373. // Find and validate executables / program accounts
  374. let callee_program_id = &instruction.program_id;
  375. let program_account_index_in_transaction = self
  376. .transaction_context
  377. .find_index_of_account(callee_program_id);
  378. let program_account_index_in_instruction = program_account_index_in_transaction
  379. .map(|index| instruction_context.get_index_of_account_in_instruction(index));
  380. // We first check if the account exists in the transaction, and then see if it is part
  381. // of the instruction.
  382. if program_account_index_in_instruction.is_none()
  383. || program_account_index_in_instruction.unwrap().is_err()
  384. {
  385. ic_msg!(self, "Unknown program {}", callee_program_id);
  386. return Err(InstructionError::MissingAccount);
  387. }
  388. // SAFETY: This unwrap is safe, because we checked the index in instruction in the
  389. // previous if-condition.
  390. program_account_index_in_transaction.unwrap()
  391. };
  392. self.transaction_context.configure_next_instruction(
  393. program_account_index,
  394. instruction_accounts,
  395. transaction_callee_map,
  396. instruction.data,
  397. )?;
  398. Ok(())
  399. }
  400. /// Helper to prepare for process_instruction()/process_precompile() when the instruction is
  401. /// a top level one
  402. pub fn prepare_next_top_level_instruction(
  403. &mut self,
  404. message: &impl SVMMessage,
  405. instruction: &SVMInstruction,
  406. program_account_index: IndexOfAccount,
  407. ) -> Result<(), InstructionError> {
  408. // We reference accounts by an u8 index, so we have a total of 256 accounts.
  409. // This algorithm allocates the array on the stack for speed.
  410. // On AArch64 in release mode, this function only consumes 464 bytes of stack (when it is
  411. // not inlined).
  412. let mut transaction_callee_map: Vec<u8> = vec![u8::MAX; MAX_ACCOUNTS_PER_TRANSACTION];
  413. debug_assert!(instruction.accounts.len() <= transaction_callee_map.len());
  414. let mut instruction_accounts: Vec<InstructionAccount> =
  415. Vec::with_capacity(instruction.accounts.len());
  416. for index_in_transaction in instruction.accounts.iter() {
  417. debug_assert!((*index_in_transaction as usize) < transaction_callee_map.len());
  418. let index_in_callee = transaction_callee_map
  419. .get_mut(*index_in_transaction as usize)
  420. .unwrap();
  421. if (*index_in_callee as usize) > instruction_accounts.len() {
  422. *index_in_callee = instruction_accounts.len() as u8;
  423. }
  424. let index_in_transaction = *index_in_transaction as usize;
  425. instruction_accounts.push(InstructionAccount::new(
  426. index_in_transaction as IndexOfAccount,
  427. message.is_signer(index_in_transaction),
  428. message.is_writable(index_in_transaction),
  429. ));
  430. }
  431. self.transaction_context.configure_next_instruction(
  432. program_account_index,
  433. instruction_accounts,
  434. transaction_callee_map,
  435. instruction.data.to_vec(),
  436. )?;
  437. Ok(())
  438. }
  439. /// Processes an instruction and returns how many compute units were used
  440. pub fn process_instruction(
  441. &mut self,
  442. compute_units_consumed: &mut u64,
  443. timings: &mut ExecuteTimings,
  444. ) -> Result<(), InstructionError> {
  445. *compute_units_consumed = 0;
  446. self.push()?;
  447. self.process_executable_chain(compute_units_consumed, timings)
  448. // MUST pop if and only if `push` succeeded, independent of `result`.
  449. // Thus, the `.and()` instead of an `.and_then()`.
  450. .and(self.pop())
  451. }
  452. /// Processes a precompile instruction
  453. pub fn process_precompile<'ix_data>(
  454. &mut self,
  455. program_id: &Pubkey,
  456. instruction_data: &[u8],
  457. message_instruction_datas_iter: impl Iterator<Item = &'ix_data [u8]>,
  458. ) -> Result<(), InstructionError> {
  459. self.push()?;
  460. let instruction_datas: Vec<_> = message_instruction_datas_iter.collect();
  461. self.environment_config
  462. .epoch_stake_callback
  463. .process_precompile(program_id, instruction_data, instruction_datas)
  464. .map_err(InstructionError::from)
  465. .and(self.pop())
  466. }
  467. /// Calls the instruction's program entrypoint method
  468. fn process_executable_chain(
  469. &mut self,
  470. compute_units_consumed: &mut u64,
  471. timings: &mut ExecuteTimings,
  472. ) -> Result<(), InstructionError> {
  473. let instruction_context = self.transaction_context.get_current_instruction_context()?;
  474. let process_executable_chain_time = Measure::start("process_executable_chain_time");
  475. let builtin_id = {
  476. let owner_id = instruction_context.get_program_owner()?;
  477. if native_loader::check_id(&owner_id) {
  478. *instruction_context.get_program_key()?
  479. } else if bpf_loader_deprecated::check_id(&owner_id)
  480. || bpf_loader::check_id(&owner_id)
  481. || bpf_loader_upgradeable::check_id(&owner_id)
  482. || loader_v4::check_id(&owner_id)
  483. {
  484. owner_id
  485. } else {
  486. return Err(InstructionError::UnsupportedProgramId);
  487. }
  488. };
  489. // The Murmur3 hash value (used by RBPF) of the string "entrypoint"
  490. const ENTRYPOINT_KEY: u32 = 0x71E3CF81;
  491. let entry = self
  492. .program_cache_for_tx_batch
  493. .find(&builtin_id)
  494. .ok_or(InstructionError::UnsupportedProgramId)?;
  495. let function = match &entry.program {
  496. ProgramCacheEntryType::Builtin(program) => program
  497. .get_function_registry()
  498. .lookup_by_key(ENTRYPOINT_KEY)
  499. .map(|(_name, function)| function),
  500. _ => None,
  501. }
  502. .ok_or(InstructionError::UnsupportedProgramId)?;
  503. let program_id = *instruction_context.get_program_key()?;
  504. self.transaction_context
  505. .set_return_data(program_id, Vec::new())?;
  506. let logger = self.get_log_collector();
  507. stable_log::program_invoke(&logger, &program_id, self.get_stack_height());
  508. let pre_remaining_units = self.get_remaining();
  509. // In program-runtime v2 we will create this VM instance only once per transaction.
  510. // `program_runtime_environment_v2.get_config()` will be used instead of `mock_config`.
  511. // For now, only built-ins are invoked from here, so the VM and its Config are irrelevant.
  512. let mock_config = Config::default();
  513. let empty_memory_mapping =
  514. MemoryMapping::new(Vec::new(), &mock_config, SBPFVersion::V0).unwrap();
  515. let mut vm = EbpfVm::new(
  516. self.environment_config
  517. .program_runtime_environments_for_execution
  518. .program_runtime_v2
  519. .clone(),
  520. SBPFVersion::V0,
  521. // Removes lifetime tracking
  522. unsafe { std::mem::transmute::<&mut InvokeContext, &mut InvokeContext>(self) },
  523. empty_memory_mapping,
  524. 0,
  525. );
  526. vm.invoke_function(function);
  527. let result = match vm.program_result {
  528. ProgramResult::Ok(_) => {
  529. stable_log::program_success(&logger, &program_id);
  530. Ok(())
  531. }
  532. ProgramResult::Err(ref err) => {
  533. if let EbpfError::SyscallError(syscall_error) = err {
  534. if let Some(instruction_err) = syscall_error.downcast_ref::<InstructionError>()
  535. {
  536. stable_log::program_failure(&logger, &program_id, instruction_err);
  537. Err(instruction_err.clone())
  538. } else {
  539. stable_log::program_failure(&logger, &program_id, syscall_error);
  540. Err(InstructionError::ProgramFailedToComplete)
  541. }
  542. } else {
  543. stable_log::program_failure(&logger, &program_id, err);
  544. Err(InstructionError::ProgramFailedToComplete)
  545. }
  546. }
  547. };
  548. let post_remaining_units = self.get_remaining();
  549. *compute_units_consumed = pre_remaining_units.saturating_sub(post_remaining_units);
  550. if builtin_id == program_id && result.is_ok() && *compute_units_consumed == 0 {
  551. return Err(InstructionError::BuiltinProgramsMustConsumeComputeUnits);
  552. }
  553. timings
  554. .execute_accessories
  555. .process_instructions
  556. .process_executable_chain_us += process_executable_chain_time.end_as_us();
  557. result
  558. }
  559. /// Get this invocation's LogCollector
  560. pub fn get_log_collector(&self) -> Option<Rc<RefCell<LogCollector>>> {
  561. self.log_collector.clone()
  562. }
  563. /// Consume compute units
  564. pub fn consume_checked(&self, amount: u64) -> Result<(), Box<dyn std::error::Error>> {
  565. let mut compute_meter = self.compute_meter.borrow_mut();
  566. let exceeded = *compute_meter < amount;
  567. *compute_meter = compute_meter.saturating_sub(amount);
  568. if exceeded {
  569. return Err(Box::new(InstructionError::ComputationalBudgetExceeded));
  570. }
  571. Ok(())
  572. }
  573. /// Set compute units
  574. ///
  575. /// Only use for tests and benchmarks
  576. pub fn mock_set_remaining(&self, remaining: u64) {
  577. *self.compute_meter.borrow_mut() = remaining;
  578. }
  579. /// Get this invocation's compute budget
  580. pub fn get_compute_budget(&self) -> &SVMTransactionExecutionBudget {
  581. &self.compute_budget
  582. }
  583. /// Get this invocation's compute budget
  584. pub fn get_execution_cost(&self) -> &SVMTransactionExecutionCost {
  585. &self.execution_cost
  586. }
  587. /// Get the current feature set.
  588. pub fn get_feature_set(&self) -> &SVMFeatureSet {
  589. self.environment_config.feature_set
  590. }
  591. pub fn get_program_runtime_environments_for_deployment(&self) -> &ProgramRuntimeEnvironments {
  592. self.environment_config
  593. .program_runtime_environments_for_deployment
  594. }
  595. pub fn is_stake_raise_minimum_delegation_to_1_sol_active(&self) -> bool {
  596. self.environment_config
  597. .feature_set
  598. .stake_raise_minimum_delegation_to_1_sol
  599. }
  600. pub fn is_deprecate_legacy_vote_ixs_active(&self) -> bool {
  601. self.environment_config
  602. .feature_set
  603. .deprecate_legacy_vote_ixs
  604. }
  605. /// Get cached sysvars
  606. pub fn get_sysvar_cache(&self) -> &SysvarCache {
  607. self.environment_config.sysvar_cache
  608. }
  609. /// Get cached epoch total stake.
  610. pub fn get_epoch_stake(&self) -> u64 {
  611. self.environment_config
  612. .epoch_stake_callback
  613. .get_epoch_stake()
  614. }
  615. /// Get cached stake for the epoch vote account.
  616. pub fn get_epoch_stake_for_vote_account(&self, pubkey: &'a Pubkey) -> u64 {
  617. self.environment_config
  618. .epoch_stake_callback
  619. .get_epoch_stake_for_vote_account(pubkey)
  620. }
  621. pub fn is_precompile(&self, pubkey: &Pubkey) -> bool {
  622. self.environment_config
  623. .epoch_stake_callback
  624. .is_precompile(pubkey)
  625. }
  626. // Should alignment be enforced during user pointer translation
  627. pub fn get_check_aligned(&self) -> bool {
  628. self.transaction_context
  629. .get_current_instruction_context()
  630. .and_then(|instruction_context| {
  631. let owner_id = instruction_context.get_program_owner();
  632. debug_assert!(owner_id.is_ok());
  633. owner_id
  634. })
  635. .map(|owner_key| owner_key != bpf_loader_deprecated::id())
  636. .unwrap_or(true)
  637. }
  638. // Set this instruction syscall context
  639. pub fn set_syscall_context(
  640. &mut self,
  641. syscall_context: SyscallContext,
  642. ) -> Result<(), InstructionError> {
  643. *self
  644. .syscall_context
  645. .last_mut()
  646. .ok_or(InstructionError::CallDepth)? = Some(syscall_context);
  647. Ok(())
  648. }
  649. // Get this instruction's SyscallContext
  650. pub fn get_syscall_context(&self) -> Result<&SyscallContext, InstructionError> {
  651. self.syscall_context
  652. .last()
  653. .and_then(std::option::Option::as_ref)
  654. .ok_or(InstructionError::CallDepth)
  655. }
  656. // Get this instruction's SyscallContext
  657. pub fn get_syscall_context_mut(&mut self) -> Result<&mut SyscallContext, InstructionError> {
  658. self.syscall_context
  659. .last_mut()
  660. .and_then(|syscall_context| syscall_context.as_mut())
  661. .ok_or(InstructionError::CallDepth)
  662. }
  663. /// Insert a VM register trace
  664. pub fn insert_register_trace(&mut self, register_trace: Vec<[u64; 12]>) {
  665. if register_trace.is_empty() {
  666. return;
  667. }
  668. let Ok(instruction_context) = self.transaction_context.get_current_instruction_context()
  669. else {
  670. return;
  671. };
  672. self.register_traces
  673. .push((instruction_context.get_index_in_trace(), register_trace));
  674. }
  675. /// Iterates over all VM register traces (including CPI)
  676. pub fn iterate_vm_traces(
  677. &self,
  678. callback: &dyn Fn(InstructionContext, &Executable, RegisterTrace),
  679. ) {
  680. for (index_in_trace, register_trace) in &self.register_traces {
  681. let Ok(instruction_context) = self
  682. .transaction_context
  683. .get_instruction_context_at_index_in_trace(*index_in_trace)
  684. else {
  685. continue;
  686. };
  687. let Ok(program_id) = instruction_context.get_program_key() else {
  688. continue;
  689. };
  690. let Some(entry) = self.program_cache_for_tx_batch.find(program_id) else {
  691. continue;
  692. };
  693. let ProgramCacheEntryType::Loaded(ref executable) = entry.program else {
  694. continue;
  695. };
  696. callback(instruction_context, executable, register_trace.as_slice());
  697. }
  698. }
  699. }
  700. #[macro_export]
  701. macro_rules! with_mock_invoke_context_with_feature_set {
  702. (
  703. $invoke_context:ident,
  704. $transaction_context:ident,
  705. $feature_set:ident,
  706. $transaction_accounts:expr $(,)?
  707. ) => {
  708. use {
  709. solana_svm_callback::InvokeContextCallback,
  710. solana_svm_log_collector::LogCollector,
  711. $crate::{
  712. __private::{Hash, ReadableAccount, Rent, TransactionContext},
  713. execution_budget::{SVMTransactionExecutionBudget, SVMTransactionExecutionCost},
  714. invoke_context::{EnvironmentConfig, InvokeContext},
  715. loaded_programs::{ProgramCacheForTxBatch, ProgramRuntimeEnvironments},
  716. sysvar_cache::SysvarCache,
  717. },
  718. };
  719. struct MockInvokeContextCallback {}
  720. impl InvokeContextCallback for MockInvokeContextCallback {}
  721. let compute_budget = SVMTransactionExecutionBudget::new_with_defaults(
  722. $feature_set.raise_cpi_nesting_limit_to_8,
  723. );
  724. let mut $transaction_context = TransactionContext::new(
  725. $transaction_accounts,
  726. Rent::default(),
  727. compute_budget.max_instruction_stack_depth,
  728. compute_budget.max_instruction_trace_length,
  729. );
  730. let mut sysvar_cache = SysvarCache::default();
  731. sysvar_cache.fill_missing_entries(|pubkey, callback| {
  732. for index in 0..$transaction_context.get_number_of_accounts() {
  733. if $transaction_context
  734. .get_key_of_account_at_index(index)
  735. .unwrap()
  736. == pubkey
  737. {
  738. callback(
  739. $transaction_context
  740. .accounts()
  741. .try_borrow(index)
  742. .unwrap()
  743. .data(),
  744. );
  745. }
  746. }
  747. });
  748. let program_runtime_environments = ProgramRuntimeEnvironments::default();
  749. let environment_config = EnvironmentConfig::new(
  750. Hash::default(),
  751. 0,
  752. &MockInvokeContextCallback {},
  753. $feature_set,
  754. &program_runtime_environments,
  755. &program_runtime_environments,
  756. &sysvar_cache,
  757. );
  758. let mut program_cache_for_tx_batch = ProgramCacheForTxBatch::default();
  759. let mut $invoke_context = InvokeContext::new(
  760. &mut $transaction_context,
  761. &mut program_cache_for_tx_batch,
  762. environment_config,
  763. Some(LogCollector::new_ref()),
  764. compute_budget,
  765. SVMTransactionExecutionCost::new_with_defaults(
  766. $feature_set.increase_cpi_account_info_limit,
  767. ),
  768. );
  769. };
  770. }
  771. #[macro_export]
  772. macro_rules! with_mock_invoke_context {
  773. (
  774. $invoke_context:ident,
  775. $transaction_context:ident,
  776. $transaction_accounts:expr $(,)?
  777. ) => {
  778. use $crate::with_mock_invoke_context_with_feature_set;
  779. let feature_set = &solana_svm_feature_set::SVMFeatureSet::default();
  780. with_mock_invoke_context_with_feature_set!(
  781. $invoke_context,
  782. $transaction_context,
  783. feature_set,
  784. $transaction_accounts
  785. )
  786. };
  787. }
  788. #[allow(clippy::too_many_arguments)]
  789. pub fn mock_process_instruction_with_feature_set<
  790. F: FnMut(&mut InvokeContext),
  791. G: FnMut(&mut InvokeContext),
  792. >(
  793. loader_id: &Pubkey,
  794. program_index: Option<IndexOfAccount>,
  795. instruction_data: &[u8],
  796. mut transaction_accounts: Vec<KeyedAccountSharedData>,
  797. instruction_account_metas: Vec<AccountMeta>,
  798. expected_result: Result<(), InstructionError>,
  799. builtin_function: BuiltinFunctionWithContext,
  800. mut pre_adjustments: F,
  801. mut post_adjustments: G,
  802. feature_set: &SVMFeatureSet,
  803. ) -> Vec<AccountSharedData> {
  804. let mut instruction_accounts: Vec<InstructionAccount> =
  805. Vec::with_capacity(instruction_account_metas.len());
  806. for account_meta in instruction_account_metas.iter() {
  807. let index_in_transaction = transaction_accounts
  808. .iter()
  809. .position(|(key, _account)| *key == account_meta.pubkey)
  810. .unwrap_or(transaction_accounts.len())
  811. as IndexOfAccount;
  812. instruction_accounts.push(InstructionAccount::new(
  813. index_in_transaction,
  814. account_meta.is_signer,
  815. account_meta.is_writable,
  816. ));
  817. }
  818. let program_index = if let Some(index) = program_index {
  819. index
  820. } else {
  821. let processor_account = AccountSharedData::new(0, 0, &native_loader::id());
  822. transaction_accounts.push((*loader_id, processor_account));
  823. transaction_accounts.len().saturating_sub(1) as IndexOfAccount
  824. };
  825. let pop_epoch_schedule_account = if !transaction_accounts
  826. .iter()
  827. .any(|(key, _)| *key == sysvar::epoch_schedule::id())
  828. {
  829. transaction_accounts.push((
  830. sysvar::epoch_schedule::id(),
  831. create_account_shared_data_for_test(&EpochSchedule::default()),
  832. ));
  833. true
  834. } else {
  835. false
  836. };
  837. with_mock_invoke_context_with_feature_set!(
  838. invoke_context,
  839. transaction_context,
  840. feature_set,
  841. transaction_accounts
  842. );
  843. let mut program_cache_for_tx_batch = ProgramCacheForTxBatch::default();
  844. program_cache_for_tx_batch.replenish(
  845. *loader_id,
  846. Arc::new(ProgramCacheEntry::new_builtin(0, 0, builtin_function)),
  847. );
  848. program_cache_for_tx_batch.set_slot_for_tests(
  849. invoke_context
  850. .get_sysvar_cache()
  851. .get_clock()
  852. .map(|clock| clock.slot)
  853. .unwrap_or(1),
  854. );
  855. invoke_context.program_cache_for_tx_batch = &mut program_cache_for_tx_batch;
  856. pre_adjustments(&mut invoke_context);
  857. invoke_context
  858. .transaction_context
  859. .configure_next_instruction_for_tests(
  860. program_index,
  861. instruction_accounts,
  862. instruction_data.to_vec(),
  863. )
  864. .unwrap();
  865. let result = invoke_context.process_instruction(&mut 0, &mut ExecuteTimings::default());
  866. assert_eq!(result, expected_result);
  867. post_adjustments(&mut invoke_context);
  868. let mut transaction_accounts = transaction_context.deconstruct_without_keys().unwrap();
  869. if pop_epoch_schedule_account {
  870. transaction_accounts.pop();
  871. }
  872. transaction_accounts.pop();
  873. transaction_accounts
  874. }
  875. pub fn mock_process_instruction<F: FnMut(&mut InvokeContext), G: FnMut(&mut InvokeContext)>(
  876. loader_id: &Pubkey,
  877. program_index: Option<IndexOfAccount>,
  878. instruction_data: &[u8],
  879. transaction_accounts: Vec<KeyedAccountSharedData>,
  880. instruction_account_metas: Vec<AccountMeta>,
  881. expected_result: Result<(), InstructionError>,
  882. builtin_function: BuiltinFunctionWithContext,
  883. pre_adjustments: F,
  884. post_adjustments: G,
  885. ) -> Vec<AccountSharedData> {
  886. mock_process_instruction_with_feature_set(
  887. loader_id,
  888. program_index,
  889. instruction_data,
  890. transaction_accounts,
  891. instruction_account_metas,
  892. expected_result,
  893. builtin_function,
  894. pre_adjustments,
  895. post_adjustments,
  896. &SVMFeatureSet::all_enabled(),
  897. )
  898. }
  899. #[cfg(test)]
  900. mod tests {
  901. use {
  902. super::*,
  903. crate::execution_budget::DEFAULT_INSTRUCTION_COMPUTE_UNIT_LIMIT,
  904. serde::{Deserialize, Serialize},
  905. solana_account::WritableAccount,
  906. solana_instruction::Instruction,
  907. solana_keypair::Keypair,
  908. solana_rent::Rent,
  909. solana_signer::Signer,
  910. solana_transaction::{sanitized::SanitizedTransaction, Transaction},
  911. solana_transaction_context::MAX_ACCOUNTS_PER_INSTRUCTION,
  912. std::collections::HashSet,
  913. test_case::test_case,
  914. };
  915. #[derive(Debug, Serialize, Deserialize)]
  916. enum MockInstruction {
  917. NoopSuccess,
  918. NoopFail,
  919. ModifyOwned,
  920. ModifyNotOwned,
  921. ModifyReadonly,
  922. UnbalancedPush,
  923. UnbalancedPop,
  924. ConsumeComputeUnits {
  925. compute_units_to_consume: u64,
  926. desired_result: Result<(), InstructionError>,
  927. },
  928. Resize {
  929. new_len: u64,
  930. },
  931. }
  932. const MOCK_BUILTIN_COMPUTE_UNIT_COST: u64 = 1;
  933. declare_process_instruction!(
  934. MockBuiltin,
  935. MOCK_BUILTIN_COMPUTE_UNIT_COST,
  936. |invoke_context| {
  937. let transaction_context = &invoke_context.transaction_context;
  938. let instruction_context = transaction_context.get_current_instruction_context()?;
  939. let instruction_data = instruction_context.get_instruction_data();
  940. let program_id = instruction_context.get_program_key()?;
  941. let instruction_accounts = (0..4)
  942. .map(|instruction_account_index| {
  943. InstructionAccount::new(instruction_account_index, false, false)
  944. })
  945. .collect::<Vec<_>>();
  946. assert_eq!(
  947. program_id,
  948. instruction_context
  949. .try_borrow_instruction_account(0)?
  950. .get_owner()
  951. );
  952. assert_ne!(
  953. instruction_context
  954. .try_borrow_instruction_account(1)?
  955. .get_owner(),
  956. instruction_context.get_key_of_instruction_account(0)?
  957. );
  958. if let Ok(instruction) = bincode::deserialize(instruction_data) {
  959. match instruction {
  960. MockInstruction::NoopSuccess => (),
  961. MockInstruction::NoopFail => return Err(InstructionError::GenericError),
  962. MockInstruction::ModifyOwned => instruction_context
  963. .try_borrow_instruction_account(0)?
  964. .set_data_from_slice(&[1])?,
  965. MockInstruction::ModifyNotOwned => instruction_context
  966. .try_borrow_instruction_account(1)?
  967. .set_data_from_slice(&[1])?,
  968. MockInstruction::ModifyReadonly => instruction_context
  969. .try_borrow_instruction_account(2)?
  970. .set_data_from_slice(&[1])?,
  971. MockInstruction::UnbalancedPush => {
  972. instruction_context
  973. .try_borrow_instruction_account(0)?
  974. .checked_add_lamports(1)?;
  975. let program_id = *transaction_context.get_key_of_account_at_index(3)?;
  976. let metas = vec![
  977. AccountMeta::new_readonly(
  978. *transaction_context.get_key_of_account_at_index(0)?,
  979. false,
  980. ),
  981. AccountMeta::new_readonly(
  982. *transaction_context.get_key_of_account_at_index(1)?,
  983. false,
  984. ),
  985. ];
  986. let inner_instruction = Instruction::new_with_bincode(
  987. program_id,
  988. &MockInstruction::NoopSuccess,
  989. metas,
  990. );
  991. invoke_context
  992. .transaction_context
  993. .configure_next_instruction_for_tests(3, instruction_accounts, vec![])
  994. .unwrap();
  995. let result = invoke_context.push();
  996. assert_eq!(result, Err(InstructionError::UnbalancedInstruction));
  997. result?;
  998. invoke_context
  999. .native_invoke(inner_instruction, &[])
  1000. .and(invoke_context.pop())?;
  1001. }
  1002. MockInstruction::UnbalancedPop => instruction_context
  1003. .try_borrow_instruction_account(0)?
  1004. .checked_add_lamports(1)?,
  1005. MockInstruction::ConsumeComputeUnits {
  1006. compute_units_to_consume,
  1007. desired_result,
  1008. } => {
  1009. invoke_context
  1010. .consume_checked(compute_units_to_consume)
  1011. .map_err(|_| InstructionError::ComputationalBudgetExceeded)?;
  1012. return desired_result;
  1013. }
  1014. MockInstruction::Resize { new_len } => instruction_context
  1015. .try_borrow_instruction_account(0)?
  1016. .set_data_from_slice(&vec![0; new_len as usize])?,
  1017. }
  1018. } else {
  1019. return Err(InstructionError::InvalidInstructionData);
  1020. }
  1021. Ok(())
  1022. }
  1023. );
  1024. #[test_case(false; "SIMD-0268 disabled")]
  1025. #[test_case(true; "SIMD-0268 enabled")]
  1026. fn test_instruction_stack_height(simd_0268_active: bool) {
  1027. let one_more_than_max_depth =
  1028. SVMTransactionExecutionBudget::new_with_defaults(simd_0268_active)
  1029. .max_instruction_stack_depth
  1030. .saturating_add(1);
  1031. let mut invoke_stack = vec![];
  1032. let mut transaction_accounts = vec![];
  1033. let mut instruction_accounts = vec![];
  1034. for index in 0..one_more_than_max_depth {
  1035. invoke_stack.push(solana_pubkey::new_rand());
  1036. transaction_accounts.push((
  1037. solana_pubkey::new_rand(),
  1038. AccountSharedData::new(index as u64, 1, invoke_stack.get(index).unwrap()),
  1039. ));
  1040. instruction_accounts.push(InstructionAccount::new(
  1041. index as IndexOfAccount,
  1042. false,
  1043. true,
  1044. ));
  1045. }
  1046. for (index, program_id) in invoke_stack.iter().enumerate() {
  1047. transaction_accounts.push((
  1048. *program_id,
  1049. AccountSharedData::new(1, 1, &solana_pubkey::Pubkey::default()),
  1050. ));
  1051. instruction_accounts.push(InstructionAccount::new(
  1052. index as IndexOfAccount,
  1053. false,
  1054. false,
  1055. ));
  1056. }
  1057. with_mock_invoke_context!(invoke_context, transaction_context, transaction_accounts);
  1058. // Check call depth increases and has a limit
  1059. let mut depth_reached: usize = 0;
  1060. for _ in 0..invoke_stack.len() {
  1061. invoke_context
  1062. .transaction_context
  1063. .configure_next_instruction_for_tests(
  1064. one_more_than_max_depth.saturating_add(depth_reached) as IndexOfAccount,
  1065. instruction_accounts.clone(),
  1066. vec![],
  1067. )
  1068. .unwrap();
  1069. if Err(InstructionError::CallDepth) == invoke_context.push() {
  1070. break;
  1071. }
  1072. depth_reached = depth_reached.saturating_add(1);
  1073. }
  1074. assert_ne!(depth_reached, 0);
  1075. assert!(depth_reached < one_more_than_max_depth);
  1076. }
  1077. #[test]
  1078. fn test_max_instruction_trace_length() {
  1079. const MAX_INSTRUCTIONS: usize = 8;
  1080. let mut transaction_context = TransactionContext::new(
  1081. vec![(
  1082. Pubkey::new_unique(),
  1083. AccountSharedData::new(1, 1, &Pubkey::new_unique()),
  1084. )],
  1085. Rent::default(),
  1086. 1,
  1087. MAX_INSTRUCTIONS,
  1088. );
  1089. for _ in 0..MAX_INSTRUCTIONS {
  1090. transaction_context.push().unwrap();
  1091. transaction_context
  1092. .configure_next_instruction_for_tests(
  1093. 0,
  1094. vec![InstructionAccount::new(0, false, false)],
  1095. vec![],
  1096. )
  1097. .unwrap();
  1098. transaction_context.pop().unwrap();
  1099. }
  1100. assert_eq!(
  1101. transaction_context.push(),
  1102. Err(InstructionError::MaxInstructionTraceLengthExceeded)
  1103. );
  1104. }
  1105. #[test_case(MockInstruction::NoopSuccess, Ok(()); "NoopSuccess")]
  1106. #[test_case(MockInstruction::NoopFail, Err(InstructionError::GenericError); "NoopFail")]
  1107. #[test_case(MockInstruction::ModifyOwned, Ok(()); "ModifyOwned")]
  1108. #[test_case(MockInstruction::ModifyNotOwned, Err(InstructionError::ExternalAccountDataModified); "ModifyNotOwned")]
  1109. #[test_case(MockInstruction::ModifyReadonly, Err(InstructionError::ReadonlyDataModified); "ModifyReadonly")]
  1110. #[test_case(MockInstruction::UnbalancedPush, Err(InstructionError::UnbalancedInstruction); "UnbalancedPush")]
  1111. #[test_case(MockInstruction::UnbalancedPop, Err(InstructionError::UnbalancedInstruction); "UnbalancedPop")]
  1112. fn test_process_instruction_account_modifications(
  1113. instruction: MockInstruction,
  1114. expected_result: Result<(), InstructionError>,
  1115. ) {
  1116. let callee_program_id = solana_pubkey::new_rand();
  1117. let owned_account = AccountSharedData::new(42, 1, &callee_program_id);
  1118. let not_owned_account = AccountSharedData::new(84, 1, &solana_pubkey::new_rand());
  1119. let readonly_account = AccountSharedData::new(168, 1, &solana_pubkey::new_rand());
  1120. let loader_account = AccountSharedData::new(0, 1, &native_loader::id());
  1121. let mut program_account = AccountSharedData::new(1, 1, &native_loader::id());
  1122. program_account.set_executable(true);
  1123. let transaction_accounts = vec![
  1124. (solana_pubkey::new_rand(), owned_account),
  1125. (solana_pubkey::new_rand(), not_owned_account),
  1126. (solana_pubkey::new_rand(), readonly_account),
  1127. (callee_program_id, program_account),
  1128. (solana_pubkey::new_rand(), loader_account),
  1129. ];
  1130. let metas = vec![
  1131. AccountMeta::new(transaction_accounts.first().unwrap().0, false),
  1132. AccountMeta::new(transaction_accounts.get(1).unwrap().0, false),
  1133. AccountMeta::new_readonly(transaction_accounts.get(2).unwrap().0, false),
  1134. ];
  1135. let instruction_accounts = (0..4)
  1136. .map(|instruction_account_index| {
  1137. InstructionAccount::new(
  1138. instruction_account_index,
  1139. false,
  1140. instruction_account_index < 2,
  1141. )
  1142. })
  1143. .collect::<Vec<_>>();
  1144. with_mock_invoke_context!(invoke_context, transaction_context, transaction_accounts);
  1145. let mut program_cache_for_tx_batch = ProgramCacheForTxBatch::default();
  1146. program_cache_for_tx_batch.replenish(
  1147. callee_program_id,
  1148. Arc::new(ProgramCacheEntry::new_builtin(0, 1, MockBuiltin::vm)),
  1149. );
  1150. invoke_context.program_cache_for_tx_batch = &mut program_cache_for_tx_batch;
  1151. // Account modification tests
  1152. invoke_context
  1153. .transaction_context
  1154. .configure_next_instruction_for_tests(4, instruction_accounts, vec![])
  1155. .unwrap();
  1156. invoke_context.push().unwrap();
  1157. let inner_instruction =
  1158. Instruction::new_with_bincode(callee_program_id, &instruction, metas.clone());
  1159. let result = invoke_context
  1160. .native_invoke(inner_instruction, &[])
  1161. .and(invoke_context.pop());
  1162. assert_eq!(result, expected_result);
  1163. }
  1164. #[test_case(Ok(()); "Ok")]
  1165. #[test_case(Err(InstructionError::GenericError); "GenericError")]
  1166. fn test_process_instruction_compute_unit_consumption(
  1167. expected_result: Result<(), InstructionError>,
  1168. ) {
  1169. let callee_program_id = solana_pubkey::new_rand();
  1170. let owned_account = AccountSharedData::new(42, 1, &callee_program_id);
  1171. let not_owned_account = AccountSharedData::new(84, 1, &solana_pubkey::new_rand());
  1172. let readonly_account = AccountSharedData::new(168, 1, &solana_pubkey::new_rand());
  1173. let loader_account = AccountSharedData::new(0, 1, &native_loader::id());
  1174. let mut program_account = AccountSharedData::new(1, 1, &native_loader::id());
  1175. program_account.set_executable(true);
  1176. let transaction_accounts = vec![
  1177. (solana_pubkey::new_rand(), owned_account),
  1178. (solana_pubkey::new_rand(), not_owned_account),
  1179. (solana_pubkey::new_rand(), readonly_account),
  1180. (callee_program_id, program_account),
  1181. (solana_pubkey::new_rand(), loader_account),
  1182. ];
  1183. let metas = vec![
  1184. AccountMeta::new(transaction_accounts.first().unwrap().0, false),
  1185. AccountMeta::new(transaction_accounts.get(1).unwrap().0, false),
  1186. AccountMeta::new_readonly(transaction_accounts.get(2).unwrap().0, false),
  1187. ];
  1188. let instruction_accounts = (0..4)
  1189. .map(|instruction_account_index| {
  1190. InstructionAccount::new(
  1191. instruction_account_index,
  1192. false,
  1193. instruction_account_index < 2,
  1194. )
  1195. })
  1196. .collect::<Vec<_>>();
  1197. with_mock_invoke_context!(invoke_context, transaction_context, transaction_accounts);
  1198. let mut program_cache_for_tx_batch = ProgramCacheForTxBatch::default();
  1199. program_cache_for_tx_batch.replenish(
  1200. callee_program_id,
  1201. Arc::new(ProgramCacheEntry::new_builtin(0, 1, MockBuiltin::vm)),
  1202. );
  1203. invoke_context.program_cache_for_tx_batch = &mut program_cache_for_tx_batch;
  1204. // Compute unit consumption tests
  1205. let compute_units_to_consume = 10;
  1206. invoke_context
  1207. .transaction_context
  1208. .configure_next_instruction_for_tests(4, instruction_accounts, vec![])
  1209. .unwrap();
  1210. invoke_context.push().unwrap();
  1211. let inner_instruction = Instruction::new_with_bincode(
  1212. callee_program_id,
  1213. &MockInstruction::ConsumeComputeUnits {
  1214. compute_units_to_consume,
  1215. desired_result: expected_result.clone(),
  1216. },
  1217. metas.clone(),
  1218. );
  1219. invoke_context
  1220. .prepare_next_instruction(inner_instruction, &[])
  1221. .unwrap();
  1222. let mut compute_units_consumed = 0;
  1223. let result = invoke_context
  1224. .process_instruction(&mut compute_units_consumed, &mut ExecuteTimings::default());
  1225. // Because the instruction had compute cost > 0, then regardless of the execution result,
  1226. // the number of compute units consumed should be a non-default which is something greater
  1227. // than zero.
  1228. assert!(compute_units_consumed > 0);
  1229. assert_eq!(
  1230. compute_units_consumed,
  1231. compute_units_to_consume.saturating_add(MOCK_BUILTIN_COMPUTE_UNIT_COST),
  1232. );
  1233. assert_eq!(result, expected_result);
  1234. invoke_context.pop().unwrap();
  1235. }
  1236. #[test]
  1237. fn test_invoke_context_compute_budget() {
  1238. let transaction_accounts = vec![(solana_pubkey::new_rand(), AccountSharedData::default())];
  1239. let execution_budget = SVMTransactionExecutionBudget {
  1240. compute_unit_limit: u64::from(DEFAULT_INSTRUCTION_COMPUTE_UNIT_LIMIT),
  1241. ..SVMTransactionExecutionBudget::default()
  1242. };
  1243. with_mock_invoke_context!(invoke_context, transaction_context, transaction_accounts);
  1244. invoke_context.compute_budget = execution_budget;
  1245. invoke_context
  1246. .transaction_context
  1247. .configure_next_instruction_for_tests(0, vec![], vec![])
  1248. .unwrap();
  1249. invoke_context.push().unwrap();
  1250. assert_eq!(*invoke_context.get_compute_budget(), execution_budget);
  1251. invoke_context.pop().unwrap();
  1252. }
  1253. #[test_case(0; "Resize the account to *the same size*, so not consuming any additional size")]
  1254. #[test_case(1; "Resize the account larger")]
  1255. #[test_case(-1; "Resize the account smaller")]
  1256. fn test_process_instruction_accounts_resize_delta(resize_delta: i64) {
  1257. let program_key = Pubkey::new_unique();
  1258. let user_account_data_len = 123u64;
  1259. let user_account =
  1260. AccountSharedData::new(100, user_account_data_len as usize, &program_key);
  1261. let dummy_account = AccountSharedData::new(10, 0, &program_key);
  1262. let mut program_account = AccountSharedData::new(500, 500, &native_loader::id());
  1263. program_account.set_executable(true);
  1264. let transaction_accounts = vec![
  1265. (Pubkey::new_unique(), user_account),
  1266. (Pubkey::new_unique(), dummy_account),
  1267. (program_key, program_account),
  1268. ];
  1269. let instruction_accounts = vec![
  1270. InstructionAccount::new(0, false, true),
  1271. InstructionAccount::new(1, false, false),
  1272. ];
  1273. with_mock_invoke_context!(invoke_context, transaction_context, transaction_accounts);
  1274. let mut program_cache_for_tx_batch = ProgramCacheForTxBatch::default();
  1275. program_cache_for_tx_batch.replenish(
  1276. program_key,
  1277. Arc::new(ProgramCacheEntry::new_builtin(0, 0, MockBuiltin::vm)),
  1278. );
  1279. invoke_context.program_cache_for_tx_batch = &mut program_cache_for_tx_batch;
  1280. let new_len = (user_account_data_len as i64).saturating_add(resize_delta) as u64;
  1281. let instruction_data = bincode::serialize(&MockInstruction::Resize { new_len }).unwrap();
  1282. invoke_context
  1283. .transaction_context
  1284. .configure_next_instruction_for_tests(2, instruction_accounts, instruction_data)
  1285. .unwrap();
  1286. let result = invoke_context.process_instruction(&mut 0, &mut ExecuteTimings::default());
  1287. assert!(result.is_ok());
  1288. assert_eq!(
  1289. invoke_context.transaction_context.accounts().resize_delta(),
  1290. resize_delta
  1291. );
  1292. }
  1293. #[test]
  1294. fn test_prepare_instruction_maximum_accounts() {
  1295. let mut transaction_accounts: Vec<KeyedAccountSharedData> =
  1296. Vec::with_capacity(MAX_ACCOUNTS_PER_TRANSACTION);
  1297. let mut account_metas: Vec<AccountMeta> = Vec::with_capacity(MAX_ACCOUNTS_PER_INSTRUCTION);
  1298. // Fee-payer
  1299. let fee_payer = Keypair::new();
  1300. transaction_accounts.push((
  1301. fee_payer.pubkey(),
  1302. AccountSharedData::new(1, 1, &Pubkey::new_unique()),
  1303. ));
  1304. account_metas.push(AccountMeta::new(fee_payer.pubkey(), true));
  1305. let program_id = Pubkey::new_unique();
  1306. let mut program_account = AccountSharedData::new(1, 1, &Pubkey::new_unique());
  1307. program_account.set_executable(true);
  1308. transaction_accounts.push((program_id, program_account));
  1309. account_metas.push(AccountMeta::new_readonly(program_id, false));
  1310. for _ in 2..MAX_ACCOUNTS_PER_INSTRUCTION {
  1311. let key = Pubkey::new_unique();
  1312. transaction_accounts.push((key, AccountSharedData::new(1, 1, &Pubkey::new_unique())));
  1313. account_metas.push(AccountMeta::new_readonly(key, false));
  1314. }
  1315. with_mock_invoke_context!(invoke_context, transaction_context, transaction_accounts);
  1316. let instruction_1 = Instruction::new_with_bytes(program_id, &[20], account_metas.clone());
  1317. let instruction_2 = Instruction::new_with_bytes(
  1318. program_id,
  1319. &[20],
  1320. account_metas.iter().rev().cloned().collect(),
  1321. );
  1322. let transaction = Transaction::new_with_payer(
  1323. &[instruction_1.clone(), instruction_2.clone()],
  1324. Some(&fee_payer.pubkey()),
  1325. );
  1326. let sanitized =
  1327. SanitizedTransaction::try_from_legacy_transaction(transaction, &HashSet::new())
  1328. .unwrap();
  1329. fn test_case_1(invoke_context: &InvokeContext) {
  1330. let instruction_context = invoke_context
  1331. .transaction_context
  1332. .get_next_instruction_context()
  1333. .unwrap();
  1334. for index_in_transaction in 0..MAX_ACCOUNTS_PER_INSTRUCTION as IndexOfAccount {
  1335. let index_in_instruction = instruction_context
  1336. .get_index_of_account_in_instruction(index_in_transaction as IndexOfAccount)
  1337. .unwrap();
  1338. let other_transaction = instruction_context
  1339. .get_index_of_instruction_account_in_transaction(index_in_instruction)
  1340. .unwrap();
  1341. assert_eq!(index_in_transaction, other_transaction);
  1342. assert_eq!(index_in_transaction, index_in_instruction);
  1343. }
  1344. }
  1345. fn test_case_2(invoke_context: &InvokeContext) {
  1346. let instruction_context = invoke_context
  1347. .transaction_context
  1348. .get_next_instruction_context()
  1349. .unwrap();
  1350. for index_in_transaction in 0..MAX_ACCOUNTS_PER_INSTRUCTION as IndexOfAccount {
  1351. let index_in_instruction = instruction_context
  1352. .get_index_of_account_in_instruction(index_in_transaction as IndexOfAccount)
  1353. .unwrap();
  1354. let other_transaction = instruction_context
  1355. .get_index_of_instruction_account_in_transaction(index_in_instruction)
  1356. .unwrap();
  1357. assert_eq!(
  1358. index_in_instruction,
  1359. (MAX_ACCOUNTS_PER_INSTRUCTION as IndexOfAccount)
  1360. .saturating_sub(index_in_transaction)
  1361. .saturating_sub(1)
  1362. );
  1363. assert_eq!(index_in_transaction, other_transaction);
  1364. }
  1365. }
  1366. let svm_instruction =
  1367. SVMInstruction::from(sanitized.message().instructions().first().unwrap());
  1368. invoke_context
  1369. .prepare_next_top_level_instruction(&sanitized, &svm_instruction, 90)
  1370. .unwrap();
  1371. test_case_1(&invoke_context);
  1372. invoke_context.transaction_context.push().unwrap();
  1373. let svm_instruction =
  1374. SVMInstruction::from(sanitized.message().instructions().get(1).unwrap());
  1375. invoke_context
  1376. .prepare_next_top_level_instruction(&sanitized, &svm_instruction, 90)
  1377. .unwrap();
  1378. test_case_2(&invoke_context);
  1379. invoke_context.transaction_context.push().unwrap();
  1380. invoke_context
  1381. .prepare_next_instruction(instruction_1, &[fee_payer.pubkey()])
  1382. .unwrap();
  1383. test_case_1(&invoke_context);
  1384. invoke_context.transaction_context.push().unwrap();
  1385. invoke_context
  1386. .prepare_next_instruction(instruction_2, &[fee_payer.pubkey()])
  1387. .unwrap();
  1388. test_case_2(&invoke_context);
  1389. }
  1390. #[test]
  1391. fn test_duplicated_accounts() {
  1392. let mut transaction_accounts: Vec<KeyedAccountSharedData> =
  1393. Vec::with_capacity(MAX_ACCOUNTS_PER_TRANSACTION);
  1394. let mut account_metas: Vec<AccountMeta> =
  1395. Vec::with_capacity(MAX_ACCOUNTS_PER_INSTRUCTION.saturating_sub(1));
  1396. // Fee-payer
  1397. let fee_payer = Keypair::new();
  1398. transaction_accounts.push((
  1399. fee_payer.pubkey(),
  1400. AccountSharedData::new(1, 1, &Pubkey::new_unique()),
  1401. ));
  1402. account_metas.push(AccountMeta::new(fee_payer.pubkey(), true));
  1403. let program_id = Pubkey::new_unique();
  1404. let mut program_account = AccountSharedData::new(1, 1, &Pubkey::new_unique());
  1405. program_account.set_executable(true);
  1406. transaction_accounts.push((program_id, program_account));
  1407. account_metas.push(AccountMeta::new_readonly(program_id, false));
  1408. for i in 2..account_metas.capacity() {
  1409. if i % 2 == 0 {
  1410. let key = Pubkey::new_unique();
  1411. transaction_accounts
  1412. .push((key, AccountSharedData::new(1, 1, &Pubkey::new_unique())));
  1413. account_metas.push(AccountMeta::new_readonly(key, false));
  1414. } else {
  1415. let last_key = transaction_accounts.last().unwrap().0;
  1416. account_metas.push(AccountMeta::new_readonly(last_key, false));
  1417. }
  1418. }
  1419. with_mock_invoke_context!(invoke_context, transaction_context, transaction_accounts);
  1420. let instruction = Instruction::new_with_bytes(program_id, &[20], account_metas.clone());
  1421. let transaction = Transaction::new_with_payer(&[instruction], Some(&fee_payer.pubkey()));
  1422. let sanitized =
  1423. SanitizedTransaction::try_from_legacy_transaction(transaction, &HashSet::new())
  1424. .unwrap();
  1425. let svm_instruction =
  1426. SVMInstruction::from(sanitized.message().instructions().first().unwrap());
  1427. invoke_context
  1428. .prepare_next_top_level_instruction(&sanitized, &svm_instruction, 90)
  1429. .unwrap();
  1430. {
  1431. let instruction_context = invoke_context
  1432. .transaction_context
  1433. .get_next_instruction_context()
  1434. .unwrap();
  1435. for index_in_instruction in 2..account_metas.len() as IndexOfAccount {
  1436. let is_duplicate = instruction_context
  1437. .is_instruction_account_duplicate(index_in_instruction)
  1438. .unwrap();
  1439. if index_in_instruction % 2 == 0 {
  1440. assert!(is_duplicate.is_none());
  1441. } else {
  1442. assert_eq!(is_duplicate, Some(index_in_instruction.saturating_sub(1)));
  1443. }
  1444. }
  1445. }
  1446. invoke_context.transaction_context.push().unwrap();
  1447. let instruction = Instruction::new_with_bytes(
  1448. program_id,
  1449. &[20],
  1450. account_metas.iter().cloned().rev().collect(),
  1451. );
  1452. invoke_context
  1453. .prepare_next_instruction(instruction, &[fee_payer.pubkey()])
  1454. .unwrap();
  1455. let instruction_context = invoke_context
  1456. .transaction_context
  1457. .get_next_instruction_context()
  1458. .unwrap();
  1459. for index_in_instruction in 2..account_metas.len().saturating_sub(1) as u16 {
  1460. let is_duplicate = instruction_context
  1461. .is_instruction_account_duplicate(index_in_instruction)
  1462. .unwrap();
  1463. if index_in_instruction % 2 == 0 {
  1464. assert!(is_duplicate.is_none());
  1465. } else {
  1466. assert_eq!(is_duplicate, Some(index_in_instruction.saturating_sub(1)));
  1467. }
  1468. }
  1469. }
  1470. }