Skip to main content

thruput_native_exec/
test_environment.rs

1use crate::frame_result::FrameResult;
2use crate::mock_contract::{MockContract, MockContractInner};
3use crate::mock_transaction_handler::MockTransactionHandler;
4use crate::test_environment_builder::TestEnvironmentBuilder;
5use crate::transact_result::TransactResult;
6use crate::transaction_builder::TransactionBuilder;
7use core::ffi::c_void;
8use sha2::{Digest, Sha256};
9use std::cell::RefCell;
10use std::rc::Rc;
11use std::time::{SystemTime, UNIX_EPOCH};
12use thruput_storage_cost::StorageCostModel;
13use thruput_sys::FFIErrorCode;
14use thruput_trace::ffi_enums::InvokeErrorCode;
15use thruput_xdr::address_auth::AddressAuthData;
16use thruput_xdr::contract::ContractEntrypointID;
17use thruput_xdr::contract::*;
18use thruput_xdr::network_config::NetworkConfig;
19use thruput_xdr::storage_item::WireStorageItem;
20use thruput_xdr::transaction::*;
21use thruput_xdr::types::*;
22use xdrs::txs;
23
24// When deploying a new contract, hogd accounts for the storage cost of the contract
25// based on its size.  We don't have access to contract size here (because it's not built),
26// so we pick a default (nonzero) value as a placeholder.
27// Nonzero so that contract tests will expect to at least pay some storage cost when deploying a new contract.
28const TEST_CONTRACT_SIZE: u32 = 1024;
29
30/// Name of the network that [`TestEnvironment`]s run on.
31///
32/// Every environment is created against one fixed, obviously-not-mainnet
33/// network identity, so that a test cannot accidentally produce (or replay)
34/// something signed for a real network.
35pub const TEST_NETWORK_NAME: &str = "LOCAL_UNIT_TEST";
36
37/// The [`NetworkHash`] that [`TestEnvironment`]s are created with:
38/// `sha256(`[`TEST_NETWORK_NAME`]`)`.
39///
40/// Pass a different one to [`TestEnvironment::with_network_hash`] if a test
41/// needs to pin a specific network.
42pub fn test_network_hash() -> NetworkHash {
43    let mut hasher = Sha256::new();
44    hasher.update(TEST_NETWORK_NAME.as_bytes());
45    let hash: [u8; 32] = hasher.finalize().into();
46    NetworkHash::new(hash.into())
47}
48
49/// The state behind a [`TestEnvironment`]: the FFI database, runtime
50/// context, and registered mock contracts.
51pub(crate) struct TestEnvironmentInner {
52    pub(crate) db: DBWrapper,
53    pub(crate) contract_context: RuntimeContextWrapper,
54    mock_contract_index: i32,
55    contracts: Vec<*mut MockContractInner>, // owns these contracts
56    clock: BlockClock,
57}
58
59/// After a pin, blocks continue from the pinned time plus the elapsed
60/// wall-clock time, and never move backwards. Before one, the host uses the
61/// wall clock.
62#[derive(Debug, Default)]
63struct BlockClock {
64    pinned: Option<PinnedClock>,
65}
66
67#[derive(Debug)]
68struct PinnedClock {
69    offset_nanos: i128,
70    last: u64,
71}
72
73impl BlockClock {
74    /// The timepoint for the next block, or `None` to let the host read the
75    /// wall clock.
76    fn next(&self, now: SystemTime) -> Option<u64> {
77        self.pinned.as_ref().map(|pinned| {
78            let shifted = unix_nanos(now).saturating_add(pinned.offset_nanos);
79            u64::try_from(shifted.max(0))
80                .unwrap_or(u64::MAX)
81                .max(pinned.last)
82        })
83    }
84
85    fn pin(&mut self, timepoint: u64, now: SystemTime) {
86        self.pinned = Some(PinnedClock {
87            offset_nanos: i128::from(timepoint) - unix_nanos(now),
88            last: timepoint,
89        });
90    }
91
92    fn advanced(&mut self, timepoint: u64) {
93        if let Some(pinned) = &mut self.pinned {
94            pinned.last = timepoint;
95        }
96    }
97}
98
99fn unix_nanos(now: SystemTime) -> i128 {
100    match now.duration_since(UNIX_EPOCH) {
101        Ok(since) => i128::try_from(since.as_nanos()).unwrap_or(i128::MAX),
102        Err(before) => {
103            -i128::try_from(before.duration().as_nanos()).unwrap_or(i128::MAX)
104        }
105    }
106}
107
108/// An in-process Thruput instance for testing contracts natively.
109///
110/// A `TestEnvironment` owns a fresh in-memory database and runtime context
111/// (backed by hogd via FFI). Constructors return a [`TestEnvironmentHandle`];
112/// clone the handle to share the environment across helpers.
113///
114/// - [`TestEnvironment::new`] takes an optional storage cost model;
115///   [`TestEnvironment::no_cost`] disables storage costs entirely. Both run on
116///   the default test network ([`test_network_hash`]);
117///   [`TestEnvironment::with_network_hash`] picks a different one.
118/// - The `setup_*` methods seed state (contracts, deployments, storage
119///   tokens) as if applied in a previous block; call them before running
120///   transactions.
121/// - [`TestEnvironment::transact`] executes a transaction against the
122///   environment and auto-commits; build frames with the fluent
123///   `tx.call(&addr)` API. [`TestEnvironment::advance_block`] makes
124///   committed effects visible to subsequent transactions.
125/// - [`TestEnvironment::builder`] reaches settings the constructors above
126///   do not, notably the chain's network config parameters. It is entirely
127///   optional: everything else here behaves the same whether or not any
128///   test uses it.
129///
130/// ```no_run
131/// use thruput_native_exec::test_environment::TestEnvironment;
132/// use thruput_xdr::types::ContractAddress;
133///
134/// let env = TestEnvironment::no_cost();
135/// let addr = ContractAddress::new([0x11; 32]);
136/// let result = env.transact(|tx| tx.call(&addr).run(|| { /* guest code */ }));
137/// result.assert_success();
138/// ```
139///
140/// Setting the `SDK_TEST_ENABLE_SYSCALL_LOGGING` environment variable turns
141/// on syscall tracing for environments created afterwards.
142pub struct TestEnvironment {
143    pub(crate) inner: RefCell<TestEnvironmentInner>,
144}
145
146unsafe extern "C" fn trampoline(
147    context: *mut c_void,
148    method: u64,
149) -> thruput_sys::ForeignInvokeResult {
150    let c: *mut MockContractInner = unsafe { core::mem::transmute(context) };
151
152    let method: ContractEntrypointID = method.to_be_bytes().into();
153
154    // Undefined method: run the registered fallback if there is one (see
155    // `MockContract::register_unknown_method`), otherwise fail the frame
156    // deterministically — the native analog of the rv32 dispatcher's
157    // `ebreak`.
158    match unsafe { (*c).get_func(method).or_else(|| (*c).get_unknown_func()) }
159    {
160        Some(x) => {
161            // Mark this thread as running a contract body for the call. The
162            // body may resume on a pool thread rather than the one that
163            // activated the panic hook, and this is the point where the right
164            // thread is known without guessing: it is the one calling `x`.
165            let _in_body = crate::invoke_error::PanicHookGuard::enter();
166            x()
167        }
168        None => thruput_sys::ForeignInvokeResult {
169            panic: InvokeErrorCode::Deterministic.0,
170        },
171    }
172}
173
174pub(crate) struct DBWrapper {
175    pub(crate) db: *mut c_void,
176}
177
178impl DBWrapper {
179    pub fn new(
180        cost_model: Option<&StorageCostModel>,
181        network_hash: &NetworkHash,
182        genesis_root_contract: &Contract,
183        network_config: Option<&NetworkConfig>,
184    ) -> Self {
185        let cost_model_bytes =
186            cost_model.map(|model| model.serialize().unwrap());
187
188        let ffi_cost_model_bytes: (*const u8, u32) = cost_model_bytes
189            .as_ref()
190            .map(|vec| (vec.as_ptr(), vec.len().try_into().unwrap()))
191            .unwrap_or((core::ptr::null(), 0));
192
193        let genesis_root_bytes = txs::encode(genesis_root_contract).unwrap();
194
195        let network_config_bytes =
196            network_config.map(|config| txs::encode(config).unwrap());
197        let ffi_network_config_bytes: (*const u8, u32) = network_config_bytes
198            .as_ref()
199            .map(|vec| (vec.as_ptr(), vec.len().try_into().unwrap()))
200            .unwrap_or((core::ptr::null(), 0));
201
202        // hogd reads exactly 32 bytes from this pointer (it is not XDR), and
203        // rejects a null one. A null network config takes this build's stock
204        // genesis values; a non-null one must state a gapless prefix of the
205        // parameter id space, which hogd checks fatally (SIGABRT, no return
206        // through the FFI) -- build it with
207        // `crate::network_config::NetworkConfigBuilder`, which refuses to
208        // produce anything else.
209        let res = unsafe {
210            thruput_sys::create_db(
211                ffi_cost_model_bytes.0,
212                ffi_cost_model_bytes.1,
213                network_hash.as_ptr(),
214                genesis_root_bytes.as_ptr(),
215                genesis_root_bytes.len().try_into().unwrap(),
216                ffi_network_config_bytes.0,
217                ffi_network_config_bytes.1,
218            )
219        };
220        let err: FFIErrorCode = res.ffi_error_code.into();
221        if err != FFIErrorCode::None {
222            panic!("failed to create db: {}", res.ffi_error_code);
223        }
224        assert!(!res.db.is_null());
225        Self { db: res.db }
226    }
227
228    pub fn get_cost_model(&self) -> StorageCostModel {
229        let res = unsafe { thruput_sys::get_cost_model(self.db) };
230        let err: FFIErrorCode = res.ffi_error_code.into();
231        if err != FFIErrorCode::None {
232            panic!("failed to get cost model: {}", res.ffi_error_code);
233        }
234        if res.data.len == 0 {
235            panic!("failed to get cost model: no data");
236        }
237
238        let data = xdrs::txs::decode::<
239            thruput_xdr::storage_cost::StorageCostModelXdr,
240        >(res.data.as_slice().unwrap())
241        .unwrap();
242        StorageCostModel::new(data)
243    }
244
245    pub fn get_network_config(&self) -> NetworkConfig {
246        let res = unsafe { thruput_sys::get_network_config(self.db) };
247        let err: FFIErrorCode = res.ffi_error_code.into();
248        if err != FFIErrorCode::None {
249            panic!("failed to get network config: {}", res.ffi_error_code);
250        }
251        if res.data.len == 0 {
252            panic!("failed to get network config: no data");
253        }
254
255        xdrs::txs::decode::<NetworkConfig>(res.data.as_slice().unwrap())
256            .unwrap()
257    }
258
259    pub fn get_snapshot_storage_item(
260        &self,
261        addr: &ContractAddress,
262        key: &StorageKeyContractData,
263    ) -> Option<WireStorageItem> {
264        self.get_snapshot_item(
265            addr,
266            StorageKey::ContractData {
267                contract_data_key: *key,
268            },
269        )
270    }
271
272    pub fn get_snapshot_auth_data(
273        &self,
274        addr: &ContractAddress,
275    ) -> Option<AddressAuthData> {
276        match self.get_snapshot_item(addr, StorageKey::AuthData)? {
277            WireStorageItem::kItemTypeAuthData { auth_data } => {
278                Some(auth_data)
279            }
280            other => panic!("auth data key holds a non-auth item: {other:?}"),
281        }
282    }
283
284    fn get_snapshot_item(
285        &self,
286        addr: &ContractAddress,
287        key: StorageKey,
288    ) -> Option<WireStorageItem> {
289        let addrkey = AddressAndKey {
290            address: *addr,
291            key,
292        };
293        let serialized_addrkey = txs::encode(&addrkey).unwrap();
294        let ffi_addrkey = thruput_sys::FFISerializedAddressAndKey {
295            data: serialized_addrkey.as_ptr(),
296            len: serialized_addrkey.len().try_into().unwrap(),
297        };
298
299        let res = unsafe {
300            thruput_sys::get_snapshot_storage_item(self.db, ffi_addrkey)
301        };
302        let err: FFIErrorCode = res.ffi_error_code.into();
303        if err != FFIErrorCode::None {
304            panic!("failed to get snapshot storage item: {err}");
305        }
306
307        res.data
308            .as_slice()
309            .map(|bytes| txs::decode::<WireStorageItem>(bytes).unwrap())
310    }
311}
312
313impl Drop for DBWrapper {
314    fn drop(&mut self) {
315        let r = unsafe { thruput_sys::free_db(self.db) };
316        let err: FFIErrorCode = r.into();
317        if err != FFIErrorCode::None {
318            crate::drop_failure(format_args!("failed to free db: {:?}", err));
319        }
320    }
321}
322
323pub(crate) struct RuntimeContextWrapper {
324    pub context: *mut c_void,
325}
326
327impl RuntimeContextWrapper {
328    pub fn new() -> Self {
329        let res = unsafe { thruput_sys::open_runtime_context() };
330        let err: FFIErrorCode = res.ffi_error_code.into();
331        if err != FFIErrorCode::None {
332            panic!("failed to create runtime context: {}", res.ffi_error_code);
333        }
334        assert!(!res.context.is_null());
335        Self {
336            context: res.context,
337        }
338    }
339}
340
341impl Drop for RuntimeContextWrapper {
342    fn drop(&mut self) {
343        let r = unsafe { thruput_sys::close_runtime_context(self.context) };
344        let err: FFIErrorCode = r.into();
345        if err != FFIErrorCode::None {
346            crate::drop_failure(format_args!(
347                "failed to close runtime context: {:?}",
348                err
349            ));
350        }
351    }
352}
353
354impl TestEnvironmentInner {
355    /// Create a fresh in-memory database (with the given cost model) and
356    /// runtime context on `network_hash`. `genesis_root_contract` is
357    /// installed as the genesis root deployment, and `network_config`
358    /// states the execution parameters -- `None` for the stock ones.
359    pub fn new(
360        cost_model: Option<&StorageCostModel>,
361        network_hash: &NetworkHash,
362        genesis_root_contract: &Contract,
363        network_config: Option<&NetworkConfig>,
364    ) -> Self {
365        // the initialization in create_db() advances the block once, so it is prepped for
366        // accepting new transactions (in proposal mode)
367        Self {
368            db: DBWrapper::new(
369                cost_model,
370                network_hash,
371                genesis_root_contract,
372                network_config,
373            ),
374            contract_context: RuntimeContextWrapper::new(),
375            mock_contract_index: 0,
376            contracts: vec![],
377            clock: BlockClock::default(),
378        }
379    }
380
381    /// Turn on FFI-level syscall logging to stderr at `level` for
382    /// environments created afterwards.
383    pub fn enable_syscall_logging(level: thruput_sys::FFILogLevel) {
384        unsafe { thruput_sys::enable_syscall_logging(level as i32) };
385    }
386
387    /// Creates a new contract within Thruput.
388    /// This new contract is not deployed at any particular address.
389    ///
390    /// In the test framework, the semantics of the setup_{create,deploy}_contract functions
391    /// are that after the function is called, the effects on the database are as though that
392    /// contract had been {created,deployed} during the previous block.
393    ///
394    /// This contract can be subsequently deployed, either by the setup_create_deployment function,
395    /// or by the syscalls within a transaction.
396    ///
397    /// Returns the hash of the contract, which is used to identify the contract when deploying it.
398    ///
399    /// Note: Even if a mock contract is added to the test environment (via add_contract),
400    /// this function must be called to create the contract within Thruput.
401    pub fn setup_create_contract(
402        &mut self,
403        contract: &Contract,
404    ) -> SHA256Hash {
405        let contract_bytes = txs::encode(&contract).unwrap();
406        let res = unsafe {
407            thruput_sys::setup_create_contract(
408                self.contract_context.context,
409                self.db.db,
410                contract_bytes.as_ptr(),
411                contract_bytes.len().try_into().unwrap(),
412            )
413        };
414        if res != 0 {
415            let err: thruput_sys::FFIErrorCode = res.into();
416            if err == thruput_sys::FFIErrorCode::ContractVerificationFailed {
417                panic!(
418                    "setup_create_contract failed: {err}\n\
419                     \n\
420                     The contract's rv32 artifact failed validation. Common causes:\n\
421                     - The raw ELF was deployed instead of the lowered .rv32a image\n\
422                     - Memory image bounds too large\n\
423                     - Unsupported instructions (only the RV32IM subset is accepted)\n"
424                );
425            }
426            panic!("setup_create_contract failed: {err}");
427        }
428        let mut hasher = Sha256::new();
429        hasher.update(&contract_bytes);
430        let res: [u8; 32] = hasher.finalize().into();
431        res.into()
432    }
433
434    /// Deploys the specified contract at the specified address.
435    /// The contract must already have been created, either by a transaction in an earlier block
436    /// or (in the test framework) by the setup_create_contract function.
437    ///
438    /// In the test framework, the semantics of the setup_{create,deploy}_contract functions
439    /// are that after the function is called, the effects on the database are as though that
440    /// contract had been {created,deployed} during the previous block.
441    ///
442    /// This address can be subsequently invoked.
443    ///
444    /// This contract will fail if the contract hash does not exist as an existing contract within Thruput
445    /// (i.e. if the contract was not created by the setup_create_contract function,
446    /// or was not created by a transaction in an earlier block).
447    pub fn setup_create_deployment(
448        &mut self,
449        addr: &ContractAddress,
450        contract: &Contract,
451    ) {
452        let contract_bytes = txs::encode(&contract).unwrap();
453
454        let mut hasher = Sha256::new();
455        hasher.update(&contract_bytes);
456        let res: [u8; 32] = hasher.finalize().into();
457        let contract_hash: SHA256Hash = res.into();
458
459        let contract_size = deployment_contract_size(contract);
460
461        let res = unsafe {
462            thruput_sys::setup_deploy_contract(
463                self.db.db,
464                addr.as_ptr(),
465                contract_hash.as_ptr(),
466                contract_size,
467            )
468        };
469        let err: FFIErrorCode = res.into();
470        if err != FFIErrorCode::None {
471            panic!("failed to setup new contract deployment: {:?}", err);
472        }
473    }
474
475    /// Grants the specified number of storage tokens to the specified contract address.
476    ///
477    /// In the test framework, the semantics of this function is that
478    /// after this function is called, the effects on the database are as though that
479    /// contract had been granted the specified number of storage tokens during the previous block.
480    ///
481    /// This function should not be called once the contract has been deployed and invoked;
482    /// the internal accounting of storage tokens will be incorrect if that occurs.
483    pub fn setup_grant_storage_tokens(
484        &mut self,
485        addr: &ContractAddress,
486        tokens: i64,
487    ) {
488        let res = unsafe {
489            thruput_sys::setup_grant_contract_storage_tokens(
490                self.db.db,
491                addr.as_ptr(),
492                tokens,
493            )
494        };
495        let err: FFIErrorCode = res.into();
496        if err != FFIErrorCode::None {
497            panic!("failed to setup grant storage tokens: {:?}", err);
498        }
499    }
500
501    /// Advances the test state to the next block.
502    /// This makes the effects of the previous block visible to the next block.
503    /// Only the transactions that were successfully committed will be visible to the next block.
504    /// An error may occur if there are any transactions that executed but did not commit or abort.
505    ///
506    /// The new block takes its timepoint from the wall clock. After
507    /// [`TestEnvironmentInner::advance_block_at`], it continues from the
508    /// pinned time instead.
509    pub fn advance_block(&mut self) {
510        match self.clock.next(SystemTime::now()) {
511            None => self.advance_block_inner(std::ptr::null()),
512            Some(timepoint) => {
513                self.advance_block_inner(&timepoint);
514                self.clock.advanced(timepoint);
515            }
516        }
517    }
518
519    /// Advances to the next block as [`TestEnvironmentInner::advance_block`]
520    /// does, but pins the new block's timepoint rather than reading the clock.
521    /// Later blocks continue from it.
522    ///
523    /// Blocks only move forward in time: `block_timepoint` must be at or after
524    /// the open block's, and the host refuses an earlier one.
525    pub fn advance_block_at(&mut self, block_timepoint: TimePoint) {
526        let raw: u64 = block_timepoint.into_inner();
527        self.advance_block_inner(&raw);
528        self.clock.pin(raw, SystemTime::now());
529    }
530
531    fn advance_block_inner(&mut self, block_timepoint: *const u64) {
532        let res = unsafe {
533            thruput_sys::advance_new_block(self.db.db, block_timepoint)
534        };
535        let err: FFIErrorCode = res.into();
536        if err == FFIErrorCode::InvalidArgument {
537            panic!(
538                "failed to advance block: the requested timepoint precedes the \
539                 block it would follow. Blocks only move forward in time; pin a \
540                 timepoint at or after the current block's."
541            );
542        }
543        if err != FFIErrorCode::None {
544            panic!("failed to advance block: {:?}", err);
545        }
546    }
547
548    /// Registers a new mock contract with the test environment.
549    /// This does not create the contract as something visible within Thruput,
550    /// nor does it deploy it at a particular address.
551    ///
552    /// This contract (a Contract(ContractType::kMockTest))
553    /// can subsequently be created by the setup_create_contract functions,
554    /// or by being attached as one of the newly created contracts
555    /// on a SignedTransaction.
556    pub fn add_contract(&mut self) -> *mut MockContractInner {
557        let out: *mut MockContractInner = Box::into_raw(Box::new(
558            MockContractInner::new(self.mock_contract_index),
559        ));
560
561        let new_id = self.mock_contract_index;
562
563        self.contracts.push(out);
564        self.mock_contract_index += 1;
565
566        let res = unsafe {
567            thruput_sys::register_new_contract(
568                self.contract_context.context,
569                new_id,
570                Some(trampoline),
571                out as *mut c_void,
572            )
573        };
574        let err: FFIErrorCode = res.into();
575        if err != FFIErrorCode::None {
576            panic!("failed to link fn: {:?}", err);
577        }
578
579        out
580    }
581
582    /// The storage cost model the environment's database is running with.
583    pub fn get_current_cost_model(&self) -> StorageCostModel {
584        self.db.get_cost_model()
585    }
586
587    /// The execution parameters the environment's chain is running under.
588    pub fn get_network_config(&self) -> NetworkConfig {
589        self.db.get_network_config()
590    }
591
592    /// Verify `tx`'s auth claims; see
593    /// [`TestEnvironment::verify_signed_transaction_auth`].
594    pub fn run_auth_checks(
595        &self,
596        tx: &SignedTransaction,
597    ) -> thruput_xdr::auth_claim::AuthVerifyErrorCode {
598        let serialized_tx = txs::encode(tx).unwrap();
599        let ffi_serialized_tx = thruput_sys::FFISerializedSignedTransaction {
600            data: serialized_tx.as_ptr() as *mut u8,
601            len: serialized_tx.len().try_into().unwrap(),
602        };
603        let res = unsafe {
604            thruput_sys::verify_signed_transaction_auth_from_db(
605                self.db.db,
606                ffi_serialized_tx,
607            )
608        };
609        let err: FFIErrorCode = res.ffi_error_code.into();
610        if err != FFIErrorCode::None {
611            panic!("failed to run auth checks: {:?}", err);
612        }
613        res.auth_error_code.into()
614    }
615}
616
617impl Drop for TestEnvironmentInner {
618    fn drop(&mut self) {
619        for contract in &self.contracts {
620            let _ = unsafe { Box::from_raw(*contract) };
621        }
622    }
623}
624
625impl Default for TestEnvironmentInner {
626    fn default() -> Self {
627        Self::new(
628            None,
629            &test_network_hash(),
630            &mock_genesis_root_contract(),
631            None,
632        )
633    }
634}
635
636/// Shared handle to a [`TestEnvironment`]; returned by its constructors.
637pub type TestEnvironmentHandle = Rc<TestEnvironment>;
638
639/// The genesis root installed by the default constructors: a mock contract
640/// whose id sits at the top of the range, away from the low ids tests
641/// typically register. The test environment executes contract bodies
642/// natively through the mock trampoline, so the genesis root's code never
643/// runs — only its deployment exists. Use
644/// [`TestEnvironment::with_genesis_root_contract`] to install a different
645/// contract (e.g. a real rv32 artifact).
646pub fn mock_genesis_root_contract() -> Contract {
647    Contract::kMockTest {
648        mock_contract_id: u32::MAX as i32,
649    }
650}
651
652impl TestEnvironment {
653    /// Creates an environment on the default test network
654    /// ([`test_network_hash`]).
655    pub fn new(
656        cost_model: Option<&StorageCostModel>,
657    ) -> TestEnvironmentHandle {
658        Self::with_network_hash(cost_model, &test_network_hash())
659    }
660
661    /// Creates an environment on a caller-chosen network, with
662    /// [`mock_genesis_root_contract`] as the genesis root.
663    pub fn with_network_hash(
664        cost_model: Option<&StorageCostModel>,
665        network_hash: &NetworkHash,
666    ) -> TestEnvironmentHandle {
667        Self::with_genesis_root_contract(
668            cost_model,
669            network_hash,
670            &mock_genesis_root_contract(),
671        )
672    }
673
674    /// Creates an environment installing a caller-chosen genesis root
675    /// contract instead of [`mock_genesis_root_contract`].
676    pub fn with_genesis_root_contract(
677        cost_model: Option<&StorageCostModel>,
678        network_hash: &NetworkHash,
679        genesis_root_contract: &Contract,
680    ) -> TestEnvironmentHandle {
681        Self::from_parts(cost_model, network_hash, genesis_root_contract, None)
682    }
683
684    /// Start configuring an environment that needs settings the plain
685    /// constructors do not reach -- notably the chain's network config
686    /// parameters.
687    ///
688    /// Returns a [`TestEnvironmentBuilder`]; chain `with_*` methods, then
689    /// finish with [`build`](TestEnvironmentBuilder::build):
690    ///
691    /// ```no_run
692    /// use thruput_native_exec::test_environment::TestEnvironment;
693    ///
694    /// let env = TestEnvironment::builder()
695    ///     .no_cost()
696    ///     .with_max_sha256_buffers(2)
697    ///     .build();
698    /// ```
699    pub fn builder() -> TestEnvironmentBuilder {
700        TestEnvironmentBuilder::new()
701    }
702
703    /// Every constructor's common path: the one place an environment's
704    /// database and runtime context are created. `network_config` is
705    /// `None` for the stock execution parameters.
706    pub(crate) fn from_parts(
707        cost_model: Option<&StorageCostModel>,
708        network_hash: &NetworkHash,
709        genesis_root_contract: &Contract,
710        network_config: Option<&NetworkConfig>,
711    ) -> TestEnvironmentHandle {
712        let te = Rc::new(Self {
713            inner: RefCell::new(TestEnvironmentInner::new(
714                cost_model,
715                network_hash,
716                genesis_root_contract,
717                network_config,
718            )),
719        });
720
721        if std::env::var("SDK_TEST_ENABLE_SYSCALL_LOGGING").is_ok() {
722            Self::enable_syscall_logging();
723        }
724
725        te
726    }
727
728    /// Environment with the chain-default cost model on the default test
729    /// network. Not the `Default` trait: constructors return a handle.
730    #[allow(clippy::should_implement_trait)]
731    pub fn default() -> TestEnvironmentHandle {
732        Self::new(None)
733    }
734
735    /// Environment in which every storage operation costs zero.
736    pub fn no_cost() -> TestEnvironmentHandle {
737        Self::new(Some(
738            &thruput_storage_cost::StorageCostModel::no_cost_model(),
739        ))
740    }
741
742    /// Turn on FFI-level syscall logging to stderr for environments
743    /// created after the call.
744    pub fn enable_syscall_logging() {
745        TestEnvironmentInner::enable_syscall_logging(
746            thruput_sys::FFILogLevel::Trace,
747        );
748    }
749
750    /// Advance to the next block, making committed effects visible to
751    /// subsequent transactions. Panics if a transaction executed but was
752    /// neither committed nor aborted.
753    ///
754    /// The new block takes its timepoint from the wall clock, so
755    /// `thruput_sdk::block::get_block_timepoint` reports a plausible
756    /// present-day value that moves between blocks. Use `advance_block_at` to
757    /// drive contract logic keyed on time -- deadlines, expiry, vesting, rate
758    /// limits. After `advance_block_at`, later blocks continue from the pinned
759    /// time instead of falling back to the wall clock.
760    ///
761    /// The SDK path is a plain code span, not an intra-doc link:
762    /// `thruput-sdk` depends on this crate, not the other way round, so there
763    /// is nothing here to resolve it against.
764    pub fn advance_block(self: &TestEnvironmentHandle) {
765        self.inner.borrow_mut().advance_block()
766    }
767
768    /// Advance to the next block with its timepoint pinned to
769    /// `block_timepoint` (Unix nanoseconds) rather than read from the clock.
770    /// Later blocks continue from it, as on a local node.
771    ///
772    /// Blocks only move forward in time, so this panics if `block_timepoint`
773    /// precedes the current block's. Note the environment opens its first
774    /// block on the wall clock, so pin forward from the current
775    /// `thruput_sdk::block::get_block_timepoint` rather than at an absolute
776    /// past date.
777    pub fn advance_block_at(
778        self: &TestEnvironmentHandle,
779        block_timepoint: TimePoint,
780    ) {
781        self.inner.borrow_mut().advance_block_at(block_timepoint)
782    }
783
784    /// The storage cost model the environment's database is running with.
785    pub fn get_current_cost_model(
786        self: &TestEnvironmentHandle,
787    ) -> StorageCostModel {
788        self.inner.borrow().get_current_cost_model()
789    }
790
791    /// The execution parameters the environment's chain is running under
792    /// (e.g. `max_sha256_buffers`, the VM's live hash-stream cap).
793    pub fn get_network_config(self: &TestEnvironmentHandle) -> NetworkConfig {
794        self.inner.borrow().get_network_config()
795    }
796
797    /// Read a committed contract-data item from the current block snapshot
798    /// (`None` if the key holds nothing).
799    pub fn get_snapshot_storage_item(
800        self: &TestEnvironmentHandle,
801        addr: &ContractAddress,
802        key: &StorageKeyContractData,
803    ) -> Option<WireStorageItem> {
804        self.inner.borrow().db.get_snapshot_storage_item(addr, key)
805    }
806
807    /// Read an address's committed [`AddressAuthData`] (its registered keys
808    /// and required weight) from the current block snapshot (`None` if the
809    /// address has none).
810    pub fn get_snapshot_auth_data(
811        self: &TestEnvironmentHandle,
812        addr: &ContractAddress,
813    ) -> Option<AddressAuthData> {
814        self.inner.borrow().db.get_snapshot_auth_data(addr)
815    }
816
817    /// Internal: create an empty mock contract. Use `register_mock` (or the
818    /// generated `register_mock_contract`) instead.
819    #[doc(hidden)]
820    pub fn add_contract(self: &TestEnvironmentHandle) -> MockContract {
821        let inner = self.inner.borrow_mut().add_contract();
822        MockContract::new(inner, self.clone())
823    }
824
825    /// Create a mock contract, register methods onto it, and make it
826    /// deployable in the test environment.
827    ///
828    /// The registrar may be a single generated `__mock` function or a
829    /// closure that combines multiple interface registrars onto one mock.
830    pub fn register_mock<F>(self: &TestEnvironmentHandle, f: F) -> MockContract
831    where
832        F: FnOnce(&mut MockContract),
833    {
834        let mut c = self.add_contract();
835        f(&mut c);
836        self.setup_create_contract(&c.as_contract());
837        c
838    }
839
840    /// Start configuring a transaction to execute in this environment.
841    ///
842    /// Returns a [`TransactionBuilder`]; chain `with_*` methods (e.g.
843    /// [`with_auth_claim`](TransactionBuilder::with_auth_claim)) to customize
844    /// the mocked transaction context, then finish with
845    /// [`transact`](TransactionBuilder::transact),
846    /// [`transact_manual`](TransactionBuilder::transact_manual), or
847    /// [`build`](TransactionBuilder::build).
848    ///
849    /// ```ignore
850    /// env.transaction()
851    ///     .with_auth_claim(my_claim)
852    ///     .transact(|tx| tx.call(&addr).run(|| { /* ... */ }));
853    /// ```
854    pub fn transaction(self: &TestEnvironmentHandle) -> TransactionBuilder {
855        TransactionBuilder::new(self.clone())
856    }
857
858    /// Execute a transaction with auto-commit and the default configuration.
859    ///
860    /// Creates a MockTransactionHandler, gives the closure a mutable reference,
861    /// and always calls try_commit_transaction when the closure returns
862    /// (hogd handles abort internally when the root frame reverted).
863    ///
864    /// The transaction has exactly one root frame: a second `tx.call`
865    /// inside the closure panics; use a child frame or another `transact`.
866    ///
867    /// Shorthand for `env.transaction().transact(f)`; use
868    /// [`transaction`](Self::transaction) to customize the transaction first.
869    #[must_use]
870    pub fn transact(
871        self: &TestEnvironmentHandle,
872        f: impl FnOnce(&mut MockTransactionHandler) -> FrameResult,
873    ) -> TransactResult {
874        self.transaction().transact(f)
875    }
876
877    /// Execute a transaction with manual commit/abort control and the default
878    /// configuration.
879    ///
880    /// The closure receives a MockTransactionHandler and is responsible for
881    /// calling tx.try_commit_transaction() or tx.abort_transaction().
882    /// The closure's return value is forwarded as the return value of transact_manual.
883    ///
884    /// Shorthand for `env.transaction().transact_manual(f)`; use
885    /// [`transaction`](Self::transaction) to customize the transaction first.
886    pub fn transact_manual<R>(
887        self: &TestEnvironmentHandle,
888        f: impl FnOnce(&mut MockTransactionHandler) -> R,
889    ) -> R {
890        self.transaction().transact_manual(f)
891    }
892
893    // -- Setup-phase methods --
894    //
895    // The setup_* methods seed Thruput state directly, bypassing
896    // transaction execution. Call them before running any transactions in
897    // a test; their effects appear as if applied in a previous block.
898
899    /// Setup phase: create a contract in Thruput state (not deployed at
900    /// any address). Returns the contract hash. Run before any
901    /// transactions in the test.
902    pub fn setup_create_contract(
903        self: &TestEnvironmentHandle,
904        contract: &Contract,
905    ) -> SHA256Hash {
906        self.inner.borrow_mut().setup_create_contract(contract)
907    }
908
909    /// Setup phase: deploy an already-created contract at `addr`. Run
910    /// before any transactions in the test.
911    pub fn setup_create_deployment(
912        self: &TestEnvironmentHandle,
913        addr: &ContractAddress,
914        contract: &Contract,
915    ) {
916        self.inner
917            .borrow_mut()
918            .setup_create_deployment(addr, contract)
919    }
920
921    /// Setup phase: grant storage tokens to the contract at `addr`, as if
922    /// granted in a previous block. Like `setup_create_contract` and
923    /// `setup_create_deployment`, run before any transactions in the test.
924    pub fn setup_grant_storage_tokens(
925        self: &TestEnvironmentHandle,
926        addr: &ContractAddress,
927        tokens: i64,
928    ) {
929        self.inner
930            .borrow_mut()
931            .setup_grant_storage_tokens(addr, tokens)
932    }
933
934    /// Check the auth claims on the provided transaction
935    /// against the auth data loaded from the database.
936    ///
937    /// May perform additional checks (such as checking block height limits)
938    /// not performed by the static version.  Will additionally fail if
939    /// addresses without auth data are referenced.
940    pub fn verify_signed_transaction_auth(
941        self: &TestEnvironmentHandle,
942        tx: &SignedTransaction,
943    ) -> thruput_xdr::auth_claim::AuthVerifyErrorCode {
944        self.inner.borrow().run_auth_checks(tx)
945    }
946
947    /// Check the auth claims on the provided transaction
948    /// against the provided source and auxiliary auth data.
949    /// Does not load any information from the database.
950    ///
951    /// Pass `None` to represent "no registered auth data" (the pubkey-claim
952    /// case). Pass `Some(d)` to supply serialized [`AddressAuthData`].
953    ///
954    /// `network_hash` is part of every signature preimage, so it must be the
955    /// network the signatures were produced for — see
956    /// `thruput_domain_separator::transaction_signature_preimage`. There is
957    /// no database here to read it from, so it is passed explicitly;
958    /// [`test_network_hash`] is what a [`TestEnvironment`] would use.
959    pub fn verify_signed_transaction_auth_static(
960        tx: &SignedTransaction,
961        source_auth_data: Option<&AddressAuthData>,
962        network_hash: &NetworkHash,
963    ) -> thruput_xdr::auth_claim::AuthVerifyErrorCode {
964        let serialized_tx = txs::encode(tx).unwrap();
965        let ffi_serialized_tx = thruput_sys::FFISerializedSignedTransaction {
966            data: serialized_tx.as_ptr() as *mut u8,
967            len: serialized_tx.len().try_into().unwrap(),
968        };
969
970        // `None` → null pointer with len=0 (pubkey-claim path, 0.20.1+).
971        // `Some(d)` → serialize and pass as before.
972        let serialized_source_auth_data =
973            source_auth_data.map(|d| txs::encode(d).unwrap());
974        let ffi_serialized_source_auth_data =
975            match &serialized_source_auth_data {
976                Some(bytes) => thruput_sys::FFISourceAuthData {
977                    data: bytes.as_ptr() as *mut u8,
978                    len: bytes.len().try_into().unwrap(),
979                },
980                None => thruput_sys::FFISourceAuthData {
981                    data: core::ptr::null_mut(),
982                    len: 0,
983                },
984            };
985
986        let res = unsafe {
987            thruput_sys::verify_signed_transaction_auth(
988                ffi_serialized_tx,
989                ffi_serialized_source_auth_data,
990                network_hash.as_ptr(),
991            )
992        };
993        let err: FFIErrorCode = res.ffi_error_code.into();
994        if err != FFIErrorCode::None {
995            panic!("failed to run auth checks: {:?}", err);
996        }
997        res.auth_error_code.into()
998    }
999}
1000
1001fn deployment_contract_size(contract: &Contract) -> u32 {
1002    match contract {
1003        Contract::kNative { .. } => 0,
1004        Contract::kMockTest { .. } => TEST_CONTRACT_SIZE,
1005        Contract::kRv32 { rv32_contract } => rv32_contract.data.len() as u32,
1006        other => panic!("unsupported contract variant: {:?}", other),
1007    }
1008}
1009
1010#[cfg(test)]
1011mod tests {
1012    use super::*;
1013    use xdrs::BytesM;
1014
1015    const TEST_ADDR: ContractAddress = ContractAddress::new([0x11; 32]);
1016
1017    #[test]
1018    fn test_network_hash_is_sha256_of_the_test_network_name() {
1019        // Pinned so the network every test runs on cannot drift silently:
1020        // sha256("LOCAL_UNIT_TEST").
1021        let expected: [u8; 32] = [
1022            0xb0, 0xb2, 0xfc, 0xc8, 0x57, 0xda, 0xa6, 0x04, 0x78, 0x7b, 0xb8,
1023            0x4b, 0x45, 0xa4, 0xca, 0xf0, 0x32, 0xea, 0x6b, 0x93, 0xf5, 0xa5,
1024            0xed, 0x1c, 0x14, 0xa9, 0xbf, 0xf8, 0xfa, 0x65, 0xbb, 0x52,
1025        ];
1026        assert_eq!(test_network_hash(), NetworkHash::new(expected.into()));
1027    }
1028
1029    #[test]
1030    fn deployment_contract_size_uses_rv32_blob_length() {
1031        let contract = Contract::kRv32 {
1032            rv32_contract: ContractBlob {
1033                data: BytesM(vec![1, 2, 3, 4, 5]),
1034            },
1035        };
1036
1037        assert_eq!(deployment_contract_size(&contract), 5);
1038    }
1039
1040    #[test]
1041    fn get_snapshot_storage_item_reads_committed_bytestring() {
1042        let env = TestEnvironment::new(None);
1043        let key = StorageKeyContractData::new([0x22; 32]);
1044        env.setup_grant_storage_tokens(&TEST_ADDR, 1_000_000_000);
1045
1046        let result = env.transact(|tx| {
1047            tx.call(&TEST_ADDR).run(|| {
1048                thruput_xdr::syscalls::raw_BytestringSet(&key, b"hello")
1049                    .unwrap();
1050            })
1051        });
1052        result.assert_success();
1053
1054        env.advance_block();
1055
1056        let item = env.get_snapshot_storage_item(&TEST_ADDR, &key);
1057        assert_eq!(
1058            item,
1059            Some(WireStorageItem::kItemTypeBytestring {
1060                bytestring: b"hello".to_vec().try_into().unwrap(),
1061            }),
1062        );
1063    }
1064
1065    #[test]
1066    fn get_snapshot_storage_item_returns_none_for_missing_key() {
1067        let env = TestEnvironment::new(None);
1068        let key = StorageKeyContractData::new([0x33; 32]);
1069
1070        assert_eq!(env.get_snapshot_storage_item(&TEST_ADDR, &key), None);
1071    }
1072
1073    #[test]
1074    fn get_snapshot_storage_item_reads_committed_bytestring_on_deployed_address()
1075     {
1076        let env = TestEnvironment::new(None);
1077        let key = StorageKeyContractData::new([0x44; 32]);
1078        env.setup_grant_storage_tokens(&TEST_ADDR, 1_000_000_000);
1079        // Any created, deployable contract works: the transact below runs
1080        // through the mock trampoline regardless of the deployed type, and
1081        // native precompiles are banned from redeployment.
1082        // A fresh environment hands out mock contract ids from zero.
1083        let _mock = env.inner.borrow_mut().add_contract();
1084        let contract = thruput_xdr::contract::Contract::kMockTest {
1085            mock_contract_id: 0,
1086        };
1087        env.inner.borrow_mut().setup_create_contract(&contract);
1088        env.inner
1089            .borrow_mut()
1090            .setup_create_deployment(&TEST_ADDR, &contract);
1091
1092        let result = env.transact(|tx| {
1093            tx.call(&TEST_ADDR).run(|| {
1094                thruput_xdr::syscalls::raw_BytestringSet(&key, b"hello")
1095                    .unwrap();
1096            })
1097        });
1098        result.assert_success();
1099
1100        env.advance_block();
1101
1102        let item = env.get_snapshot_storage_item(&TEST_ADDR, &key);
1103        assert_eq!(
1104            item,
1105            Some(WireStorageItem::kItemTypeBytestring {
1106                bytestring: b"hello".to_vec().try_into().unwrap(),
1107            }),
1108        );
1109    }
1110}
1111
1112#[cfg(test)]
1113mod block_clock_tests {
1114    use std::time::{Duration, SystemTime, UNIX_EPOCH};
1115
1116    use super::BlockClock;
1117
1118    const NOW: u64 = 1_760_000_000_000_000_000;
1119    const HOUR: u64 = 60 * 60 * 1_000_000_000;
1120
1121    fn at(nanos: u64) -> SystemTime {
1122        UNIX_EPOCH + Duration::from_nanos(nanos)
1123    }
1124
1125    #[test]
1126    fn before_any_pin_the_host_reads_the_wall_clock() {
1127        assert_eq!(BlockClock::default().next(at(NOW)), None);
1128    }
1129
1130    #[test]
1131    fn after_a_pin_blocks_advance_by_the_elapsed_wall_clock_time() {
1132        let mut clock = BlockClock::default();
1133        clock.pin(NOW + 72 * HOUR, at(NOW));
1134
1135        // Seven nanoseconds of wall-clock time later, the next block is seven
1136        // nanoseconds past the pinned time: it neither freezes nor falls back.
1137        assert_eq!(clock.next(at(NOW + 7)), Some(NOW + 72 * HOUR + 7));
1138        assert_eq!(clock.next(at(NOW + HOUR)), Some(NOW + 73 * HOUR));
1139    }
1140
1141    #[test]
1142    fn a_block_never_moves_behind_the_one_before_it() {
1143        let mut clock = BlockClock::default();
1144        clock.pin(NOW + HOUR, at(NOW));
1145        clock.advanced(NOW + 2 * HOUR);
1146
1147        // The wall clock implies NOW + HOUR + 5, but the last block was later.
1148        assert_eq!(clock.next(at(NOW + 5)), Some(NOW + 2 * HOUR));
1149        // Once the clock passes the last block, it leads again.
1150        assert_eq!(clock.next(at(NOW + 2 * HOUR)), Some(NOW + 3 * HOUR));
1151    }
1152
1153    #[test]
1154    fn a_wall_clock_step_back_keeps_the_last_block() {
1155        let mut clock = BlockClock::default();
1156        clock.pin(NOW + HOUR, at(NOW));
1157
1158        assert_eq!(clock.next(at(NOW - HOUR)), Some(NOW + HOUR));
1159    }
1160}