1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
use core::fmt::Debug;

#[cfg(target_family = "wasm")]
pub mod internal {
    pub use soroban_env_guest::*;
    pub type EnvImpl = Guest;
}

#[cfg(not(target_family = "wasm"))]
pub mod internal {
    pub use soroban_env_host::*;
    pub type EnvImpl = Host;

    #[doc(hidden)]
    impl<F, T> TryConvert<F, T> for super::Env
    where
        EnvImpl: TryConvert<F, T>,
    {
        type Error = <EnvImpl as TryConvert<F, T>>::Error;
        fn convert(&self, f: F) -> Result<T, Self::Error> {
            self.env_impl.convert(f)
        }
    }
}

pub use internal::meta;
pub use internal::xdr;
pub use internal::BitSet;
pub use internal::ConversionError;
pub use internal::EnvBase;
pub use internal::IntoVal;
pub use internal::Object;
pub use internal::RawVal;
pub use internal::RawValConvertible;
pub use internal::Status;
pub use internal::Symbol;
pub use internal::TryFromVal;
pub use internal::TryIntoVal;
pub use internal::Val;

pub type EnvType<V> = internal::EnvVal<Env, V>;
pub type EnvVal = internal::EnvVal<Env, RawVal>;
pub type EnvObj = internal::EnvVal<Env, Object>;

use crate::binary::{Binary, FixedBinary};
use crate::ContractData;

/// The [Env] type provides access to the environment the contract is executing
/// within.
///
/// The [Env] provides access to information about the currently executing
/// contract, who invoked it, contract data, functions for signing, hashing,
/// etc.
///
/// Most types require access to an [Env] to be constructed or converted.
#[derive(Clone)]
pub struct Env {
    env_impl: internal::EnvImpl,
}

impl Default for Env {
    #[cfg(not(feature = "testutils"))]
    fn default() -> Self {
        Self {
            env_impl: Default::default(),
        }
    }

    #[cfg(feature = "testutils")]
    fn default() -> Self {
        Self::with_empty_recording_storage()
    }
}

impl Env {
    /// Invokes a function of a contract that is registered in the [Env].
    ///
    /// # Panics
    ///
    /// Will panic if the `contract_id` does not match a registered contract,
    /// `func` does not match a function of the referenced contract, or the
    /// number of `args` do not match the argument count of the referenced
    /// contract function.
    ///
    /// Will also panic if the value returned from the contract cannot be
    /// converted into the type `T`.
    ///
    /// ### TODO
    ///
    /// Return a [Result] instead of panic.
    pub fn invoke_contract<T: TryFromVal<Env, RawVal>>(
        &self,
        contract_id: &FixedBinary<32>,
        func: &Symbol,
        args: crate::vec::Vec<EnvVal>,
    ) -> T {
        let rv = internal::Env::call(self, contract_id.to_object(), *func, args.to_object());
        T::try_from_val(&self, rv).map_err(|_| ()).unwrap()
    }

    /// Get a [ContractData] for accessing and update contract data that has
    /// been stored by the currently executing contract.
    #[inline(always)]
    pub fn contract_data(&self) -> ContractData {
        ContractData::new(self)
    }

    /// Get the 32-byte hash identifier of the current executing contract.
    pub fn get_current_contract(&self) -> FixedBinary<32> {
        internal::Env::get_current_contract(self)
            .in_env(self)
            .try_into()
            .unwrap()
    }

    /// Get the 32-byte hash identifier of the contract that invoked this
    /// contract.
    ///
    /// # Panics
    ///
    /// Will panic the contract was not invoked by another contract.
    pub fn get_invoking_contract(&self) -> FixedBinary<32> {
        let rv = internal::Env::get_invoking_contract(self).to_raw();
        let bin = Binary::try_from_val(self, rv).unwrap();
        bin.try_into().unwrap()
    }

    #[doc(hidden)]
    #[deprecated(note = "use contract_data().has(key)")]
    pub fn has_contract_data<K>(&self, key: K) -> bool
    where
        K: IntoVal<Env, RawVal>,
    {
        self.contract_data().has(key)
    }

    #[doc(hidden)]
    #[deprecated(note = "use contract_data().get(key)")]
    pub fn get_contract_data<K, V>(&self, key: K) -> V
    where
        V::Error: Debug,
        K: IntoVal<Env, RawVal>,
        V: TryFromVal<Env, RawVal>,
    {
        self.contract_data().get_unchecked(key).unwrap()
    }

    #[doc(hidden)]
    #[deprecated(note = "use contract_data().set(key)")]
    pub fn put_contract_data<K, V>(&self, key: K, val: V)
    where
        K: IntoVal<Env, RawVal>,
        V: IntoVal<Env, RawVal>,
    {
        self.contract_data().set(key, val);
    }

    #[doc(hidden)]
    #[deprecated(note = "use contract_data().remove(key)")]
    pub fn del_contract_data<K>(&self, key: K)
    where
        K: IntoVal<Env, RawVal>,
    {
        self.contract_data().remove(key);
    }

    /// Computes a SHA-256 hash.
    pub fn compute_hash_sha256(&self, msg: Binary) -> FixedBinary<32> {
        let bin_obj = internal::Env::compute_hash_sha256(self, msg.into());
        bin_obj.in_env(self).try_into().unwrap()
    }

    /// Verifies an ed25519 signature.
    ///
    /// The ed25519 siganture (`sig`) is verified as a valid signature of the
    /// message (`msg`) by the ed25519 public key (`pk`).
    ///
    /// ### Panics
    ///
    /// Will panic if the siganture verification fails.
    ///
    /// ### TODO
    ///
    /// Return a [Result] instead of panicking.
    pub fn verify_sig_ed25519(&self, pk: FixedBinary<32>, msg: Binary, sig: FixedBinary<64>) {
        internal::Env::verify_sig_ed25519(self, msg.to_object(), pk.to_object(), sig.to_object())
            .try_into()
            .unwrap()
    }

    #[doc(hidden)]
    pub fn create_contract_from_contract(
        &self,
        contract: Binary,
        salt: FixedBinary<32>,
    ) -> FixedBinary<32> {
        let contract_obj: Object = RawVal::from(contract).try_into().unwrap();
        let salt_obj: Object = RawVal::from(salt).try_into().unwrap();
        let id_obj = internal::Env::create_contract_from_contract(self, contract_obj, salt_obj);
        id_obj.in_env(self).try_into().unwrap()
    }

    #[doc(hidden)]
    pub fn binary_new_from_linear_memory(&self, ptr: u32, len: u32) -> Binary {
        let bin_obj = internal::Env::binary_new_from_linear_memory(self, ptr.into(), len.into());
        bin_obj.in_env(self).try_into().unwrap()
    }

    #[doc(hidden)]
    pub fn binary_copy_to_linear_memory(&self, bin: Binary, b_pos: u32, lm_pos: u32, len: u32) {
        let bin_obj: Object = RawVal::from(bin).try_into().unwrap();
        internal::Env::binary_copy_to_linear_memory(
            self,
            bin_obj,
            b_pos.into(),
            lm_pos.into(),
            len.into(),
        );
    }

    #[doc(hidden)]
    pub fn binary_copy_from_linear_memory(
        &self,
        bin: Binary,
        b_pos: u32,
        lm_pos: u32,
        len: u32,
    ) -> Binary {
        let bin_obj: Object = RawVal::from(bin).try_into().unwrap();
        let new_obj = internal::Env::binary_copy_from_linear_memory(
            self,
            bin_obj,
            b_pos.into(),
            lm_pos.into(),
            len.into(),
        );
        new_obj.in_env(self).try_into().unwrap()
    }

    #[doc(hidden)]
    pub fn log_value<V: IntoVal<Env, RawVal>>(&self, v: V) {
        internal::Env::log_value(self, v.into_val(self));
    }
}

#[cfg(feature = "testutils")]
use crate::testutils::ContractFunctionSet;
#[cfg(feature = "testutils")]
use std::rc::Rc;
#[cfg(feature = "testutils")]
#[cfg_attr(feature = "docs", doc(cfg(feature = "testutils")))]
impl Env {
    fn with_empty_recording_storage() -> Env {
        struct EmptySnapshotSource();

        impl internal::storage::SnapshotSource for EmptySnapshotSource {
            fn get(
                &self,
                _key: &xdr::LedgerKey,
            ) -> Result<xdr::LedgerEntry, soroban_env_host::HostError> {
                use xdr::{ScHostStorageErrorCode, ScStatus};
                let status: internal::Status =
                    ScStatus::HostStorageError(ScHostStorageErrorCode::UnknownError).into();
                Err(status.into())
            }

            fn has(&self, _key: &xdr::LedgerKey) -> Result<bool, soroban_env_host::HostError> {
                Ok(false)
            }
        }

        let rf = Rc::new(EmptySnapshotSource());
        let storage = internal::storage::Storage::with_recording_footprint(rf);
        Env {
            env_impl: internal::EnvImpl::with_storage(storage),
        }
    }

    /// Register a contract with the [Env] for testing.
    ///
    /// ### Examples
    /// ```
    /// use soroban_sdk::{contractimpl, FixedBinary, Env, Symbol};
    ///
    /// pub struct HelloContract;
    ///
    /// #[contractimpl]
    /// impl HelloContract {
    ///     pub fn hello(env: Env, recipient: soroban_sdk::Symbol) -> soroban_sdk::Symbol {
    ///         todo!()
    ///     }
    /// }
    ///
    /// # fn main() {
    /// let env = Env::default();
    /// let contract_id = FixedBinary::from_array(&env, [0; 32]);
    /// env.register_contract(&contract_id, HelloContract);
    /// # }
    /// ```
    pub fn register_contract<T: ContractFunctionSet + 'static>(
        &self,
        contract_id: &FixedBinary<32>,
        contract: T,
    ) {
        struct InternalContractFunctionSet<T: ContractFunctionSet>(pub(crate) T);
        impl<T: ContractFunctionSet> internal::ContractFunctionSet for InternalContractFunctionSet<T> {
            fn call(
                &self,
                func: &Symbol,
                env_impl: &internal::EnvImpl,
                args: &[RawVal],
            ) -> Option<RawVal> {
                self.0.call(func, Env::with_impl(env_impl.clone()), args)
            }
        }

        self.env_impl
            .register_test_contract(
                contract_id.to_object(),
                Rc::new(InternalContractFunctionSet(contract)),
            )
            .unwrap();
    }

    #[doc(hidden)]
    pub fn invoke_contract_external_raw(&self, hf: xdr::HostFunction, args: xdr::ScVec) -> RawVal {
        self.env_impl.invoke_function_raw(hf, args).unwrap()
    }

    #[doc(hidden)]
    pub fn invoke_contract_external(&self, hf: xdr::HostFunction, args: xdr::ScVec) -> xdr::ScVal {
        self.env_impl.invoke_function(hf, args).unwrap()
    }

    #[cfg(not(target_family = "wasm"))]
    fn clone_self_and_catch_panic<F, T>(&self, f: F) -> (Env, std::thread::Result<T>)
    where
        F: FnOnce(Env) -> T,
    {
        let hook = std::panic::take_hook();
        std::panic::set_hook(Box::new(|_| ()));
        let deep_clone = self.deep_clone();
        let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(deep_clone.clone())));
        std::panic::set_hook(hook);
        (deep_clone, res)
    }

    #[cfg(not(target_family = "wasm"))]
    pub fn assert_panic_with_string<F, T: Debug>(&self, s: &str, f: F)
    where
        F: FnOnce(Env) -> T,
    {
        match self.clone_self_and_catch_panic(f) {
            (_, Ok(v)) => panic!("inner function expected to panic, but returned {:?}", v),
            (_, Err(e)) => match e.downcast_ref::<String>() {
                None => match e.downcast_ref::<&str>() {
                    Some(ps) => assert_eq!(*ps, s),
                    None => panic!(
                        "inner function panicked with unknown type when \"{}\" expected",
                        s
                    ),
                },
                Some(ps) => assert_eq!(*ps, s),
            },
        }
    }

    #[cfg(not(target_family = "wasm"))]
    pub fn assert_panic_with_status<F, T: Debug>(&self, status: Status, f: F)
    where
        F: FnOnce(Env) -> T,
    {
        use soroban_env_host::events::{DebugArg, HostEvent};

        match self.clone_self_and_catch_panic(f) {
            (_, Ok(v)) => panic!("inner function expected to panic, but returned {:?}", v),
            (clone, Err(e)) => {
                // Allow if there was a panic literally _carrying_ the status requested.
                if let Some(st) = e.downcast_ref::<Status>() {
                    assert_eq!(*st, status);
                    return;
                }
                // Allow if the last debug log entry contains the status of requested.
                if let Some(HostEvent::Debug(dbg)) = clone.env_impl.get_events().0.last() {
                    for arg in dbg.args.iter() {
                        if let DebugArg::Val(v) = arg {
                            if let Ok(st) = TryInto::<Status>::try_into(*v) {
                                if st == status {
                                    return;
                                }
                            }
                        }
                    }
                }

                // Otherwise we're going to fail but we'll try to produce a useful diagnostic if
                // the panic was a string, which many are.
                if let Some(s) = e.downcast_ref::<String>() {
                    panic!(
                        "inner function panicked with \"{}\" when status {:?} expected",
                        s, status
                    );
                }
                if let Some(s) = e.downcast_ref::<&str>() {
                    panic!(
                        "inner function panicked with \"{}\" when status {:?} expected",
                        s, status
                    );
                }
                panic!(
                    "inner function panicked with unknown type when status {:?} expected",
                    status
                );
            }
        }
    }
}

#[doc(hidden)]
impl Env {
    pub fn with_impl(env_impl: internal::EnvImpl) -> Env {
        Env { env_impl }
    }
}

#[doc(hidden)]
impl internal::EnvBase for Env {
    fn as_mut_any(&mut self) -> &mut dyn core::any::Any {
        self
    }

    fn check_same_env(&self, other: &Self) {
        self.env_impl.check_same_env(&other.env_impl);
    }

    fn deep_clone(&self) -> Self {
        Env {
            env_impl: self.env_impl.deep_clone(),
        }
    }

    fn binary_copy_from_slice(&self, _: Object, _: RawVal, _: &[u8]) -> Object {
        unimplemented!()
    }

    fn binary_copy_to_slice(&self, _: Object, _: RawVal, _: &mut [u8]) {
        unimplemented!()
    }

    fn binary_new_from_slice(&self, _: &[u8]) -> Object {
        unimplemented!()
    }

    fn log_static_fmt_val(&self, _: &'static str, _: RawVal) {
        unimplemented!()
    }

    fn log_static_fmt_static_str(&self, _: &'static str, _: &'static str) {
        unimplemented!()
    }

    fn log_static_fmt_val_static_str(&self, _: &'static str, _: RawVal, _: &'static str) {
        unimplemented!()
    }

    fn log_static_fmt_general(&self, _: &'static str, _: &[RawVal], _: &[&'static str]) {
        unimplemented!()
    }
}

///////////////////////////////////////////////////////////////////////////////
/// X-macro use: impl Env for SDK's Env
///////////////////////////////////////////////////////////////////////////////

// This is a helper macro used only by impl_env_for_sdk below. It consumes a
// token-tree of the form:
//
//  {fn $fn_id:ident $args:tt -> $ret:ty}
//
// and produces the the corresponding method definition to be used in the
// SDK's Env implementation of the Env (calling through to the corresponding
// guest or host implementation).
macro_rules! sdk_function_helper {
    {$mod_id:ident, fn $fn_id:ident($($arg:ident:$type:ty),*) -> $ret:ty}
    =>
    {
        fn $fn_id(&self, $($arg:$type),*) -> $ret {
            self.env_impl.$fn_id($($arg),*)
        }
    };
}

// This is a callback macro that pattern-matches the token-tree passed by the
// x-macro (call_macro_with_all_host_functions) and produces a suite of
// forwarding-method definitions, which it places in the body of the declaration
// of the implementation of Env for the SDK's Env.
macro_rules! impl_env_for_sdk {
    {
        $(
            // This outer pattern matches a single 'mod' block of the token-tree
            // passed from the x-macro to this macro. It is embedded in a `$()*`
            // pattern-repetition matcher so that it will match all provided
            // 'mod' blocks provided.
            $(#[$mod_attr:meta])*
            mod $mod_id:ident $mod_str:literal
            {
                $(
                    // This inner pattern matches a single function description
                    // inside a 'mod' block in the token-tree passed from the
                    // x-macro to this macro. It is embedded in a `$()*`
                    // pattern-repetition matcher so that it will match all such
                    // descriptions.
                    $(#[$fn_attr:meta])*
                    { $fn_str:literal, fn $fn_id:ident $args:tt -> $ret:ty }
                )*
            }
        )*
    }

    =>  // The part of the macro above this line is a matcher; below is its expansion.

    {
        // This macro expands to a single item: the implementation of Env for
        // the SDK's Env struct used by client contract code running in a WASM VM.
        #[doc(hidden)]
        impl internal::Env for Env
        {
            $(
                $(
                    // This invokes the guest_function_helper! macro above
                    // passing only the relevant parts of the declaration
                    // matched by the inner pattern above. It is embedded in two
                    // nested `$()*` pattern-repetition expanders that
                    // correspond to the pattern-repetition matchers in the
                    // match section, but we ignore the structure of the 'mod'
                    // block repetition-level from the outer pattern in the
                    // expansion, flattening all functions from all 'mod' blocks
                    // into the implementation of Env for Guest.
                    sdk_function_helper!{$mod_id, fn $fn_id $args -> $ret}
                )*
            )*
        }
    };
}

// Here we invoke the x-macro passing generate_env_trait as its callback macro.
internal::call_macro_with_all_host_functions! { impl_env_for_sdk }