thruput-native-exec 0.58.0

Native execution environment for testing Thruput smart contracts
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
use crate::network_config::NetworkConfigBuilder;
use crate::test_environment::{
    TestEnvironment, TestEnvironmentHandle, mock_genesis_root_contract,
    test_network_hash,
};
use thruput_storage_cost::StorageCostModel;
use thruput_xdr::contract::Contract;
use thruput_xdr::network_config::{ConfigParam, NetworkConfig};
use thruput_xdr::types::NetworkHash;

/// Builder for a [`TestEnvironment`] that needs something other than the
/// stock chain settings.
///
/// The plain constructors ([`TestEnvironment::new`],
/// [`no_cost`](TestEnvironment::no_cost), and the rest) cover the ordinary
/// case and are unaffected by this type. Reach for the builder when a test
/// wants to drive contract behavior that a network config parameter
/// governs -- what a contract does as it approaches a cap the chain sets,
/// which is otherwise only observable on a chain configured that way:
///
/// ```no_run
/// use thruput_native_exec::test_environment::TestEnvironment;
///
/// let env = TestEnvironment::builder()
///     .no_cost()
///     .with_max_sha256_buffers(2)
///     .build();
/// ```
///
/// Every setter is optional and independent; an unset one keeps what
/// [`TestEnvironment::new`] would have used, and unstated config
/// parameters keep their stock values (see
/// [`stock_network_config`](crate::network_config::stock_network_config)).
/// A builder with no configuration overrides at all creates its database
/// exactly as the plain constructors do. A parameter setter needs a hogd
/// build that knows the parameter; see [`NetworkConfigBuilder`].
#[must_use = "a TestEnvironmentBuilder does nothing until `build` is called"]
pub struct TestEnvironmentBuilder {
    cost_model: Option<StorageCostModel>,
    network_hash: NetworkHash,
    genesis_root_contract: Contract,
    network_config: NetworkConfigBuilder,
}

impl Default for TestEnvironmentBuilder {
    fn default() -> Self {
        Self {
            cost_model: None,
            network_hash: test_network_hash(),
            genesis_root_contract: mock_genesis_root_contract(),
            network_config: NetworkConfigBuilder::new(),
        }
    }
}

impl TestEnvironmentBuilder {
    /// A builder that would produce exactly `TestEnvironment::new(None)`.
    pub fn new() -> Self {
        Self::default()
    }

    /// Charge storage against `cost_model` instead of the chain default.
    pub fn with_cost_model(mut self, cost_model: StorageCostModel) -> Self {
        self.cost_model = Some(cost_model);
        self
    }

    /// Make every storage operation free, as
    /// [`TestEnvironment::no_cost`] does.
    pub fn no_cost(self) -> Self {
        self.with_cost_model(StorageCostModel::no_cost_model())
    }

    /// Run on `network_hash` instead of [`test_network_hash`].
    ///
    /// The network hash is part of every transaction signature preimage, so
    /// pin it when a test's signatures were produced for a specific
    /// network.
    pub fn with_network_hash(mut self, network_hash: NetworkHash) -> Self {
        self.network_hash = network_hash;
        self
    }

    /// Install `contract` as the genesis root deployment instead of
    /// [`mock_genesis_root_contract`].
    pub fn with_genesis_root_contract(mut self, contract: Contract) -> Self {
        self.genesis_root_contract = contract;
        self
    }

    /// Apply the parameter setters below to `config` rather than to the
    /// stock configuration.
    ///
    /// This is the whole-configuration escape hatch: pass one read back off
    /// another environment, or one built by hand. Anything the setters do
    /// not restate is taken from it verbatim.
    pub fn with_network_config(mut self, config: NetworkConfig) -> Self {
        self.network_config = self.network_config.with_base(config);
        self
    }

    /// State one config parameter the typed setters below do not cover.
    pub fn with_config_param(mut self, param: ConfigParam) -> Self {
        self.network_config = self.network_config.with_config_param(param);
        self
    }

    /// Concurrently open incremental SHA-256 buffers permitted per invocation
    /// frame (the cap `thruput_sdk::Hasher` allocates against).
    pub fn with_max_sha256_buffers(mut self, max_sha256_buffers: u32) -> Self {
        self.network_config = self
            .network_config
            .with_max_sha256_buffers(max_sha256_buffers);
        self
    }

    /// Invocation frames one transaction may have open at once.
    ///
    /// The harness opens its frames directly, so one the executor refuses is
    /// an unrecoverable panic rather than the error a contract would observe.
    /// To assert on the cap, have the frame call through the Invoke syscall
    /// (`thruput_sdk::call::try_call_raw_with`), which reports it as
    /// `RawCallError::DepthExceeded`.
    pub fn with_max_cross_invoke_depth(
        mut self,
        max_cross_invoke_depth: u32,
    ) -> Self {
        self.network_config = self
            .network_config
            .with_max_cross_invoke_depth(max_cross_invoke_depth);
        self
    }

    /// Contracts one transaction may attach in `contracts_to_deploy`.
    pub fn with_max_new_contracts_per_tx(
        mut self,
        max_new_contracts_per_tx: u32,
    ) -> Self {
        self.network_config = self
            .network_config
            .with_max_new_contracts_per_tx(max_new_contracts_per_tx);
        self
    }

    /// Bytes one bytestring storage item may hold.
    pub fn with_max_bytestring_len(mut self, max_bytestring_len: u32) -> Self {
        self.network_config = self
            .network_config
            .with_max_bytestring_len(max_bytestring_len);
        self
    }

    /// Bytes one attached contract's code blob (`ContractBlob.data`) may
    /// hold, checked before any attached contract is verified or executed.
    pub fn with_max_contract_size_bytes(
        mut self,
        max_contract_size_bytes: u32,
    ) -> Self {
        self.network_config = self
            .network_config
            .with_max_contract_size_bytes(max_contract_size_bytes);
        self
    }

    /// Storage savepoints one transaction may have open at once: one per
    /// `TryInvoke` frame still executing, plus the one the root commit
    /// takes.
    pub fn with_max_savepoint_depth(
        mut self,
        max_savepoint_depth: u32,
    ) -> Self {
        self.network_config = self
            .network_config
            .with_max_savepoint_depth(max_savepoint_depth);
        self
    }

    /// Bytes one incremental SHA-256 buffer may absorb between resets, the
    /// per-buffer companion of
    /// [`with_max_sha256_buffers`](Self::with_max_sha256_buffers).
    pub fn with_max_sha256_buffer_bytes(
        mut self,
        max_sha256_buffer_bytes: u32,
    ) -> Self {
        self.network_config = self
            .network_config
            .with_max_sha256_buffer_bytes(max_sha256_buffer_bytes);
        self
    }

    /// Levels of `AuthTokenNode` nesting an auth token may carry, counted
    /// from its root.
    pub fn with_max_auth_token_depth(
        mut self,
        max_auth_token_depth: u32,
    ) -> Self {
        self.network_config = self
            .network_config
            .with_max_auth_token_depth(max_auth_token_depth);
        self
    }

    /// Bytes of code (`code_size` in the artifact header) an RV32 artifact
    /// may carry to be attached as a contract.
    pub fn with_max_rv32_code_bytes(
        mut self,
        max_rv32_code_bytes: u32,
    ) -> Self {
        self.network_config = self
            .network_config
            .with_max_rv32_code_bytes(max_rv32_code_bytes);
        self
    }

    /// Bytes of guest data memory (`memory_bytes` in the artifact header)
    /// an RV32 artifact may declare to be attached as a contract.
    pub fn with_max_rv32_memory_bytes(
        mut self,
        max_rv32_memory_bytes: u32,
    ) -> Self {
        self.network_config = self
            .network_config
            .with_max_rv32_memory_bytes(max_rv32_memory_bytes);
        self
    }

    /// Create the configured environment.
    pub fn build(self) -> TestEnvironmentHandle {
        // Nothing to configure: create the database the way the plain
        // constructors do, rather than restating hogd's own defaults back
        // at it (which would also cost a probe for them).
        let network_config = if self.network_config.is_stock() {
            None
        } else {
            Some(self.network_config.build())
        };

        TestEnvironment::from_parts(
            self.cost_model.as_ref(),
            &self.network_hash,
            &self.genesis_root_contract,
            network_config.as_ref(),
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::network_config::{
        config_params, find_config_param, stock_network_config,
    };
    use crate::test_helpers::Named;
    use thruput_xdr::network_config::ConfigParamID;
    use thruput_xdr::syscalls::{raw_BytestringSet, raw_SHA256Update};
    use thruput_xdr::types::{ContractAddress, StorageKeyContractData};

    fn max_sha256_buffers(config: &NetworkConfig) -> u32 {
        match find_config_param(
            config,
            ConfigParamID::kConfigParamMaxSHA256Buffers,
        ) {
            Some(ConfigParam::kConfigParamMaxSHA256Buffers {
                max_sha256_buffers,
            }) => *max_sha256_buffers,
            other => panic!("no SHA-256 buffer cap in the config: {other:?}"),
        }
    }

    #[test]
    fn a_builder_with_no_overrides_matches_the_plain_constructor() {
        let built = TestEnvironment::builder().build();
        let plain = TestEnvironment::new(None);

        assert_eq!(built.get_network_config(), plain.get_network_config());
        assert_eq!(built.get_network_config(), stock_network_config());
    }

    #[test]
    fn no_cost_builds_the_free_cost_model() {
        assert_eq!(
            TestEnvironment::builder()
                .no_cost()
                .build()
                .get_current_cost_model()
                .bytestring_cost(32),
            0,
        );
        assert!(
            TestEnvironment::builder()
                .build()
                .get_current_cost_model()
                .bytestring_cost(32)
                > 0,
            "the chain default charges for storage",
        );
    }

    #[test]
    fn an_overridden_parameter_is_the_only_one_that_changes() {
        let stock = stock_network_config();
        let env = TestEnvironment::builder()
            .with_max_sha256_buffers(max_sha256_buffers(&stock) + 1)
            .build();
        let config = env.get_network_config();

        assert_eq!(
            max_sha256_buffers(&config),
            max_sha256_buffers(&stock) + 1,
        );
        assert_eq!(config_params(&config).len(), config_params(&stock).len());
        assert_eq!(
            &config_params(&config)[1..],
            &config_params(&stock)[1..],
            "the parameters left alone keep their stock values",
        );
    }

    // The point of the whole builder: a parameter the chain sets, set
    // differently, actually governs execution. Every live incremental
    // SHA-256 stream costs one buffer, so the cap is what the VM refuses
    // the next one against.
    #[test]
    fn the_sha256_buffer_cap_the_builder_sets_is_the_one_the_vm_enforces() {
        let env = TestEnvironment::builder()
            .no_cost()
            .with_max_sha256_buffers(2)
            .build();

        env.transact(|tx| {
            tx.call(&ContractAddress::named("sha256_cap")).run(|| {
                assert!(raw_SHA256Update(0, &[], true).is_ok());
                assert!(raw_SHA256Update(1, &[], true).is_ok());
                assert!(
                    raw_SHA256Update(2, &[], true).is_err(),
                    "a third live stream must exceed the cap of 2",
                );
            })
        })
        .assert_success();
    }

    #[test]
    fn the_stock_cap_leaves_room_for_more_streams_than_that() {
        let env = TestEnvironment::builder().no_cost().build();
        let cap = max_sha256_buffers(&env.get_network_config());
        assert!(cap > 2, "this test needs a stock cap above the one above");

        env.transact(|tx| {
            tx.call(&ContractAddress::named("sha256_stock_cap")).run(
                move || {
                    for index in 0..cap {
                        assert!(raw_SHA256Update(index, &[], true).is_ok());
                    }
                    assert!(raw_SHA256Update(cap, &[], true).is_err());
                },
            )
        })
        .assert_success();
    }

    #[test]
    fn the_max_bytestring_len_parameter_is_settable() {
        let env = TestEnvironment::builder()
            .no_cost()
            .with_max_bytestring_len(64)
            .build();

        assert_eq!(
            find_config_param(
                &env.get_network_config(),
                ConfigParamID::kConfigParamMaxBytestringLen,
            ),
            Some(&ConfigParam::kConfigParamMaxBytestringLen {
                max_bytestring_len: 64
            }),
        );
    }

    // As with the SHA-256 cap: the parameter the builder sets is the one
    // the write is measured against. It is checked where the bytestring is
    // written, so that is where the boundary shows.
    #[test]
    fn the_bytestring_cap_the_builder_sets_is_the_one_the_vm_enforces() {
        let env = TestEnvironment::builder()
            .no_cost()
            .with_max_bytestring_len(64)
            .build();
        let key = StorageKeyContractData::new([0x77; 32]);

        env.transact(|tx| {
            tx.call(&ContractAddress::named("bytestring_cap"))
                .run(move || {
                    assert!(
                        raw_BytestringSet(&key, &[0u8; 64]).is_ok(),
                        "a bytestring at the cap must still be admitted",
                    );
                    assert!(
                        raw_BytestringSet(&key, &[0u8; 65])
                            .unwrap_err()
                            .is_invalid_input(),
                        "one byte over must not be",
                    );
                })
        })
        .assert_success();
    }

    #[test]
    fn an_explicit_network_config_is_taken_verbatim() {
        let stock = stock_network_config();
        let env = TestEnvironment::builder()
            .with_network_config(stock.clone())
            .build();

        assert_eq!(env.get_network_config(), stock);
    }
}