soroban_env_host/host/frame.rs
1use crate::{
2 auth::AuthorizationManagerSnapshot,
3 budget::AsBudget,
4 err,
5 host::{
6 metered_clone::{MeteredClone, MeteredContainer, MeteredIterator},
7 prng::Prng,
8 },
9 storage::{InstanceStorageMap, StorageMap},
10 xdr::{
11 ContractExecutable, ContractId, ContractIdPreimage, CreateContractArgsV2, Hash,
12 HostFunction, HostFunctionType, ScAddress, ScContractInstance, ScErrorCode, ScErrorType,
13 ScVal,
14 },
15 AddressObject, Error, ErrorHandler, Host, HostError, Object, Symbol, SymbolStr, TryFromVal,
16 TryIntoVal, Val, Vm, DEFAULT_HOST_DEPTH_LIMIT,
17};
18
19#[cfg(any(test, feature = "testutils"))]
20use core::cell::RefCell;
21use std::rc::Rc;
22
23/// Determines the re-entry mode for calling a contract.
24pub(crate) enum ContractReentryMode {
25 /// Re-entry is completely prohibited.
26 Prohibited,
27 /// Re-entry is allowed, but only directly into the same contract (i.e. it's
28 /// possible for a contract to do a self-call via host).
29 SelfAllowed,
30 /// Re-entry is fully allowed.
31 #[allow(dead_code)]
32 Allowed,
33}
34
35/// All the contract functions starting with double underscore are considered
36/// to be reserved by the Soroban host and can't be directly called by another
37/// contracts.
38const RESERVED_CONTRACT_FN_PREFIX: &str = "__";
39
40/// Saves host state (storage and objects) for rolling back a (sub-)transaction
41/// on error. A helper type used by [`FrameGuard`].
42// Notes on metering: `RollbackPoint` are metered under Frame operations
43// #[derive(Clone)]
44pub(super) struct RollbackPoint {
45 storage: StorageMap,
46 events: usize,
47 auth: AuthorizationManagerSnapshot,
48}
49
50#[cfg(any(test, feature = "testutils"))]
51pub trait ContractFunctionSet {
52 fn call(&self, func: &Symbol, host: &Host, args: &[Val]) -> Option<Val>;
53}
54
55#[cfg(any(test, feature = "testutils"))]
56#[derive(Debug, Clone)]
57pub(crate) struct TestContractFrame {
58 pub(crate) id: ContractId,
59 pub(crate) func: Symbol,
60 pub(crate) args: Vec<Val>,
61 pub(crate) panic: Rc<RefCell<Option<Error>>>,
62 pub(crate) instance: ScContractInstance,
63}
64
65#[cfg(any(test, feature = "testutils"))]
66impl std::hash::Hash for TestContractFrame {
67 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
68 self.id.hash(state);
69 self.func.hash(state);
70 self.args.hash(state);
71 if let Some(panic) = self.panic.borrow().as_ref() {
72 panic.hash(state);
73 }
74 self.instance.hash(state);
75 }
76}
77
78#[cfg(any(test, feature = "testutils"))]
79impl TestContractFrame {
80 pub fn new(id: ContractId, func: Symbol, args: Vec<Val>, instance: ScContractInstance) -> Self {
81 Self {
82 id,
83 func,
84 args,
85 panic: Rc::new(RefCell::new(None)),
86 instance,
87 }
88 }
89}
90
91/// Context pairs a variable-case [`Frame`] enum with state that's common to all
92/// cases (eg. a [`Prng`]).
93#[derive(Clone, Hash)]
94pub(crate) struct Context {
95 pub(crate) frame: Frame,
96 pub(crate) prng: Option<Prng>,
97 pub(crate) storage: Option<InstanceStorageMap>,
98}
99
100pub(crate) struct CallParams {
101 pub(crate) reentry_mode: ContractReentryMode,
102 pub(crate) internal_host_call: bool,
103 pub(crate) treat_missing_function_as_noop: bool,
104}
105
106impl CallParams {
107 pub(crate) fn default_external_call() -> Self {
108 Self {
109 reentry_mode: ContractReentryMode::Prohibited,
110 internal_host_call: false,
111 treat_missing_function_as_noop: false,
112 }
113 }
114
115 #[allow(unused)]
116 pub(crate) fn default_internal_call() -> Self {
117 Self {
118 reentry_mode: ContractReentryMode::Prohibited,
119 internal_host_call: true,
120 treat_missing_function_as_noop: false,
121 }
122 }
123}
124
125/// Holds contextual information about a single invocation, either
126/// a reference to a contract [`Vm`] or an enclosing [`HostFunction`]
127/// invocation.
128///
129/// Frames are arranged into a stack in [`HostImpl::context`], and are pushed
130/// with [`Host::push_frame`], which returns a [`FrameGuard`] that will
131/// pop the frame on scope-exit.
132///
133/// Frames are also the units of (sub-)transactions: each frame captures
134/// the host state when it is pushed, and the [`FrameGuard`] will either
135/// commit or roll back that state when it pops the stack.
136#[derive(Clone, Hash)]
137pub(crate) enum Frame {
138 ContractVM {
139 vm: Rc<Vm>,
140 fn_name: Symbol,
141 args: Vec<Val>,
142 instance: ScContractInstance,
143 relative_objects: Vec<Object>,
144 },
145 HostFunction(HostFunctionType),
146 StellarAssetContract(ContractId, Symbol, Vec<Val>, ScContractInstance),
147 #[cfg(any(test, feature = "testutils"))]
148 TestContract(TestContractFrame),
149}
150
151impl Frame {
152 fn contract_id(&self) -> Option<&ContractId> {
153 match self {
154 Frame::ContractVM { vm, .. } => Some(&vm.contract_id),
155 Frame::HostFunction(_) => None,
156 Frame::StellarAssetContract(id, ..) => Some(id),
157 #[cfg(any(test, feature = "testutils"))]
158 Frame::TestContract(tc) => Some(&tc.id),
159 }
160 }
161
162 fn instance(&self) -> Option<&ScContractInstance> {
163 match self {
164 Frame::ContractVM { instance, .. } => Some(instance),
165 Frame::HostFunction(_) => None,
166 Frame::StellarAssetContract(_, _, _, instance) => Some(instance),
167 #[cfg(any(test, feature = "testutils"))]
168 Frame::TestContract(tc) => Some(&tc.instance),
169 }
170 }
171 #[cfg(any(test, feature = "testutils"))]
172 fn is_contract_vm(&self) -> bool {
173 matches!(self, Frame::ContractVM { .. })
174 }
175}
176
177impl Host {
178 /// Returns if the host currently has a frame on the stack.
179 ///
180 /// A frame being on the stack usually indicates that a contract is currently
181 /// executing, or is in a state just-before or just-after executing.
182 pub fn has_frame(&self) -> Result<bool, HostError> {
183 self.with_current_frame_opt(|opt| Ok(opt.is_some()))
184 }
185
186 /// Helper function for [`Host::with_frame`] below. Pushes a new [`Context`]
187 /// on the context stack, returning a [`RollbackPoint`] such that if
188 /// operation fails, it can be used to roll the [`Host`] back to the state
189 /// it had before its associated [`Context`] was pushed.
190 pub(super) fn push_context(&self, ctx: Context) -> Result<RollbackPoint, HostError> {
191 let _span = tracy_span!("push context");
192 let auth_manager = self.try_borrow_authorization_manager()?;
193 let auth_snapshot = auth_manager.push_frame(self, &ctx.frame)?;
194 // Establish the rp first, since this might run out of gas and fail.
195 let rp = RollbackPoint {
196 storage: self.try_borrow_storage()?.map.metered_clone(self)?,
197 events: self.try_borrow_events()?.vec.len(),
198 auth: auth_snapshot,
199 };
200 // Charge for the push, which might also run out of gas.
201 Vec::<Context>::charge_bulk_init_cpy(1, self.as_budget())?;
202 // Finally commit to doing the push.
203 self.try_borrow_context_stack_mut()?.push(ctx);
204 Ok(rp)
205 }
206
207 /// Helper function for [`Host::with_frame`] below. Pops a [`Context`] off
208 /// the current context stack and optionally rolls back the [`Host`]'s objects
209 /// and storage map to the state in the provided [`RollbackPoint`].
210 pub(super) fn pop_context(&self, orp: Option<RollbackPoint>) -> Result<Context, HostError> {
211 let _span = tracy_span!("pop context");
212
213 let ctx = self.try_borrow_context_stack_mut()?.pop();
214
215 #[cfg(any(test, feature = "recording_mode"))]
216 if self.try_borrow_context_stack()?.is_empty() {
217 // When there are no contexts left, emulate authentication for the
218 // recording auth mode. This is a no-op for the enforcing mode.
219 self.try_borrow_authorization_manager()?
220 .maybe_emulate_authentication(self)?;
221 }
222 let mut auth_snapshot = None;
223 if let Some(rp) = orp {
224 self.try_borrow_storage_mut()?.map = rp.storage;
225 self.try_borrow_events_mut()?.rollback(rp.events)?;
226 auth_snapshot = Some(rp.auth);
227 }
228 self.try_borrow_authorization_manager()?
229 .pop_frame(self, auth_snapshot)?;
230 ctx.ok_or_else(|| {
231 self.err(
232 ScErrorType::Context,
233 ScErrorCode::InternalError,
234 "unmatched host context push/pop",
235 &[],
236 )
237 })
238 }
239
240 /// Applies a function to the top [`Frame`] of the context stack. Returns
241 /// [`HostError`] if the context stack is empty, otherwise returns result of
242 /// function call.
243 //
244 // Notes on metering: aquiring the current frame is cheap and not charged.
245 // Metering happens in the passed-in closure where actual work is being done.
246 pub(super) fn with_current_frame<F, U>(&self, f: F) -> Result<U, HostError>
247 where
248 F: FnOnce(&Frame) -> Result<U, HostError>,
249 {
250 let Ok(context_guard) = self.0.context_stack.try_borrow() else {
251 return Err(self.err(
252 ScErrorType::Context,
253 ScErrorCode::InternalError,
254 "context is already borrowed",
255 &[],
256 ));
257 };
258
259 if let Some(context) = context_guard.last() {
260 f(&context.frame)
261 } else {
262 drop(context_guard);
263 Err(self.err(
264 ScErrorType::Context,
265 ScErrorCode::InternalError,
266 "no contract running",
267 &[],
268 ))
269 }
270 }
271
272 /// Applies a function to a mutable reference to the top [`Context`] of the
273 /// context stack. Returns [`HostError`] if the context stack is empty,
274 /// otherwise returns result of function call.
275 //
276 // Notes on metering: aquiring the current frame is cheap and not charged.
277 // Metering happens in the passed-in closure where actual work is being done.
278 pub(super) fn with_current_context_mut<F, U>(&self, f: F) -> Result<U, HostError>
279 where
280 F: FnOnce(&mut Context) -> Result<U, HostError>,
281 {
282 let Ok(mut context_guard) = self.0.context_stack.try_borrow_mut() else {
283 return Err(self.err(
284 ScErrorType::Context,
285 ScErrorCode::InternalError,
286 "context is already borrowed",
287 &[],
288 ));
289 };
290 if let Some(context) = context_guard.last_mut() {
291 f(context)
292 } else {
293 drop(context_guard);
294 Err(self.err(
295 ScErrorType::Context,
296 ScErrorCode::InternalError,
297 "no contract running",
298 &[],
299 ))
300 }
301 }
302
303 /// Same as [`Self::with_current_frame`] but passes `None` when there is no current
304 /// frame, rather than failing with an error.
305 pub(crate) fn with_current_frame_opt<F, U>(&self, f: F) -> Result<U, HostError>
306 where
307 F: FnOnce(Option<&Frame>) -> Result<U, HostError>,
308 {
309 let Ok(context_guard) = self.0.context_stack.try_borrow() else {
310 return Err(self.err(
311 ScErrorType::Context,
312 ScErrorCode::InternalError,
313 "context is already borrowed",
314 &[],
315 ));
316 };
317 if let Some(context) = context_guard.last() {
318 f(Some(&context.frame))
319 } else {
320 drop(context_guard);
321 f(None)
322 }
323 }
324
325 pub(crate) fn with_current_frame_relative_object_table<F, U>(
326 &self,
327 f: F,
328 ) -> Result<U, HostError>
329 where
330 F: FnOnce(&mut Vec<Object>) -> Result<U, HostError>,
331 {
332 self.with_current_context_mut(|ctx| {
333 if let Frame::ContractVM {
334 relative_objects, ..
335 } = &mut ctx.frame
336 {
337 f(relative_objects)
338 } else {
339 Err(self.err(
340 ScErrorType::Context,
341 ScErrorCode::InternalError,
342 "accessing relative object table in non-VM frame",
343 &[],
344 ))
345 }
346 })
347 }
348
349 pub(crate) fn with_current_prng<F, U>(&self, f: F) -> Result<U, HostError>
350 where
351 F: FnOnce(&mut Prng) -> Result<U, HostError>,
352 {
353 // We mem::take the context's PRNG into a local variable and then put it
354 // back when we're done. This allows the callback to borrow the context
355 // to report errors if anything goes wrong in it. If the callback also
356 // installs a PRNG of its own (it shouldn't!) we notice when putting the
357 // context's PRNG back and fail with an internal error.
358 let curr_prng_opt =
359 self.with_current_context_mut(|ctx| Ok(std::mem::take(&mut ctx.prng)))?;
360
361 let mut curr_prng = match curr_prng_opt {
362 // There's already a context PRNG, so use it.
363 Some(prng) => prng,
364
365 // There's no context PRNG yet, seed one from the base PRNG (unless
366 // the base PRNG itself hasn't been seeded).
367 None => {
368 let mut base_guard = self.try_borrow_base_prng_mut()?;
369 if let Some(base) = base_guard.as_mut() {
370 base.sub_prng(self.as_budget())?
371 } else {
372 return Err(self.err(
373 ScErrorType::Context,
374 ScErrorCode::InternalError,
375 "host base PRNG was not seeded",
376 &[],
377 ));
378 }
379 }
380 };
381
382 // Call the callback with the new-or-existing context PRNG.
383 let res: Result<U, HostError> = f(&mut curr_prng);
384
385 // Put the (possibly newly-initialized frame PRNG-option back)
386 self.with_current_context_mut(|ctx| {
387 if ctx.prng.is_some() {
388 return Err(self.err(
389 ScErrorType::Context,
390 ScErrorCode::InternalError,
391 "callback re-entered with_current_prng",
392 &[],
393 ));
394 }
395 ctx.prng = Some(curr_prng);
396 Ok(())
397 })?;
398 res
399 }
400
401 /// Pushes a [`Frame`], runs a closure, and then pops the frame, rolling back
402 /// if the closure returned an error. Returns the result that the closure
403 /// returned (or any error caused during the frame push/pop).
404 pub(crate) fn with_frame<F>(&self, frame: Frame, f: F) -> Result<Val, HostError>
405 where
406 F: FnOnce() -> Result<Val, HostError>,
407 {
408 let start_depth = self.try_borrow_context_stack()?.len();
409 if start_depth as u32 >= DEFAULT_HOST_DEPTH_LIMIT {
410 return Err(Error::from_type_and_code(
411 ScErrorType::Context,
412 ScErrorCode::ExceededLimit,
413 )
414 .into());
415 }
416 #[cfg(any(test, feature = "testutils"))]
417 {
418 if let Some(ctx) = self.try_borrow_context_stack()?.last() {
419 if frame.is_contract_vm() && ctx.frame.is_contract_vm() {
420 if let Ok(mut scoreboard) = self.try_borrow_coverage_scoreboard_mut() {
421 scoreboard.vm_to_vm_calls += 1;
422 }
423 }
424 }
425 }
426 let ctx = Context {
427 frame,
428 prng: None,
429 storage: None,
430 };
431 let rp = self.push_context(ctx)?;
432 {
433 // We do this _after_ the context is pushed, in order to let the
434 // observation code assume a context exists
435 if let Some(ctx) = self.try_borrow_context_stack()?.last() {
436 self.call_any_lifecycle_hook(crate::host::TraceEvent::PushCtx(ctx))?;
437 }
438 }
439 #[cfg(any(test, feature = "testutils"))]
440 let mut is_top_contract_invocation = false;
441 #[cfg(any(test, feature = "testutils"))]
442 {
443 if self.try_borrow_context_stack()?.len() == 1 {
444 if let Some(ctx) = self.try_borrow_context_stack()?.first() {
445 match ctx.frame {
446 // Don't call the contract invocation hook for
447 // the host functions.
448 Frame::HostFunction(_) => (),
449 // Everything else is some sort of contract call.
450 _ => {
451 is_top_contract_invocation = true;
452 if let Some(contract_invocation_hook) =
453 self.try_borrow_top_contract_invocation_hook()?.as_ref()
454 {
455 contract_invocation_hook(
456 self,
457 crate::host::ContractInvocationEvent::Start,
458 );
459 }
460 }
461 }
462 }
463 }
464 }
465
466 let res = f();
467 let mut res = if let Ok(v) = res {
468 // If a contract function happens to have signature Result<...,
469 // Code> its Wasm ABI encoding will be ambiguous: if it exits with
470 // Err(Code) it'll wind up exiting the Wasm VM "successfully" with a
471 // Val that's of type Error, we'll get Ok(Error) here. To allow this
472 // to work and avoid losing errors, we define _any_ successful
473 // return of Ok(Error) as "a contract failure"; contracts aren't
474 // allowed to return Ok(Error) and have it considered actually-ok.
475 //
476 // (If we were called from try_call, it will actually turn this
477 // Err(ScErrorType::Contract) back into Ok(ScErrorType::Contract)
478 // since that is a "recoverable" type of error.)
479 if let Ok(err) = Error::try_from(v) {
480 // Unfortunately there are still two sub-cases to consider. One
481 // is when a contract returns Ok(Error) with
482 // ScErrorType::Contract, which is allowed and legitimate and
483 // "how a contract would signal a Result::Err(Code) as described
484 // above". In this (good) case we propagate the Error they
485 // provided, just switching it from Ok(Error) to Err(Error)
486 // indicating that the contract "failed" with this Error.
487 //
488 // The second (bad) case is when the contract returns Ok(Error)
489 // with a non-ScErrorType::Contract. This might be some kind of
490 // mistake on their part but it might also be an attempt at
491 // spoofing error reporting, by claiming some subsystem of the
492 // host failed when it really didn't. In particular if a
493 // contract wants to forcibly fail a caller that did `try_call`,
494 // the contract could spoof-return an unrecoverable Error code
495 // like InternalError or BudgetExceeded. We want to deny all
496 // such cases, so we just define them as illegal returns, and
497 // report them all as a specific error type of and description
498 // our own choosing: not a contract's own logic failing, but a
499 // contract failing to live up to a postcondition we're
500 // enforcing of "never returning this sort of error code".
501 if err.is_type(ScErrorType::Contract) {
502 Err(self.error(
503 err,
504 "escalating Ok(ScErrorType::Contract) frame-exit to Err",
505 &[],
506 ))
507 } else {
508 Err(self.err(
509 ScErrorType::Context,
510 ScErrorCode::InvalidAction,
511 "frame-exit with Ok(Error) carrying a non-ScErrorType::Contract Error",
512 &[err.to_val()],
513 ))
514 }
515 } else {
516 Ok(v)
517 }
518 } else {
519 res
520 };
521
522 // We try flushing instance storage at the end of the frame if nothing
523 // else failed. Unfortunately flushing instance storage is _itself_
524 // fallible in a variety of ways, and if it fails we want to roll back
525 // everything else.
526 if res.is_ok() {
527 if let Err(e) = self.persist_instance_storage() {
528 res = Err(e)
529 }
530 }
531 {
532 // We do this _before_ the context is popped, in order to let the
533 // observation code assume a context exists
534 if let Some(ctx) = self.try_borrow_context_stack()?.last() {
535 let res = match &res {
536 Ok(v) => Ok(*v),
537 Err(ref e) => Err(e),
538 };
539 self.call_any_lifecycle_hook(crate::host::TraceEvent::PopCtx(&ctx, &res))?;
540 }
541 }
542 if res.is_err() {
543 // Pop and rollback on error.
544 self.pop_context(Some(rp))?
545 } else {
546 // Just pop on success.
547 self.pop_context(None)?
548 };
549 // Every push and pop should be matched; if not there is a bug.
550 let end_depth = self.try_borrow_context_stack()?.len();
551 if start_depth != end_depth {
552 return Err(err!(
553 self,
554 (ScErrorType::Context, ScErrorCode::InternalError),
555 "frame-depth mismatch",
556 start_depth,
557 end_depth
558 ));
559 }
560 #[cfg(any(test, feature = "testutils"))]
561 if end_depth == 0 {
562 // Empty call stack in tests means that some contract function call
563 // has been finished and hence the authorization manager can be reset.
564 // In non-test scenarios, there should be no need to ever reset
565 // the authorization manager as the host instance shouldn't be
566 // shared between the contract invocations.
567 *self.try_borrow_previous_authorization_manager_mut()? =
568 Some(self.try_borrow_authorization_manager()?.clone());
569 self.try_borrow_authorization_manager_mut()?.reset();
570
571 // Call the contract invocation hook for contract invocations only.
572 if is_top_contract_invocation {
573 if let Some(top_contract_invocation_hook) =
574 self.try_borrow_top_contract_invocation_hook()?.as_ref()
575 {
576 top_contract_invocation_hook(
577 self,
578 crate::host::ContractInvocationEvent::Finish,
579 );
580 }
581 }
582 }
583 res
584 }
585
586 /// Inspects the frame at the top of the context and returns the contract ID
587 /// if it exists. Returns `Ok(None)` if the context stack is empty or has a
588 /// non-contract frame on top.
589 pub(crate) fn get_current_contract_id_opt_internal(
590 &self,
591 ) -> Result<Option<ContractId>, HostError> {
592 self.with_current_frame_opt(|opt_frame| match opt_frame {
593 Some(frame) => frame
594 .contract_id()
595 .map(|id| id.metered_clone(self))
596 .transpose(),
597 None => Ok(None),
598 })
599 }
600
601 /// Returns [`Hash`] contract ID from the VM frame at the top of the context
602 /// stack, or a [`HostError`] if the context stack is empty or has a non-VM
603 /// frame at its top.
604 pub(crate) fn get_current_contract_id_internal(&self) -> Result<ContractId, HostError> {
605 if let Some(id) = self.get_current_contract_id_opt_internal()? {
606 Ok(id)
607 } else {
608 // This should only ever happen if we try to access the contract ID
609 // from a HostFunction frame (meaning before a contract is running).
610 // Doing so is a logic bug on our part. If we simply run out of
611 // budget while cloning the Hash we won't get here, the `?` above
612 // will propagate the budget error.
613 Err(self.err(
614 ScErrorType::Context,
615 ScErrorCode::InternalError,
616 "Current context has no contract ID",
617 &[],
618 ))
619 }
620 }
621
622 /// Pushes a test contract [`Frame`], runs a closure, and then pops the
623 /// frame, rolling back if the closure returned an error. Returns the result
624 /// that the closure returned (or any error caused during the frame
625 /// push/pop). Used for testing.
626 #[cfg(any(test, feature = "testutils"))]
627 pub fn with_test_contract_frame<F>(
628 &self,
629 id: ContractId,
630 func: Symbol,
631 f: F,
632 ) -> Result<Val, HostError>
633 where
634 F: FnOnce() -> Result<Val, HostError>,
635 {
636 let _invocation_meter_scope = self.maybe_meter_invocation(
637 crate::host::invocation_metering::MeteringInvocation::CreateContractEntryPoint,
638 );
639 self.with_frame(
640 Frame::TestContract(self.create_test_contract_frame(id, func, vec![])?),
641 f,
642 )
643 }
644
645 #[cfg(any(test, feature = "testutils"))]
646 fn create_test_contract_frame(
647 &self,
648 id: ContractId,
649 func: Symbol,
650 args: Vec<Val>,
651 ) -> Result<TestContractFrame, HostError> {
652 let instance_key = self.contract_instance_ledger_key(&id)?;
653 let instance = self.retrieve_contract_instance_from_storage(&instance_key)?;
654 Ok(TestContractFrame::new(id, func, args.to_vec(), instance))
655 }
656
657 // Notes on metering: this is covered by the called components.
658 fn call_contract_fn(
659 &self,
660 id: &ContractId,
661 func: &Symbol,
662 args: &[Val],
663 treat_missing_function_as_noop: bool,
664 ) -> Result<Val, HostError> {
665 // Create key for storage
666 let storage_key = self.contract_instance_ledger_key(id)?;
667 let instance = self.retrieve_contract_instance_from_storage(&storage_key)?;
668 Vec::<Val>::charge_bulk_init_cpy(args.len() as u64, self.as_budget())?;
669 let args_vec = args.to_vec();
670 match &instance.executable {
671 ContractExecutable::Wasm(wasm_hash) => {
672 let vm = self.instantiate_vm(id, wasm_hash)?;
673 let relative_objects = Vec::new();
674 self.with_frame(
675 Frame::ContractVM {
676 vm: Rc::clone(&vm),
677 fn_name: *func,
678 args: args_vec,
679 instance,
680 relative_objects,
681 },
682 || vm.invoke_function_raw(self, func, args, treat_missing_function_as_noop),
683 )
684 }
685 ContractExecutable::StellarAsset => self.with_frame(
686 Frame::StellarAssetContract(id.metered_clone(self)?, *func, args_vec, instance),
687 || {
688 use crate::builtin_contracts::{BuiltinContract, StellarAssetContract};
689 StellarAssetContract.call(func, self, args)
690 },
691 ),
692 }
693 }
694
695 fn instantiate_vm(&self, id: &ContractId, wasm_hash: &Hash) -> Result<Rc<Vm>, HostError> {
696 let contract_id = id.metered_clone(self)?;
697 if let Some(cache) = &*self.try_borrow_module_cache()? {
698 // Check that storage thinks the entry exists before
699 // checking the cache: this seems like overkill but it
700 // provides some future-proofing, see below.
701 let wasm_key = self.contract_code_ledger_key(wasm_hash)?;
702 if self.try_borrow_storage_mut()?.has(&wasm_key, self, None)? {
703 if let Some(parsed_module) = cache.get_module(wasm_hash)? {
704 return Vm::from_parsed_module_and_wasmi_linker(
705 self,
706 contract_id,
707 parsed_module,
708 &cache.wasmi_linker,
709 );
710 }
711 }
712 };
713
714 // We can get here a few ways:
715 //
716 // 1. We are in simulation so don't have a module cache.
717 //
718 // 2. We have a module cache, but it somehow doesn't have
719 // the module requested. This in turn has two
720 // sub-cases:
721 //
722 // - User invoked us with bad input, eg. calling a
723 // contract that wasn't provided in footprint/storage.
724 //
725 // - User uploaded the wasm in this ledger so we didn't
726 // cache it when starting the ledger (and couldn't add
727 // it: the module cache and the wasmi engine used to
728 // build modules are both locked and shared across
729 // threads during execution, we don't want to perturb
730 // it even if we could; uploads use a throwaway engine
731 // for validation purposes).
732 //
733 // 3. Even more pathological: the module cache was built,
734 // and contained the module, but someone _removed_ the
735 // wasm from storage after the the cache was built
736 // (this is not currently possible from guest code, but
737 // we do some future-proofing here in case it becomes
738 // possible). This is the case we handle above with the
739 // early check for storage.has(wasm_key) before
740 // checking the cache as well.
741 //
742 // In all these cases, we want to try accessing storage, and
743 // if it has the wasm, make a _throwaway_ module with its
744 // own engine. If it doesn't have the wasm, we want to fail
745 // with a storage error.
746
747 #[cfg(any(test, feature = "recording_mode"))]
748 // In recording mode:
749 // - We have no _real_ module cache.
750 // - We have a choice of whether simulate a cache-hit.
751 // - We will "simulate a hit" by doing a fresh parse but charging it
752 // to the shadow budget, not the real budget.
753 // - We _want_ to simulate a miss any time _would_ be a corresponding
754 // (charged-for) miss in enforcing mode, because otherwise we're
755 // under-charging and the tx we're simulating will fail in execution.
756 // - One case we know for sure will cause a miss: if the module
757 // literally isn't in the snapshot at all. This happens when someone
758 // uploads a contract and tries running it in the same ledger.
759 // - Other cases we're _not sure_: a module might be expired and evicted
760 // (thus removed from module cache) between simulation time and
761 // enforcement time.
762 // - But we can and do make an approximation here:
763 // - If the module is _expired_ we assume it's on its way to eviction
764 // soon and simulate a miss, risking overcharging.
765 // - If the module is _not expired_ we assume it'll be survive until
766 // execution, simulate a hit, and risk undercharging.
767 if self.in_storage_recording_mode()? {
768 if let Some((parsed_module, wasmi_linker)) =
769 self.budget_ref().with_observable_shadow_mode(|| {
770 use crate::vm::ParsedModule;
771 let wasm_key = self.contract_code_ledger_key(wasm_hash)?;
772 let is_key_live_in_snapshot = self
773 .try_borrow_storage_mut()?
774 .is_key_live_in_snapshot(self, &wasm_key)?;
775 if is_key_live_in_snapshot {
776 let (code, _costs) = self.retrieve_wasm_from_storage(&wasm_hash)?;
777 // Currently only v0 costs are used by the inter-ledger
778 // module cache. Note, that when key is not in the live
779 // snapshot, the inter-ledger cache won't be used
780 // either, so we'll end up in the "cache miss" case
781 // below and then correctly charge the instantiation
782 // costs in `Vm::new_with_cost_inputs`.
783 let costs_v0 = crate::vm::VersionedContractCodeCostInputs::V0 {
784 wasm_bytes: code.len(),
785 };
786 let parsed_module = ParsedModule::new_with_isolated_engine(
787 self,
788 code.as_slice(),
789 costs_v0,
790 )?;
791 let wasmi_linker = parsed_module.make_wasmi_linker(self)?;
792 Ok(Some((parsed_module, wasmi_linker)))
793 } else {
794 Ok(None)
795 }
796 })?
797 {
798 return Vm::from_parsed_module_and_wasmi_linker(
799 self,
800 contract_id,
801 parsed_module,
802 &wasmi_linker,
803 );
804 }
805 }
806
807 let (code, costs) = self.retrieve_wasm_from_storage(&wasm_hash)?;
808 Vm::new_with_cost_inputs(self, contract_id, code.as_slice(), costs)
809 }
810
811 pub(crate) fn get_contract_protocol_version(
812 &self,
813 contract_id: &ContractId,
814 ) -> Result<u32, HostError> {
815 #[cfg(any(test, feature = "testutils"))]
816 if self.is_test_contract_executable(contract_id)? {
817 return self.get_ledger_protocol_version();
818 }
819 let storage_key = self.contract_instance_ledger_key(contract_id)?;
820 let instance = self.retrieve_contract_instance_from_storage(&storage_key)?;
821 match &instance.executable {
822 ContractExecutable::Wasm(wasm_hash) => {
823 let vm = self.instantiate_vm(contract_id, wasm_hash)?;
824 Ok(vm.module.proto_version)
825 }
826 ContractExecutable::StellarAsset => self.get_ledger_protocol_version(),
827 }
828 }
829
830 // Notes on metering: this is covered by the called components.
831 pub(crate) fn call_n_internal(
832 &self,
833 id: &ContractId,
834 func: Symbol,
835 args: &[Val],
836 call_params: CallParams,
837 ) -> Result<Val, HostError> {
838 #[cfg(any(test, feature = "testutils"))]
839 let _invocation_meter_scope = self.maybe_meter_invocation(
840 crate::host::invocation_metering::MeteringInvocation::contract_invocation(
841 self, id, func,
842 ),
843 );
844 // Internal host calls may call some special functions that otherwise
845 // aren't allowed to be called.
846 if !call_params.internal_host_call
847 && SymbolStr::try_from_val(self, &func)?
848 .to_string()
849 .as_str()
850 .starts_with(RESERVED_CONTRACT_FN_PREFIX)
851 {
852 return Err(self.err(
853 ScErrorType::Context,
854 ScErrorCode::InvalidAction,
855 "can't invoke a reserved function directly",
856 &[func.to_val()],
857 ));
858 }
859
860 if !matches!(call_params.reentry_mode, ContractReentryMode::Allowed) {
861 let reentry_distance = self
862 .try_borrow_context_stack()?
863 .iter()
864 .rev()
865 .filter_map(|c| c.frame.contract_id())
866 .position(|caller| caller == id);
867
868 match (call_params.reentry_mode, reentry_distance) {
869 // Non-reentrant calls, or calls in Allowed mode,
870 // or immediate-reentry calls in SelfAllowed mode
871 // are all acceptable.
872 (_, None)
873 | (ContractReentryMode::Allowed, _)
874 | (ContractReentryMode::SelfAllowed, Some(0)) => (),
875
876 // But any non-immediate-reentry in SelfAllowed mode,
877 // or any reentry at all in Prohibited mode, are errors.
878 (ContractReentryMode::SelfAllowed, Some(_))
879 | (ContractReentryMode::Prohibited, Some(_)) => {
880 return Err(self.err(
881 ScErrorType::Context,
882 ScErrorCode::InvalidAction,
883 "Contract re-entry is not allowed",
884 &[],
885 ));
886 }
887 }
888 }
889
890 self.fn_call_diagnostics(id, &func, args);
891
892 // Try dispatching the contract to the compiled-in registred
893 // implmentation. Only the contracts with the special (empty) executable
894 // are dispatched in this way, so that it's possible to switch the
895 // compiled-in implementation back to Wasm via
896 // `update_current_contract_wasm`.
897 // "testutils" is not covered by budget metering.
898 #[cfg(any(test, feature = "testutils"))]
899 if self.is_test_contract_executable(id)? {
900 // This looks a little un-idiomatic, but this avoids maintaining a borrow of
901 // self.0.contracts. Implementing it as
902 //
903 // if let Some(cfs) = self.try_borrow_contracts()?.get(&id).cloned() { ... }
904 //
905 // maintains a borrow of self.0.contracts, which can cause borrow errors.
906 let cfs_option = self.try_borrow_contracts()?.get(&id).cloned();
907 if let Some(cfs) = cfs_option {
908 let frame = self.create_test_contract_frame(id.clone(), func, args.to_vec())?;
909 let panic = frame.panic.clone();
910 return self.with_frame(Frame::TestContract(frame), || {
911 use std::any::Any;
912 use std::panic::AssertUnwindSafe;
913 type PanicVal = Box<dyn Any + Send>;
914
915 // We're directly invoking a native rust contract here,
916 // which we allow only in local testing scenarios, and we
917 // want it to behave as close to the way it would behave if
918 // the contract were actually compiled to WASM and running
919 // in a VM.
920 //
921 // In particular: if the contract function panics, if it
922 // were WASM it would cause the VM to trap, so we do
923 // something "as similar as we can" in the native case here,
924 // catch the native panic and attempt to continue by
925 // translating the panic back to an error, so that
926 // `with_frame` will rollback the host to its pre-call state
927 // (as best it can) and propagate the error to its caller
928 // (which might be another contract doing try_call).
929 //
930 // This is somewhat best-effort, but it's compiled-out when
931 // building a host for production use, so we're willing to
932 // be a bit forgiving.
933 let closure = AssertUnwindSafe(move || cfs.call(&func, self, args));
934 let res: Result<Option<Val>, PanicVal> =
935 crate::testutils::call_with_suppressed_panic_hook(closure);
936 match res {
937 Ok(Some(val)) => {
938 self.fn_return_diagnostics(id, &func, &val);
939 Ok(val)
940 }
941 Ok(None) => {
942 if call_params.treat_missing_function_as_noop {
943 Ok(Val::VOID.into())
944 } else {
945 Err(self.err(
946 ScErrorType::Context,
947 ScErrorCode::MissingValue,
948 "calling unknown contract function",
949 &[func.to_val()],
950 ))
951 }
952 }
953 Err(panic_payload) => {
954 // Return an error indicating the contract function
955 // panicked.
956 //
957 // If it was a panic generated by a Env-upgraded
958 // HostError, it had its `Error` captured by
959 // `VmCallerEnv::escalate_error_to_panic`: fish the
960 // `Error` stored in the frame back out and
961 // propagate it.
962 //
963 // If it was a panic generated by user code calling
964 // panic!(...) we won't retrieve such a stored
965 // `Error`. Since we're trying to emulate
966 // what-the-VM-would-do here, and the VM traps with
967 // an unreachable error on contract panic, we
968 // generate same error (by converting a wasm
969 // trap-unreachable code). It's a little weird
970 // because we're not actually running a VM, but we
971 // prioritize emulation fidelity over honesty here.
972 let mut error: Error =
973 Error::from(wasmi::core::TrapCode::UnreachableCodeReached);
974
975 let mut recovered_error_from_panic_refcell = false;
976 if let Ok(panic) = panic.try_borrow() {
977 if let Some(err) = *panic {
978 recovered_error_from_panic_refcell = true;
979 error = err;
980 }
981 }
982
983 // If we didn't manage to recover a structured error
984 // code from the frame's refcell, and we're allowed
985 // to record dynamic strings (which happens when
986 // diagnostics are active), and we got a panic
987 // payload of a simple string, log that panic
988 // payload into the diagnostic event buffer. This
989 // code path will get hit when contracts do
990 // `panic!("some string")` in native testing mode.
991 if !recovered_error_from_panic_refcell {
992 self.with_debug_mode(|| {
993 if let Some(str) = panic_payload.downcast_ref::<&str>() {
994 let msg: String = format!(
995 "caught panic '{}' from contract function '{:?}'",
996 str, func
997 );
998 let _ = self.log_diagnostics(&msg, args);
999 } else if let Some(str) = panic_payload.downcast_ref::<String>()
1000 {
1001 let msg: String = format!(
1002 "caught panic '{}' from contract function '{:?}'",
1003 str, func
1004 );
1005 let _ = self.log_diagnostics(&msg, args);
1006 };
1007 Ok(())
1008 })
1009 }
1010 Err(self.error(error, "caught error from function", &[]))
1011 }
1012 }
1013 });
1014 }
1015 }
1016
1017 let res =
1018 self.call_contract_fn(id, &func, args, call_params.treat_missing_function_as_noop);
1019
1020 match &res {
1021 Ok(res) => self.fn_return_diagnostics(id, &func, res),
1022 Err(_err) => {}
1023 }
1024
1025 res
1026 }
1027
1028 // Notes on metering: covered by the called components.
1029 fn invoke_function_and_return_val(&self, hf: HostFunction) -> Result<Val, HostError> {
1030 let hf_type = hf.discriminant();
1031 let frame = Frame::HostFunction(hf_type);
1032 match hf {
1033 HostFunction::InvokeContract(invoke_args) => {
1034 self.with_frame(frame, || {
1035 // Metering: conversions to host objects are covered.
1036 let ScAddress::Contract(ref contract_id) = invoke_args.contract_address else {
1037 return Err(self.err(
1038 ScErrorType::Value,
1039 ScErrorCode::UnexpectedType,
1040 "invoked address doesn't belong to a contract",
1041 &[],
1042 ));
1043 };
1044 let function_name: Symbol = invoke_args.function_name.try_into_val(self)?;
1045 let args = self.scvals_to_val_vec(invoke_args.args.as_slice())?;
1046 self.call_n_internal(
1047 contract_id,
1048 function_name,
1049 args.as_slice(),
1050 CallParams::default_external_call(),
1051 )
1052 })
1053 }
1054 HostFunction::CreateContract(args) => self.with_frame(frame, || {
1055 let deployer: Option<AddressObject> = match &args.contract_id_preimage {
1056 ContractIdPreimage::Address(preimage_from_addr) => {
1057 Some(self.add_host_object(preimage_from_addr.address.metered_clone(self)?)?)
1058 }
1059 ContractIdPreimage::Asset(_) => None,
1060 };
1061 self.create_contract_internal(
1062 deployer,
1063 CreateContractArgsV2 {
1064 contract_id_preimage: args.contract_id_preimage,
1065 executable: args.executable,
1066 constructor_args: Default::default(),
1067 },
1068 vec![],
1069 )
1070 .map(<Val>::from)
1071 }),
1072 HostFunction::CreateContractV2(args) => self.with_frame(frame, || {
1073 let deployer: Option<AddressObject> = match &args.contract_id_preimage {
1074 ContractIdPreimage::Address(preimage_from_addr) => {
1075 Some(self.add_host_object(preimage_from_addr.address.metered_clone(self)?)?)
1076 }
1077 ContractIdPreimage::Asset(_) => None,
1078 };
1079 let arg_vals = self.scvals_to_val_vec(args.constructor_args.as_slice())?;
1080 self.create_contract_internal(deployer, args, arg_vals)
1081 .map(<Val>::from)
1082 }),
1083 HostFunction::UploadContractWasm(wasm) => self.with_frame(frame, || {
1084 self.upload_contract_wasm(wasm.to_vec()).map(<Val>::from)
1085 }),
1086 }
1087 }
1088
1089 // Notes on metering: covered by the called components.
1090 pub fn invoke_function(&self, hf: HostFunction) -> Result<ScVal, HostError> {
1091 #[cfg(any(test, feature = "testutils"))]
1092 let _invocation_meter_scope = self.maybe_meter_invocation(
1093 crate::host::invocation_metering::MeteringInvocation::from_host_function(&hf),
1094 );
1095
1096 let rv = self.invoke_function_and_return_val(hf)?;
1097 self.from_host_val(rv)
1098 }
1099
1100 pub(crate) fn maybe_init_instance_storage(&self, ctx: &mut Context) -> Result<(), HostError> {
1101 // Lazily initialize the storage on first access - it's not free and
1102 // not every contract will use it.
1103 if ctx.storage.is_some() {
1104 return Ok(());
1105 }
1106
1107 let Some(instance) = ctx.frame.instance() else {
1108 return Err(self.err(
1109 ScErrorType::Context,
1110 ScErrorCode::InternalError,
1111 "access to instance in frame without instance",
1112 &[],
1113 ));
1114 };
1115
1116 ctx.storage = Some(InstanceStorageMap::from_map(
1117 instance.storage.as_ref().map_or_else(
1118 || Ok(vec![]),
1119 |m| {
1120 m.iter()
1121 .map(|i| {
1122 Ok((
1123 self.to_valid_host_val(&i.key)?,
1124 self.to_valid_host_val(&i.val)?,
1125 ))
1126 })
1127 .metered_collect::<Result<Vec<(Val, Val)>, HostError>>(self)?
1128 },
1129 )?,
1130 self,
1131 )?);
1132 Ok(())
1133 }
1134
1135 // Make the in-memory instance storage persist into the `Storage` by writing
1136 // its updated contents into corresponding `ContractData` ledger entry.
1137 fn persist_instance_storage(&self) -> Result<(), HostError> {
1138 let updated_instance_storage = self.with_current_context_mut(|ctx| {
1139 if let Some(storage) = &ctx.storage {
1140 if !storage.is_modified {
1141 return Ok(None);
1142 }
1143 Ok(Some(self.instance_storage_map_to_scmap(&storage.map)?))
1144 } else {
1145 Ok(None)
1146 }
1147 })?;
1148 if updated_instance_storage.is_some() {
1149 let contract_id = self.get_current_contract_id_internal()?;
1150 let key = self.contract_instance_ledger_key(&contract_id)?;
1151
1152 self.store_contract_instance(None, updated_instance_storage, contract_id, &key)?;
1153 }
1154 Ok(())
1155 }
1156}