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