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        self.with_frame(
638            Frame::TestContract(self.create_test_contract_frame(id, func, vec![])?),
639            f,
640        )
641    }
642
643    #[cfg(any(test, feature = "testutils"))]
644    fn create_test_contract_frame(
645        &self,
646        id: ContractId,
647        func: Symbol,
648        args: Vec<Val>,
649    ) -> Result<TestContractFrame, HostError> {
650        let instance_key = self.contract_instance_ledger_key(&id)?;
651        let instance = self.retrieve_contract_instance_from_storage(&instance_key)?;
652        Ok(TestContractFrame::new(id, func, args.to_vec(), instance))
653    }
654
655    // Notes on metering: this is covered by the called components.
656    fn call_contract_fn(
657        &self,
658        id: &ContractId,
659        func: &Symbol,
660        args: &[Val],
661        treat_missing_function_as_noop: bool,
662    ) -> Result<Val, HostError> {
663        // Create key for storage
664        let storage_key = self.contract_instance_ledger_key(id)?;
665        let instance = self.retrieve_contract_instance_from_storage(&storage_key)?;
666        Vec::<Val>::charge_bulk_init_cpy(args.len() as u64, self.as_budget())?;
667        let args_vec = args.to_vec();
668        match &instance.executable {
669            ContractExecutable::Wasm(wasm_hash) => {
670                let vm = self.instantiate_vm(id, wasm_hash)?;
671                let relative_objects = Vec::new();
672                self.with_frame(
673                    Frame::ContractVM {
674                        vm: Rc::clone(&vm),
675                        fn_name: *func,
676                        args: args_vec,
677                        instance,
678                        relative_objects,
679                    },
680                    || vm.invoke_function_raw(self, func, args, treat_missing_function_as_noop),
681                )
682            }
683            ContractExecutable::StellarAsset => self.with_frame(
684                Frame::StellarAssetContract(id.metered_clone(self)?, *func, args_vec, instance),
685                || {
686                    use crate::builtin_contracts::{BuiltinContract, StellarAssetContract};
687                    StellarAssetContract.call(func, self, args)
688                },
689            ),
690        }
691    }
692
693    fn instantiate_vm(&self, id: &ContractId, wasm_hash: &Hash) -> Result<Rc<Vm>, HostError> {
694        let contract_id = id.metered_clone(self)?;
695        if let Some(cache) = &*self.try_borrow_module_cache()? {
696            // Check that storage thinks the entry exists before
697            // checking the cache: this seems like overkill but it
698            // provides some future-proofing, see below.
699            let wasm_key = self.contract_code_ledger_key(wasm_hash)?;
700            if self.try_borrow_storage_mut()?.has(&wasm_key, self, None)? {
701                if let Some(parsed_module) = cache.get_module(wasm_hash)? {
702                    return Vm::from_parsed_module_and_wasmi_linker(
703                        self,
704                        contract_id,
705                        parsed_module,
706                        &cache.wasmi_linker,
707                    );
708                }
709            }
710        };
711
712        // We can get here a few ways:
713        //
714        //   1. We are in simulation so don't have a module cache.
715        //
716        //   2. We have a module cache, but it somehow doesn't have
717        //      the module requested. This in turn has two
718        //      sub-cases:
719        //
720        //     - User invoked us with bad input, eg. calling a
721        //       contract that wasn't provided in footprint/storage.
722        //
723        //     - User uploaded the wasm _in this transaction_ so we
724        //       didn't cache it when starting the transaction (and
725        //       couldn't add it: additions use a shared wasmi engine
726        //       that owns all the cache entries, and that engine is
727        //       locked while we're running; uploads use a throwaway
728        //       engine for validation purposes).
729        //
730        //   3. Even more pathological: the module cache was built,
731        //      and contained the module, but someone _removed_ the
732        //      wasm from storage after the the cache was built
733        //      (this is not currently possible from guest code, but
734        //      we do some future-proofing here in case it becomes
735        //      possible). This is the case we handle above with the
736        //      early check for storage.has(wasm_key) before
737        //      checking the cache as well.
738        //
739        // In all these cases, we want to try accessing storage, and
740        // if it has the wasm, make a _throwaway_ module with its
741        // own engine. If it doesn't have the wasm, we want to fail
742        // with a storage error.
743
744        #[cfg(any(test, feature = "recording_mode"))]
745        // In recording mode: if a contract was present in the initial snapshot image, it is part of
746        // the set of contracts that would have been built into a module cache in enforcing mode;
747        // we want to suppress the cost of parsing those (simulating them as module cache hits).
748        //
749        // If a contract is _not_ in the initial snapshot image, it's because someone just uploaded
750        // it during execution. Those would be cache misses in enforcing mode, and so it is right to
751        // continue to charge for them as such (charging the parse cost on each call) in recording.
752        if self.in_storage_recording_mode()? {
753            if let Some((parsed_module, wasmi_linker)) =
754                self.budget_ref().with_observable_shadow_mode(|| {
755                    use crate::vm::ParsedModule;
756                    let wasm_key = self.contract_code_ledger_key(wasm_hash)?;
757                    if self
758                        .try_borrow_storage()?
759                        .get_snapshot_value(self, &wasm_key)?
760                        .is_some()
761                    {
762                        let (code, costs) = self.retrieve_wasm_from_storage(&wasm_hash)?;
763                        let parsed_module =
764                            ParsedModule::new_with_isolated_engine(self, code.as_slice(), costs)?;
765                        let wasmi_linker = parsed_module.make_wasmi_linker(self)?;
766                        Ok(Some((parsed_module, wasmi_linker)))
767                    } else {
768                        Ok(None)
769                    }
770                })?
771            {
772                return Vm::from_parsed_module_and_wasmi_linker(
773                    self,
774                    contract_id,
775                    parsed_module,
776                    &wasmi_linker,
777                );
778            }
779        }
780
781        let (code, costs) = self.retrieve_wasm_from_storage(&wasm_hash)?;
782        Vm::new_with_cost_inputs(self, contract_id, code.as_slice(), costs)
783    }
784
785    pub(crate) fn get_contract_protocol_version(
786        &self,
787        contract_id: &ContractId,
788    ) -> Result<u32, HostError> {
789        #[cfg(any(test, feature = "testutils"))]
790        if self.is_test_contract_executable(contract_id)? {
791            return self.get_ledger_protocol_version();
792        }
793        let storage_key = self.contract_instance_ledger_key(contract_id)?;
794        let instance = self.retrieve_contract_instance_from_storage(&storage_key)?;
795        match &instance.executable {
796            ContractExecutable::Wasm(wasm_hash) => {
797                let vm = self.instantiate_vm(contract_id, wasm_hash)?;
798                Ok(vm.module.proto_version)
799            }
800            ContractExecutable::StellarAsset => self.get_ledger_protocol_version(),
801        }
802    }
803
804    // Notes on metering: this is covered by the called components.
805    pub(crate) fn call_n_internal(
806        &self,
807        id: &ContractId,
808        func: Symbol,
809        args: &[Val],
810        call_params: CallParams,
811    ) -> Result<Val, HostError> {
812        // Internal host calls may call some special functions that otherwise
813        // aren't allowed to be called.
814        if !call_params.internal_host_call
815            && SymbolStr::try_from_val(self, &func)?
816                .to_string()
817                .as_str()
818                .starts_with(RESERVED_CONTRACT_FN_PREFIX)
819        {
820            return Err(self.err(
821                ScErrorType::Context,
822                ScErrorCode::InvalidAction,
823                "can't invoke a reserved function directly",
824                &[func.to_val()],
825            ));
826        }
827
828        if !matches!(call_params.reentry_mode, ContractReentryMode::Allowed) {
829            let reentry_distance = self
830                .try_borrow_context_stack()?
831                .iter()
832                .rev()
833                .filter_map(|c| c.frame.contract_id())
834                .position(|caller| caller == id);
835
836            match (call_params.reentry_mode, reentry_distance) {
837                // Non-reentrant calls, or calls in Allowed mode,
838                // or immediate-reentry calls in SelfAllowed mode
839                // are all acceptable.
840                (_, None)
841                | (ContractReentryMode::Allowed, _)
842                | (ContractReentryMode::SelfAllowed, Some(0)) => (),
843
844                // But any non-immediate-reentry in SelfAllowed mode,
845                // or any reentry at all in Prohibited mode, are errors.
846                (ContractReentryMode::SelfAllowed, Some(_))
847                | (ContractReentryMode::Prohibited, Some(_)) => {
848                    return Err(self.err(
849                        ScErrorType::Context,
850                        ScErrorCode::InvalidAction,
851                        "Contract re-entry is not allowed",
852                        &[],
853                    ));
854                }
855            }
856        }
857
858        self.fn_call_diagnostics(id, &func, args);
859
860        // Try dispatching the contract to the compiled-in registred
861        // implmentation. Only the contracts with the special (empty) executable
862        // are dispatched in this way, so that it's possible to switch the
863        // compiled-in implementation back to Wasm via
864        // `update_current_contract_wasm`.
865        // "testutils" is not covered by budget metering.
866        #[cfg(any(test, feature = "testutils"))]
867        if self.is_test_contract_executable(id)? {
868            // This looks a little un-idiomatic, but this avoids maintaining a borrow of
869            // self.0.contracts. Implementing it as
870            //
871            //     if let Some(cfs) = self.try_borrow_contracts()?.get(&id).cloned() { ... }
872            //
873            // maintains a borrow of self.0.contracts, which can cause borrow errors.
874            let cfs_option = self.try_borrow_contracts()?.get(&id).cloned();
875            if let Some(cfs) = cfs_option {
876                let frame = self.create_test_contract_frame(id.clone(), func, args.to_vec())?;
877                let panic = frame.panic.clone();
878                return self.with_frame(Frame::TestContract(frame), || {
879                    use std::any::Any;
880                    use std::panic::AssertUnwindSafe;
881                    type PanicVal = Box<dyn Any + Send>;
882
883                    // We're directly invoking a native rust contract here,
884                    // which we allow only in local testing scenarios, and we
885                    // want it to behave as close to the way it would behave if
886                    // the contract were actually compiled to WASM and running
887                    // in a VM.
888                    //
889                    // In particular: if the contract function panics, if it
890                    // were WASM it would cause the VM to trap, so we do
891                    // something "as similar as we can" in the native case here,
892                    // catch the native panic and attempt to continue by
893                    // translating the panic back to an error, so that
894                    // `with_frame` will rollback the host to its pre-call state
895                    // (as best it can) and propagate the error to its caller
896                    // (which might be another contract doing try_call).
897                    //
898                    // This is somewhat best-effort, but it's compiled-out when
899                    // building a host for production use, so we're willing to
900                    // be a bit forgiving.
901                    let closure = AssertUnwindSafe(move || cfs.call(&func, self, args));
902                    let res: Result<Option<Val>, PanicVal> =
903                        crate::testutils::call_with_suppressed_panic_hook(closure);
904                    match res {
905                        Ok(Some(val)) => {
906                            self.fn_return_diagnostics(id, &func, &val);
907                            Ok(val)
908                        }
909                        Ok(None) => {
910                            if call_params.treat_missing_function_as_noop {
911                                Ok(Val::VOID.into())
912                            } else {
913                                Err(self.err(
914                                    ScErrorType::Context,
915                                    ScErrorCode::MissingValue,
916                                    "calling unknown contract function",
917                                    &[func.to_val()],
918                                ))
919                            }
920                        }
921                        Err(panic_payload) => {
922                            // Return an error indicating the contract function
923                            // panicked.
924                            //
925                            // If it was a panic generated by a Env-upgraded
926                            // HostError, it had its `Error` captured by
927                            // `VmCallerEnv::escalate_error_to_panic`: fish the
928                            // `Error` stored in the frame back out and
929                            // propagate it.
930                            //
931                            // If it was a panic generated by user code calling
932                            // panic!(...) we won't retrieve such a stored
933                            // `Error`. Since we're trying to emulate
934                            // what-the-VM-would-do here, and the VM traps with
935                            // an unreachable error on contract panic, we
936                            // generate same error (by converting a wasm
937                            // trap-unreachable code). It's a little weird
938                            // because we're not actually running a VM, but we
939                            // prioritize emulation fidelity over honesty here.
940                            let mut error: Error =
941                                Error::from(wasmi::core::TrapCode::UnreachableCodeReached);
942
943                            let mut recovered_error_from_panic_refcell = false;
944                            if let Ok(panic) = panic.try_borrow() {
945                                if let Some(err) = *panic {
946                                    recovered_error_from_panic_refcell = true;
947                                    error = err;
948                                }
949                            }
950
951                            // If we didn't manage to recover a structured error
952                            // code from the frame's refcell, and we're allowed
953                            // to record dynamic strings (which happens when
954                            // diagnostics are active), and we got a panic
955                            // payload of a simple string, log that panic
956                            // payload into the diagnostic event buffer. This
957                            // code path will get hit when contracts do
958                            // `panic!("some string")` in native testing mode.
959                            if !recovered_error_from_panic_refcell {
960                                self.with_debug_mode(|| {
961                                    if let Some(str) = panic_payload.downcast_ref::<&str>() {
962                                        let msg: String = format!(
963                                            "caught panic '{}' from contract function '{:?}'",
964                                            str, func
965                                        );
966                                        let _ = self.log_diagnostics(&msg, args);
967                                    } else if let Some(str) = panic_payload.downcast_ref::<String>()
968                                    {
969                                        let msg: String = format!(
970                                            "caught panic '{}' from contract function '{:?}'",
971                                            str, func
972                                        );
973                                        let _ = self.log_diagnostics(&msg, args);
974                                    };
975                                    Ok(())
976                                })
977                            }
978                            Err(self.error(error, "caught error from function", &[]))
979                        }
980                    }
981                });
982            }
983        }
984
985        let res =
986            self.call_contract_fn(id, &func, args, call_params.treat_missing_function_as_noop);
987
988        match &res {
989            Ok(res) => self.fn_return_diagnostics(id, &func, res),
990            Err(_err) => {}
991        }
992
993        res
994    }
995
996    // Notes on metering: covered by the called components.
997    fn invoke_function_and_return_val(&self, hf: HostFunction) -> Result<Val, HostError> {
998        let hf_type = hf.discriminant();
999        let frame = Frame::HostFunction(hf_type);
1000        match hf {
1001            HostFunction::InvokeContract(invoke_args) => {
1002                self.with_frame(frame, || {
1003                    // Metering: conversions to host objects are covered.
1004                    let ScAddress::Contract(ref contract_id) = invoke_args.contract_address else {
1005                        return Err(self.err(
1006                            ScErrorType::Value,
1007                            ScErrorCode::UnexpectedType,
1008                            "invoked address doesn't belong to a contract",
1009                            &[],
1010                        ));
1011                    };
1012                    let function_name: Symbol = invoke_args.function_name.try_into_val(self)?;
1013                    let args = self.scvals_to_val_vec(invoke_args.args.as_slice())?;
1014                    self.call_n_internal(
1015                        contract_id,
1016                        function_name,
1017                        args.as_slice(),
1018                        CallParams::default_external_call(),
1019                    )
1020                })
1021            }
1022            HostFunction::CreateContract(args) => self.with_frame(frame, || {
1023                let deployer: Option<AddressObject> = match &args.contract_id_preimage {
1024                    ContractIdPreimage::Address(preimage_from_addr) => {
1025                        Some(self.add_host_object(preimage_from_addr.address.metered_clone(self)?)?)
1026                    }
1027                    ContractIdPreimage::Asset(_) => None,
1028                };
1029                self.create_contract_internal(
1030                    deployer,
1031                    CreateContractArgsV2 {
1032                        contract_id_preimage: args.contract_id_preimage,
1033                        executable: args.executable,
1034                        constructor_args: Default::default(),
1035                    },
1036                    vec![],
1037                )
1038                .map(<Val>::from)
1039            }),
1040            HostFunction::CreateContractV2(args) => self.with_frame(frame, || {
1041                let deployer: Option<AddressObject> = match &args.contract_id_preimage {
1042                    ContractIdPreimage::Address(preimage_from_addr) => {
1043                        Some(self.add_host_object(preimage_from_addr.address.metered_clone(self)?)?)
1044                    }
1045                    ContractIdPreimage::Asset(_) => None,
1046                };
1047                let arg_vals = self.scvals_to_val_vec(args.constructor_args.as_slice())?;
1048                self.create_contract_internal(deployer, args, arg_vals)
1049                    .map(<Val>::from)
1050            }),
1051            HostFunction::UploadContractWasm(wasm) => self.with_frame(frame, || {
1052                self.upload_contract_wasm(wasm.to_vec()).map(<Val>::from)
1053            }),
1054        }
1055    }
1056
1057    // Notes on metering: covered by the called components.
1058    pub fn invoke_function(&self, hf: HostFunction) -> Result<ScVal, HostError> {
1059        #[cfg(any(test, feature = "testutils"))]
1060        let _invocation_meter_scope = self.maybe_meter_invocation()?;
1061
1062        let rv = self.invoke_function_and_return_val(hf)?;
1063        self.from_host_val(rv)
1064    }
1065
1066    pub(crate) fn maybe_init_instance_storage(&self, ctx: &mut Context) -> Result<(), HostError> {
1067        // Lazily initialize the storage on first access - it's not free and
1068        // not every contract will use it.
1069        if ctx.storage.is_some() {
1070            return Ok(());
1071        }
1072
1073        let Some(instance) = ctx.frame.instance() else {
1074            return Err(self.err(
1075                ScErrorType::Context,
1076                ScErrorCode::InternalError,
1077                "access to instance in frame without instance",
1078                &[],
1079            ));
1080        };
1081
1082        ctx.storage = Some(InstanceStorageMap::from_map(
1083            instance.storage.as_ref().map_or_else(
1084                || Ok(vec![]),
1085                |m| {
1086                    m.iter()
1087                        .map(|i| {
1088                            Ok((
1089                                self.to_valid_host_val(&i.key)?,
1090                                self.to_valid_host_val(&i.val)?,
1091                            ))
1092                        })
1093                        .metered_collect::<Result<Vec<(Val, Val)>, HostError>>(self)?
1094                },
1095            )?,
1096            self,
1097        )?);
1098        Ok(())
1099    }
1100
1101    // Make the in-memory instance storage persist into the `Storage` by writing
1102    // its updated contents into corresponding `ContractData` ledger entry.
1103    fn persist_instance_storage(&self) -> Result<(), HostError> {
1104        let updated_instance_storage = self.with_current_context_mut(|ctx| {
1105            if let Some(storage) = &ctx.storage {
1106                if !storage.is_modified {
1107                    return Ok(None);
1108                }
1109                Ok(Some(self.instance_storage_map_to_scmap(&storage.map)?))
1110            } else {
1111                Ok(None)
1112            }
1113        })?;
1114        if updated_instance_storage.is_some() {
1115            let contract_id = self.get_current_contract_id_internal()?;
1116            let key = self.contract_instance_ledger_key(&contract_id)?;
1117
1118            self.store_contract_instance(None, updated_instance_storage, contract_id, &key)?;
1119        }
1120        Ok(())
1121    }
1122}