Skip to main content

oasis_runtime_sdk/
state.rs

1use std::{
2    any::Any,
3    cell::RefCell,
4    collections::btree_map::{BTreeMap, Entry},
5    fmt,
6    marker::PhantomData,
7    mem,
8    sync::Arc,
9};
10
11use oasis_core_runtime::{common::crypto::hash::Hash, consensus::roothash, storage::mkvs};
12
13use crate::{
14    context::Context,
15    crypto::{random::RootRng, signature::PublicKey},
16    event::{Event, EventTag, EventTags},
17    modules::core::Error,
18    storage::{MKVSStore, NestedStore, OverlayStore, Store},
19    types::{address::Address, message::MessageEventHookInvocation, transaction},
20};
21
22/// Execution mode.
23#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)]
24#[repr(u8)]
25pub enum Mode {
26    /// Actually execute transactions during block production.
27    #[default]
28    Execute,
29    /// Check that transactions are valid for local acceptance into the transaction pool.
30    Check,
31    /// Simulate transaction outcomes (e.g. for gas estimation).
32    Simulate,
33    /// Check that transactions are still valid before scheduling.
34    PreSchedule,
35}
36
37const MODE_CHECK: &str = "check";
38const MODE_EXECUTE: &str = "execute";
39const MODE_SIMULATE: &str = "simulate";
40const MODE_PRE_SCHEDULE: &str = "pre_schedule";
41
42impl fmt::Display for Mode {
43    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44        f.write_str(self.into())
45    }
46}
47
48impl From<&Mode> for &'static str {
49    fn from(m: &Mode) -> Self {
50        match m {
51            Mode::Check => MODE_CHECK,
52            Mode::Execute => MODE_EXECUTE,
53            Mode::Simulate => MODE_SIMULATE,
54            Mode::PreSchedule => MODE_PRE_SCHEDULE,
55        }
56    }
57}
58
59/// Information about the execution environment.
60#[derive(Clone, Default, Debug)]
61pub struct Environment {
62    mode: Mode,
63    tx: Option<Arc<TransactionInfo>>,
64    internal: bool,
65}
66
67impl Environment {
68    /// Execution mode.
69    pub fn mode(&self) -> Mode {
70        self.mode
71    }
72
73    /// Whether the execution mode is such that only checks should be performed.
74    pub fn is_check_only(&self) -> bool {
75        matches!(self.mode, Mode::Check | Mode::PreSchedule)
76    }
77
78    /// Whether the execution mode is `Mode::PreSchedule`.
79    pub fn is_pre_schedule(&self) -> bool {
80        matches!(self.mode, Mode::PreSchedule)
81    }
82
83    /// Whether the execution mode is `Mode::Simulate`.
84    pub fn is_simulation(&self) -> bool {
85        matches!(self.mode, Mode::Simulate)
86    }
87
88    /// Whether the execution mode is `Mode::Execute`.
89    pub fn is_execute(&self) -> bool {
90        matches!(self.mode, Mode::Execute)
91    }
92
93    /// Whether there is an active transaction in the current environment.
94    pub fn is_transaction(&self) -> bool {
95        self.tx.is_some()
96    }
97
98    /// An active transaction's index (order) within the block.
99    ///
100    /// # Panics
101    ///
102    /// This method will panic if called outside a transaction environment.
103    pub fn tx_index(&self) -> usize {
104        self.tx
105            .as_ref()
106            .map(|tx| tx.index)
107            .expect("only in transaction environment")
108    }
109
110    /// An active transaction's size in bytes.
111    ///
112    /// # Panics
113    ///
114    /// This method will panic if called outside a transaction environment.
115    pub fn tx_size(&self) -> u32 {
116        self.tx
117            .as_ref()
118            .map(|tx| tx.size)
119            .expect("only in transaction environment")
120    }
121
122    /// An active transaction's authentication information.
123    ///
124    /// # Panics
125    ///
126    /// This method will panic if called outside a transaction environment.
127    pub fn tx_auth_info(&self) -> &transaction::AuthInfo {
128        self.tx
129            .as_ref()
130            .map(|tx| &tx.auth_info)
131            .expect("only in transaction environment")
132    }
133
134    /// An active transaction's call format.
135    ///
136    /// # Panics
137    ///
138    /// This method will panic if called outside a transaction environment.
139    pub fn tx_call_format(&self) -> transaction::CallFormat {
140        self.tx
141            .as_ref()
142            .map(|tx| tx.call_format)
143            .expect("only in transaction environment")
144    }
145
146    /// An active transaction's read only flag.
147    ///
148    /// # Panics
149    ///
150    /// This method will panic if called outside a transaction environment.
151    pub fn is_read_only(&self) -> bool {
152        self.tx
153            .as_ref()
154            .map(|tx| tx.read_only)
155            .expect("only in transaction environment")
156    }
157
158    /// Whether the current execution environment is part of an internal subcall.
159    pub fn is_internal(&self) -> bool {
160        self.internal
161    }
162
163    /// Authenticated address of the caller.
164    ///
165    /// In case there are multiple signers of a transaction, this will return the address
166    /// corresponding to the first signer. If there are no signers, it returns the default address.
167    ///
168    /// # Panics
169    ///
170    /// This method will panic if called outside a transaction environment.
171    pub fn tx_caller_address(&self) -> Address {
172        self.tx_auth_info()
173            .signer_info
174            .first()
175            .map(|si| si.address_spec.address())
176            .unwrap_or_default()
177    }
178
179    /// Authenticated caller public key if available.
180    ///
181    /// In case there are multiple signers of a transaction, this will return the public key
182    /// corresponding to the first signer. If there are no signers or if the address specification
183    /// does not represent a single public key, it returns `None`.
184    ///
185    /// # Panics
186    ///
187    /// This method will panic if called outside a transaction environment.
188    pub fn tx_caller_public_key(&self) -> Option<PublicKey> {
189        self.tx_auth_info()
190            .signer_info
191            .first()
192            .and_then(|si| si.address_spec.public_key())
193    }
194}
195
196/// Information about a transaction that is exposed through the execution environment.
197///
198/// The call method and body are intentionally not part of this information as they are consumed
199/// by the dispatcher.
200#[derive(Clone, Debug)]
201pub struct TransactionInfo {
202    /// Transaction authentication information.
203    pub auth_info: transaction::AuthInfo,
204    /// Call format.
205    pub call_format: transaction::CallFormat,
206    /// Read-only flag.
207    pub read_only: bool,
208    /// Transaction size.
209    pub size: u32,
210    /// Transaction index within the batch.
211    pub index: usize,
212    /// Transaction hash.
213    pub hash: Hash,
214}
215
216impl TransactionInfo {
217    /// Split the given transaction into transaction information and the call to dispatch.
218    pub fn from_tx(
219        tx: transaction::Transaction,
220        size: u32,
221        index: usize,
222        hash: Hash,
223    ) -> (Self, transaction::Call) {
224        let info = Self {
225            auth_info: tx.auth_info,
226            call_format: tx.call.format,
227            read_only: tx.call.read_only,
228            size,
229            index,
230            hash,
231        };
232        (info, tx.call)
233    }
234
235    /// Split the given internally generated transaction into transaction information and the call
236    /// to dispatch.
237    ///
238    /// Internally generated transactions have zero size, index and hash.
239    pub fn internal(tx: transaction::Transaction) -> (Self, transaction::Call) {
240        Self::from_tx(tx, 0, 0, Default::default())
241    }
242}
243
244#[cfg(any(test, feature = "test"))]
245impl From<transaction::Transaction> for Arc<TransactionInfo> {
246    fn from(tx: transaction::Transaction) -> Self {
247        Arc::new(TransactionInfo::internal(tx).0) // For use in tests.
248    }
249}
250
251/// Environment modification options.
252#[derive(Clone, Default, Debug)]
253pub struct Options {
254    pub mode: Option<Mode>,
255    pub tx: Option<Arc<TransactionInfo>>,
256    pub internal: Option<bool>,
257    pub rng_local_entropy: bool,
258}
259
260impl Options {
261    /// Create options with default values.
262    pub fn new() -> Self {
263        Self::default()
264    }
265
266    /// Change the execution mode of the environment.
267    pub fn with_mode(self, mode: Mode) -> Self {
268        Self {
269            mode: Some(mode),
270            ..self
271        }
272    }
273
274    /// Change the active transaction of the environment.
275    pub fn with_tx(self, tx: Arc<TransactionInfo>) -> Self {
276        Self {
277            tx: Some(tx),
278            ..self
279        }
280    }
281
282    /// Change the internal flag of the environment.
283    pub fn with_internal(self, internal: bool) -> Self {
284        Self {
285            internal: Some(internal),
286            ..self
287        }
288    }
289
290    /// Request for local entropy to be mixed into the current RNG.
291    ///
292    /// # Determinism
293    ///
294    /// Using this method will result in non-deterministic behavior as the node's local entropy is
295    /// mixed into the RNG. As such, this method should only be used in cases where non-determinism
296    /// is not problematic (e.g. local queries).
297    pub fn with_rng_local_entropy(self) -> Self {
298        Self {
299            rng_local_entropy: true,
300            ..self
301        }
302    }
303}
304
305/// Mutable block state of a runtime.
306///
307/// The state includes storage, emitted events, messages to consensus layer, etc. States can be
308/// nested via `open`, `commit` and `rollback` methods which behave like transactions.
309pub struct State {
310    parent: Option<Box<State>>,
311    store: Option<OverlayStore<Box<dyn Store>>>,
312
313    events: EventTags,
314    unconditional_events: EventTags,
315    messages: Vec<(roothash::Message, MessageEventHookInvocation)>,
316
317    block_values: BTreeMap<&'static str, Box<dyn Any>>,
318    hidden_block_values: Option<BTreeMap<&'static str, Box<dyn Any>>>,
319    local_values: BTreeMap<&'static str, Box<dyn Any>>,
320
321    rng: Option<RootRng>,
322    hidden_rng: Option<RootRng>,
323    env: Environment,
324
325    always_rollback: bool,
326}
327
328impl State {
329    /// Initialize the state with the given options.
330    fn init(&mut self, opts: Options) {
331        if let Some(mode) = opts.mode {
332            // Change mode.
333            self.env.mode = mode;
334            // If we have enabled pre-schedule or simulation mode, always rollback state and hide
335            // block values to prevent leaking them.
336            if matches!(mode, Mode::PreSchedule | Mode::Simulate) {
337                self.always_rollback = true;
338                self.hide_block_values();
339            }
340        }
341
342        if let Some(tx) = opts.tx {
343            // Change RNG state.
344            self.rng.as_mut().unwrap().append_tx(tx.hash);
345            // Change tx metadata.
346            self.env.tx = Some(tx);
347        }
348
349        if let Some(internal) = opts.internal {
350            self.env.internal = internal;
351            if internal {
352                self.hide_block_values();
353            }
354        }
355
356        if opts.rng_local_entropy {
357            // Append local entropy to RNG state.
358            self.rng.as_mut().unwrap().append_local_entropy();
359        }
360
361        if !matches!(self.env.mode, Mode::PreSchedule) {
362            // Record opening a child state in the RNG.
363            self.rng.as_mut().unwrap().append_subcontext();
364        } else {
365            // Use an invalid RNG as its use is not allowed in pre-schedule context.
366            self.disable_rng();
367        }
368    }
369
370    /// Open a child state after which self will point to the child state.
371    pub fn open(&mut self) {
372        let mut parent = Self {
373            parent: None,
374            store: None,
375            events: EventTags::new(),
376            unconditional_events: EventTags::new(),
377            messages: Vec::new(),
378            block_values: BTreeMap::new(),
379            hidden_block_values: None,
380            local_values: BTreeMap::new(),
381            rng: None,
382            hidden_rng: None,
383            env: self.env.clone(),
384            always_rollback: false,
385        };
386        mem::swap(&mut parent, self);
387
388        // Wrap parent store to create an overlay child store.
389        self.store = parent
390            .store
391            .take()
392            .map(|pstore| OverlayStore::new(Box::new(pstore) as Box<dyn Store>));
393
394        // Take block values map. We will put it back after commit/rollback.
395        mem::swap(&mut parent.block_values, &mut self.block_values);
396        // Take RNG. We will put it back after commit/rollback.
397        mem::swap(&mut parent.rng, &mut self.rng);
398
399        self.parent = Some(Box::new(parent));
400    }
401
402    fn convert_store(store: Box<dyn Store>) -> OverlayStore<Box<dyn Store>> {
403        let raw = Box::into_raw(store);
404        unsafe {
405            // SAFETY: This is safe because we always wrap child stores into OverlayStore.
406            *Box::from_raw(raw as *mut OverlayStore<Box<dyn Store>>)
407        }
408    }
409
410    /// Commit the current state and return to its parent state.
411    ///
412    /// # Panics
413    ///
414    /// This method will panic when attempting to commit the root state.
415    pub fn commit(&mut self) {
416        if self.always_rollback {
417            self.rollback();
418        } else {
419            self._commit();
420        }
421    }
422
423    fn _commit(&mut self) {
424        let mut child = *self.parent.take().expect("cannot commit on root state");
425        mem::swap(&mut child, self);
426
427        // Commit storage.
428        self.store = child
429            .store
430            .take()
431            .map(|cstore| Self::convert_store(cstore.commit()));
432
433        // Propagate messages.
434        self.messages.extend(child.messages);
435
436        // Propagate events.
437        for (key, event) in child.events {
438            let events = self.events.entry(key).or_default();
439            events.extend(event);
440        }
441        for (key, event) in child.unconditional_events {
442            let events = self.unconditional_events.entry(key).or_default();
443            events.extend(event);
444        }
445
446        // Put back per-block values.
447        if let Some(mut block_values) = child.hidden_block_values {
448            mem::swap(&mut block_values, &mut self.block_values); // Block values were hidden.
449        } else {
450            mem::swap(&mut child.block_values, &mut self.block_values);
451        }
452        // Always drop local values.
453
454        // Put back RNG.
455        if child.hidden_rng.is_some() {
456            mem::swap(&mut child.hidden_rng, &mut self.rng); // RNG was hidden.
457        } else {
458            mem::swap(&mut child.rng, &mut self.rng);
459        }
460    }
461
462    /// Rollback the current state and return to its parent state.
463    ///
464    /// # Panics
465    ///
466    /// This method will panic when attempting to rollback the root state.
467    pub fn rollback(&mut self) {
468        let mut child = *self.parent.take().expect("cannot rollback on root state");
469        mem::swap(&mut child, self);
470
471        // Rollback storage.
472        self.store = child
473            .store
474            .take()
475            .map(|cstore| Self::convert_store(cstore.rollback()));
476
477        // Always put back per-block values.
478        if let Some(mut block_values) = child.hidden_block_values {
479            mem::swap(&mut block_values, &mut self.block_values); // Block values were hidden.
480        } else {
481            mem::swap(&mut child.block_values, &mut self.block_values);
482        }
483        // Always drop local values.
484
485        // Always put back RNG.
486        if child.hidden_rng.is_some() {
487            mem::swap(&mut child.hidden_rng, &mut self.rng); // RNG was hidden.
488        } else {
489            mem::swap(&mut child.rng, &mut self.rng);
490        }
491    }
492
493    /// Fetches a block state value entry.
494    ///
495    /// Block values live as long as the root `State` and are propagated to child states. They are
496    /// not affected by state rollbacks. If you need state-scoped values, use local values.
497    pub fn block_value<V: Any>(&mut self, key: &'static str) -> StateValue<'_, V> {
498        StateValue::new(self.block_values.entry(key))
499    }
500
501    /// Fetches a local state value entry.
502    ///
503    /// Local values only live as long as the current `State`, are dropped upon exiting to parent
504    /// state and child states start with an empty set. If you need longer-lived values, use block
505    /// values.
506    pub fn local_value<V: Any>(&mut self, key: &'static str) -> StateValue<'_, V> {
507        StateValue::new(self.local_values.entry(key))
508    }
509
510    /// Hides block values from the current state which will have an empty set of values after this
511    /// method returns. Hidden values will be restored upon exit to parent state.
512    pub fn hide_block_values(&mut self) {
513        if self.parent.is_none() {
514            // Allowing hiding on root state would prevent those values from ever being recovered.
515            panic!("cannot hide block values on root state");
516        }
517        if self.hidden_block_values.is_some() {
518            return; // Parent block values already hidden.
519        }
520
521        self.hidden_block_values = Some(mem::take(&mut self.block_values));
522    }
523
524    /// Emitted messages count returns the number of messages emitted so far across this and all
525    /// parent states.
526    pub fn emitted_messages_count(&self) -> usize {
527        self.messages.len()
528            + self
529                .parent
530                .as_ref()
531                .map(|p| p.emitted_messages_count())
532                .unwrap_or_default()
533    }
534
535    /// Emitted messages count returns the number of messages emitted so far in this state, not
536    /// counting any parent states.
537    pub fn emitted_messages_local_count(&self) -> usize {
538        self.messages.len()
539    }
540
541    /// Maximum number of messages that can be emitted.
542    pub fn emitted_messages_max<C: Context>(&self, ctx: &C) -> u32 {
543        if self.env.is_transaction() {
544            let limit = self.env.tx_auth_info().fee.consensus_messages;
545            if limit > 0 {
546                limit
547            } else {
548                ctx.max_messages() // Zero means an implicit limit by gas use.
549            }
550        } else {
551            ctx.max_messages()
552        }
553    }
554
555    /// Queue a message to be emitted by the runtime for consensus layer to process.
556    pub fn emit_message<C: Context>(
557        &mut self,
558        ctx: &C,
559        msg: roothash::Message,
560        hook: MessageEventHookInvocation,
561    ) -> Result<(), Error> {
562        // Check against maximum number of messages that can be emitted per round.
563        if self.emitted_messages_count() >= self.emitted_messages_max(ctx) as usize {
564            return Err(Error::OutOfMessageSlots);
565        }
566
567        self.messages.push((msg, hook));
568
569        Ok(())
570    }
571
572    /// Take all messages accumulated in the current state.
573    pub fn take_messages(&mut self) -> Vec<(roothash::Message, MessageEventHookInvocation)> {
574        mem::take(&mut self.messages)
575    }
576
577    /// Emit an event.
578    pub fn emit_event<E: Event>(&mut self, event: E) {
579        self.emit_event_raw(event.into_event_tag());
580    }
581
582    /// Emit a raw event.
583    pub fn emit_event_raw(&mut self, etag: EventTag) {
584        let events = self.events.entry(etag.key).or_default();
585        events.push(etag.value);
586    }
587
588    /// Emit an unconditional event.
589    ///
590    /// The only difference to regular events is that these are handled as a separate set.
591    pub fn emit_unconditional_event<E: Event>(&mut self, event: E) {
592        let etag = event.into_event_tag();
593        let events = self.unconditional_events.entry(etag.key).or_default();
594        events.push(etag.value);
595    }
596
597    /// Take all regular events accumulated in the current state.
598    pub fn take_events(&mut self) -> EventTags {
599        mem::take(&mut self.events)
600    }
601
602    /// Take all unconditional events accumulated in the current state.
603    pub fn take_unconditional_events(&mut self) -> EventTags {
604        mem::take(&mut self.unconditional_events)
605    }
606
607    /// Take all events accumulated in the current state and return the merged set.
608    pub fn take_all_events(&mut self) -> EventTags {
609        let mut events = self.take_events();
610        let unconditional_events = self.take_unconditional_events();
611
612        for (key, val) in unconditional_events {
613            let tag = events.entry(key).or_default();
614            tag.extend(val)
615        }
616
617        events
618    }
619
620    /// Store associated with the state.
621    ///
622    /// # Panics
623    ///
624    /// This method will panic if no store exists.
625    pub fn store(&mut self) -> &mut dyn Store {
626        self.store.as_mut().unwrap()
627    }
628
629    /// Whether the store associated with the state has any pending updates.
630    pub fn has_pending_store_updates(&self) -> bool {
631        self.store
632            .as_ref()
633            .map(|store| store.has_pending_updates())
634            .unwrap_or_default()
635    }
636
637    /// Size (in bytes) of any pending updates in the associated store.
638    pub fn pending_store_update_byte_size(&self) -> usize {
639        self.store
640            .as_ref()
641            .map(|store| store.pending_update_byte_size())
642            .unwrap_or_default()
643    }
644
645    /// Random number generator.
646    pub fn rng(&mut self) -> &mut RootRng {
647        self.rng.as_mut().unwrap()
648    }
649
650    /// Disables the RNG by replacing the instance with an invalid RNG.
651    fn disable_rng(&mut self) {
652        if self.parent.is_none() {
653            // Allowing hiding on root state would prevent the RNG from ever being recovered.
654            panic!("cannot hide the RNG on root state");
655        }
656        if self.hidden_rng.is_some() {
657            return; // Parent RNG already hidden.
658        }
659
660        self.hidden_rng = self.rng.replace(RootRng::invalid());
661    }
662
663    /// Environment information.
664    pub fn env(&self) -> &Environment {
665        &self.env
666    }
667
668    /// Origin environment information.
669    ///
670    /// The origin environment is the first non-internal environment in the hierarchy.
671    pub fn env_origin(&self) -> &Environment {
672        match self.parent {
673            Some(ref parent) if self.env.internal => parent.env_origin(),
674            _ => &self.env,
675        }
676    }
677
678    /// Returns the nesting level of the current state.
679    pub fn level(&self) -> usize {
680        if let Some(ref parent) = self.parent {
681            parent.level() + 1
682        } else {
683            0
684        }
685    }
686}
687
688thread_local! {
689    static CURRENT: RefCell<Vec<State>> = const { RefCell::new(Vec::new()) };
690}
691
692struct CurrentStateGuard;
693
694impl Drop for CurrentStateGuard {
695    fn drop(&mut self) {
696        CURRENT.with(|c| {
697            let root = c.borrow_mut().pop().expect("must have current state");
698            // Commit root state as it has been wrapped in an overlay.
699            let store = root
700                .store
701                .expect("must not have open child states after exiting root state");
702            store.commit();
703        });
704    }
705}
706
707struct TransactionGuard(usize);
708
709impl Drop for TransactionGuard {
710    fn drop(&mut self) {
711        let level = CurrentState::with(|state| state.level());
712
713        // If transaction hasn't been either committed or reverted, rollback.
714        if level == self.0 {
715            CurrentState::rollback_transaction();
716        }
717    }
718}
719
720/// Result of a transaction helper closure.
721pub enum TransactionResult<T> {
722    Commit(T),
723    Rollback(T),
724}
725
726impl From<()> for TransactionResult<()> {
727    fn from(_: ()) -> TransactionResult<()> {
728        TransactionResult::Commit(())
729    }
730}
731
732impl<R, E> From<Result<R, E>> for TransactionResult<Result<R, E>> {
733    fn from(v: Result<R, E>) -> TransactionResult<Result<R, E>> {
734        match v {
735            Ok(_) => TransactionResult::Commit(v),
736            Err(_) => TransactionResult::Rollback(v),
737        }
738    }
739}
740
741/// State attached to the current thread.
742pub struct CurrentState;
743
744impl CurrentState {
745    /// Attach a new state to the current thread and enter the state's context.
746    ///
747    /// The passed store is used as the root store.
748    ///
749    /// # Panics
750    ///
751    /// This method will panic if called from within a `CurrentState::with` block.
752    pub fn enter<S, F, R>(root: S, f: F) -> R
753    where
754        S: Store,
755        F: FnOnce() -> R,
756    {
757        Self::enter_opts(
758            Options {
759                mode: Some(Default::default()), // Make sure there is a default mode.
760                ..Options::default()
761            },
762            root,
763            f,
764        )
765    }
766
767    /// Attach a new state to the current thread and enter the state's context.
768    ///
769    /// The passed store is used as the root store.
770    ///
771    /// # Panics
772    ///
773    /// This method will panic if called from within a `CurrentState::with` block or if the mode
774    /// has not been explicitly set in `opts`.
775    pub fn enter_opts<S, F, R>(opts: Options, mut root: S, f: F) -> R
776    where
777        S: Store,
778        F: FnOnce() -> R,
779    {
780        let root = unsafe {
781            // SAFETY: Keeping the root store is safe as it can only be accessed from the current
782            // thread while we are running inside `CurrentState::enter` where we are holding a
783            // mutable reference on it.
784            std::mem::transmute::<&mut dyn Store, &mut (dyn Store + 'static)>(
785                &mut root as &mut dyn Store,
786            )
787        };
788        // Initialize the root state.
789        let mode = opts
790            .mode
791            .expect("mode must be explicitly set on root state");
792        let mut root = State {
793            parent: None,
794            store: Some(OverlayStore::new(Box::new(root) as Box<dyn Store>)),
795            events: EventTags::new(),
796            unconditional_events: EventTags::new(),
797            messages: Vec::new(),
798            block_values: BTreeMap::new(),
799            hidden_block_values: None,
800            local_values: BTreeMap::new(),
801            rng: Some(RootRng::new(mode)),
802            hidden_rng: None,
803            env: Default::default(),
804            always_rollback: false,
805        };
806        // Apply options to allow customization of the root state.
807        root.init(opts);
808
809        CURRENT.with(|c| {
810            c.try_borrow_mut()
811                .expect("must not re-enter from with block")
812                .push(root)
813        });
814        let _guard = CurrentStateGuard; // Ensure current state is popped once we return.
815
816        f()
817    }
818
819    /// Create an empty baseline state for the current thread.
820    ///
821    /// This should only be used in tests to have state always available.
822    ///
823    /// # Panics
824    ///
825    /// This method will panic if any states have been attached to the local thread or if called
826    /// within a `CurrentState::with` block.
827    #[doc(hidden)]
828    pub(crate) fn init_local_fallback() {
829        thread_local! {
830            static BASE_STATE_INIT: RefCell<bool> = const { RefCell::new(false) };
831        }
832
833        BASE_STATE_INIT.with(|initialized| {
834            // Initialize once per thread.
835            if *initialized.borrow() {
836                return;
837            }
838            *initialized.borrow_mut() = true;
839
840            let root = mkvs::OverlayTree::new(
841                mkvs::Tree::builder()
842                    .with_root_type(mkvs::RootType::State)
843                    .build(Box::new(mkvs::sync::NoopReadSyncer)),
844            );
845            let root = MKVSStore::new(root);
846
847            // Initialize the root state.
848            let root = State {
849                parent: None,
850                store: Some(OverlayStore::new(Box::new(root) as Box<dyn Store>)),
851                events: EventTags::new(),
852                unconditional_events: EventTags::new(),
853                messages: Vec::new(),
854                block_values: BTreeMap::new(),
855                hidden_block_values: None,
856                local_values: BTreeMap::new(),
857                rng: Some(RootRng::new(Default::default())),
858                hidden_rng: None,
859                env: Default::default(),
860                always_rollback: false,
861            };
862
863            CURRENT.with(|c| {
864                let mut current = c
865                    .try_borrow_mut()
866                    .expect("must not re-enter from with block");
867                assert!(
868                    current.is_empty(),
869                    "must have no prior states attached to local thread"
870                );
871
872                current.push(root);
873            });
874        });
875    }
876
877    /// Run a closure with the currently active state.
878    ///
879    /// # Panics
880    ///
881    /// This method will panic if called outside `CurrentState::enter` or if any transaction methods
882    /// are called from the closure.
883    pub fn with<F, R>(f: F) -> R
884    where
885        F: FnOnce(&mut State) -> R,
886    {
887        CURRENT.with(|c| {
888            let mut current_ref = c.try_borrow_mut().expect("must not re-enter with");
889            let current = current_ref.last_mut().expect("must enter context");
890
891            f(current)
892        })
893    }
894
895    /// Run a closure with the store of the currently active state.
896    ///
897    /// # Panics
898    ///
899    /// This method will panic if called outside `CurrentState::enter` or if any transaction methods
900    /// are called from the closure.
901    pub fn with_store<F, R>(f: F) -> R
902    where
903        F: FnOnce(&mut dyn Store) -> R,
904    {
905        Self::with(|state| f(state.store()))
906    }
907
908    /// Run a closure with the environment of the currently active state.
909    ///
910    /// # Panics
911    ///
912    /// This method will panic if called outside `CurrentState::enter` or if any transaction methods
913    /// are called from the closure.
914    pub fn with_env<F, R>(f: F) -> R
915    where
916        F: FnOnce(&Environment) -> R,
917    {
918        Self::with(|state| f(state.env()))
919    }
920
921    /// Run a closure with the origin environment of the currently active state.
922    ///
923    /// # Panics
924    ///
925    /// This method will panic if called outside `CurrentState::enter` or if any transaction methods
926    /// are called from the closure.
927    pub fn with_env_origin<F, R>(f: F) -> R
928    where
929        F: FnOnce(&Environment) -> R,
930    {
931        Self::with(|state| f(state.env_origin()))
932    }
933
934    /// Start a new transaction by opening a new child state.
935    ///
936    /// # Panics
937    ///
938    /// This method will panic if called outside `CurrentState::enter` or if called within a
939    /// `CurrentState::with` block.
940    pub fn start_transaction() {
941        Self::with(|state| state.open());
942    }
943
944    /// Commit a previously started transaction.
945    ///
946    /// # Panics
947    ///
948    /// This method will panic if called outside `CurrentState::enter`, if there is no currently
949    /// open transaction (started via `CurrentState::start_transaction`) or if called within a
950    /// `CurrentState::with` block.
951    pub fn commit_transaction() {
952        Self::with(|state| state.commit());
953    }
954
955    /// Rollback a previously started transaction.
956    ///
957    /// # Panics
958    ///
959    /// This method will panic if called outside `CurrentState::enter`, if there is no currently
960    /// open transaction (started via `CurrentState::start_transaction`) or if called within a
961    /// `CurrentState::with` block.
962    pub fn rollback_transaction() {
963        Self::with(|state| state.rollback());
964    }
965
966    /// Run a closure within a state transaction.
967    ///
968    /// If the closure returns `TransactionResult::Commit(R)` then the child state is committed,
969    /// otherwise the child state is rolled back.
970    pub fn with_transaction<F, R, Rs>(f: F) -> R
971    where
972        F: FnOnce() -> Rs,
973        Rs: Into<TransactionResult<R>>,
974    {
975        Self::with_transaction_opts(Options::default(), f)
976    }
977
978    /// Run a closure within a state transaction, allowing the caller to customize state.
979    ///
980    /// If the closure returns `TransactionResult::Commit(R)` then the child state is committed,
981    /// otherwise the child state is rolled back.
982    pub fn with_transaction_opts<F, R, Rs>(opts: Options, f: F) -> R
983    where
984        F: FnOnce() -> Rs,
985        Rs: Into<TransactionResult<R>>,
986    {
987        let level = Self::with(|state| {
988            state.open();
989            state.init(opts);
990            state.level()
991        });
992        let _guard = TransactionGuard(level); // Ensure transaction is always closed.
993
994        match f().into() {
995            TransactionResult::Commit(result) => {
996                Self::commit_transaction();
997                result
998            }
999            TransactionResult::Rollback(result) => {
1000                Self::rollback_transaction();
1001                result
1002            }
1003        }
1004    }
1005}
1006
1007/// A per-state arbitrary value.
1008pub struct StateValue<'a, V> {
1009    inner: Entry<'a, &'static str, Box<dyn Any>>,
1010    _value: PhantomData<V>,
1011}
1012
1013impl<'a, V: Any> StateValue<'a, V> {
1014    fn new(inner: Entry<'a, &'static str, Box<dyn Any>>) -> Self {
1015        Self {
1016            inner,
1017            _value: PhantomData,
1018        }
1019    }
1020
1021    /// Gets a reference to the specified per-state value.
1022    ///
1023    /// # Panics
1024    ///
1025    /// Panics if the retrieved type is not the type that was stored.
1026    pub fn get(self) -> Option<&'a V> {
1027        match self.inner {
1028            Entry::Occupied(oe) => Some(
1029                oe.into_mut()
1030                    .downcast_ref()
1031                    .expect("type should stay the same"),
1032            ),
1033            _ => None,
1034        }
1035    }
1036
1037    /// Gets a mutable reference to the specified per-state value.
1038    ///
1039    /// # Panics
1040    ///
1041    /// Panics if the retrieved type is not the type that was stored.
1042    pub fn get_mut(&mut self) -> Option<&mut V> {
1043        match &mut self.inner {
1044            Entry::Occupied(oe) => Some(
1045                oe.get_mut()
1046                    .downcast_mut()
1047                    .expect("type should stay the same"),
1048            ),
1049            _ => None,
1050        }
1051    }
1052
1053    /// Sets the context value, returning a mutable reference to the set value.
1054    ///
1055    /// # Panics
1056    ///
1057    /// Panics if the retrieved type is not the type that was stored.
1058    pub fn set(self, value: V) -> &'a mut V {
1059        let value = Box::new(value);
1060        match self.inner {
1061            Entry::Occupied(mut oe) => {
1062                oe.insert(value);
1063                oe.into_mut()
1064            }
1065            Entry::Vacant(ve) => ve.insert(value),
1066        }
1067        .downcast_mut()
1068        .expect("type should stay the same")
1069    }
1070
1071    /// Takes the context value, if it exists.
1072    ///
1073    /// # Panics
1074    ///
1075    /// Panics if the retrieved type is not the type that was stored.
1076    pub fn take(self) -> Option<V> {
1077        match self.inner {
1078            Entry::Occupied(oe) => {
1079                Some(*oe.remove().downcast().expect("type should stay the same"))
1080            }
1081            Entry::Vacant(_) => None,
1082        }
1083    }
1084}
1085
1086impl<'a, V: Any + Default> StateValue<'a, V> {
1087    /// Retrieves the existing value or inserts and returns the default.
1088    ///
1089    /// # Panics
1090    ///
1091    /// Panics if the retrieved type is not the type that was stored.
1092    pub fn or_default(self) -> &'a mut V {
1093        match self.inner {
1094            Entry::Occupied(oe) => oe.into_mut(),
1095            Entry::Vacant(ve) => ve.insert(Box::<V>::default()),
1096        }
1097        .downcast_mut()
1098        .expect("type should stay the same")
1099    }
1100}
1101
1102#[cfg(test)]
1103mod test {
1104    use std::sync::Arc;
1105
1106    use oasis_core_runtime::{
1107        common::versioned::Versioned,
1108        consensus::{roothash, staking},
1109        storage::mkvs,
1110    };
1111
1112    use super::{CurrentState, Mode, Options, TransactionInfo, TransactionResult};
1113    use crate::{
1114        modules::core::Event,
1115        storage::{MKVSStore, Store},
1116        testing::mock::{self, Mock},
1117        types::message::MessageEventHookInvocation,
1118    };
1119
1120    #[test]
1121    fn test_value() {
1122        CurrentState::init_local_fallback();
1123
1124        CurrentState::with(|state| {
1125            let x = state.block_value::<u64>("module.TestKey").get();
1126            assert_eq!(x, None);
1127
1128            state.block_value::<u64>("module.TestKey").set(42);
1129
1130            let y = state.block_value::<u64>("module.TestKey").get();
1131            assert_eq!(y, Some(&42u64));
1132
1133            let z = state.block_value::<u64>("module.TestKey").take();
1134            assert_eq!(z, Some(42u64));
1135
1136            let y = state.block_value::<u64>("module.TestKey").get();
1137            assert_eq!(y, None);
1138        });
1139    }
1140
1141    #[test]
1142    #[should_panic]
1143    fn test_value_type_change_block_value() {
1144        CurrentState::init_local_fallback();
1145
1146        CurrentState::with(|state| {
1147            state.block_value::<u64>("module.TestKey").or_default();
1148            state.block_value::<u32>("module.TestKey").get();
1149        });
1150    }
1151
1152    #[test]
1153    #[should_panic]
1154    fn test_value_type_change_local_value() {
1155        CurrentState::init_local_fallback();
1156
1157        CurrentState::with(|state| {
1158            state.local_value::<u64>("module.TestKey").or_default();
1159            state.local_value::<u32>("module.TestKey").get();
1160        });
1161    }
1162
1163    #[test]
1164    fn test_value_hidden_block_values() {
1165        CurrentState::init_local_fallback();
1166
1167        CurrentState::with(|state| {
1168            state.block_value("module.TestKey").set(42u64);
1169
1170            state.open();
1171            state.hide_block_values();
1172
1173            let v = state.block_value::<u64>("module.TestKey").get();
1174            assert!(v.is_none(), "block values should not propagate when hidden");
1175
1176            state.block_value("module.TestKey").set(48u64);
1177
1178            state.commit();
1179
1180            let v = state.block_value::<u64>("module.TestKey").get();
1181            assert_eq!(
1182                v,
1183                Some(&42u64),
1184                "block values should not propagate when hidden"
1185            );
1186        });
1187    }
1188
1189    #[test]
1190    fn test_value_local() {
1191        CurrentState::init_local_fallback();
1192
1193        CurrentState::with(|state| {
1194            state.block_value("module.TestKey").set(42u64);
1195
1196            state.open();
1197
1198            let mut y = state.block_value::<u64>("module.TestKey");
1199            let y = y.get_mut().unwrap();
1200            assert_eq!(*y, 42);
1201            *y = 48;
1202
1203            let a = state.local_value::<u64>("module.TestTxKey").get();
1204            assert_eq!(a, None);
1205            state.local_value::<u64>("module.TestTxKey").set(65);
1206
1207            let b = state.local_value::<u64>("module.TestTxKey").get();
1208            assert_eq!(b, Some(&65));
1209
1210            let c = state
1211                .local_value::<u64>("module.TestTakeTxKey")
1212                .or_default();
1213            *c = 67;
1214            let d = state.local_value::<u64>("module.TestTakeTxKey").take();
1215            assert_eq!(d, Some(67));
1216            let e = state.local_value::<u64>("module.TestTakeTxKey").get();
1217            assert_eq!(e, None);
1218
1219            state.rollback(); // Block values are always propagated.
1220
1221            let x = state.block_value::<u64>("module.TestKey").get();
1222            assert_eq!(x, Some(&48));
1223
1224            state.open();
1225
1226            let z = state.block_value::<u64>("module.TestKey").take();
1227            assert_eq!(z, Some(48));
1228
1229            let a = state.local_value::<u64>("module.TestTxKey").get();
1230            assert_eq!(a, None, "local values should not be propagated");
1231
1232            state.rollback(); // Block values are always propagated.
1233
1234            let y = state.block_value::<u64>("module.TestKey").get();
1235            assert_eq!(y, None);
1236        });
1237    }
1238
1239    #[test]
1240    fn test_emit_messages() {
1241        let mut mock = Mock::default(); // Also creates local fallback state.
1242        let max_messages = mock.max_messages as usize;
1243        let ctx = mock.create_ctx();
1244
1245        CurrentState::with(|state| {
1246            state.open();
1247
1248            assert_eq!(state.emitted_messages_count(), 0);
1249            assert_eq!(state.emitted_messages_local_count(), 0);
1250
1251            state
1252                .emit_message(
1253                    &ctx,
1254                    roothash::Message::Staking(Versioned::new(
1255                        0,
1256                        roothash::StakingMessage::Transfer(staking::Transfer::default()),
1257                    )),
1258                    MessageEventHookInvocation::new("test".to_string(), ""),
1259                )
1260                .expect("message emission should succeed");
1261            assert_eq!(state.emitted_messages_count(), 1);
1262            assert_eq!(state.emitted_messages_local_count(), 1);
1263            assert_eq!(state.emitted_messages_max(&ctx), max_messages as u32);
1264
1265            state.open(); // Start child state.
1266
1267            assert_eq!(state.emitted_messages_local_count(), 0);
1268
1269            state
1270                .emit_message(
1271                    &ctx,
1272                    roothash::Message::Staking(Versioned::new(
1273                        0,
1274                        roothash::StakingMessage::Transfer(staking::Transfer::default()),
1275                    )),
1276                    MessageEventHookInvocation::new("test".to_string(), ""),
1277                )
1278                .expect("message emission should succeed");
1279            assert_eq!(state.emitted_messages_count(), 2);
1280            assert_eq!(state.emitted_messages_local_count(), 1);
1281            assert_eq!(state.emitted_messages_max(&ctx), max_messages as u32);
1282
1283            state.rollback(); // Rollback.
1284
1285            assert_eq!(
1286                state.emitted_messages_count(),
1287                1,
1288                "emitted message should have been rolled back"
1289            );
1290            assert_eq!(state.emitted_messages_local_count(), 1);
1291
1292            state.open(); // Start child state.
1293
1294            assert_eq!(state.emitted_messages_local_count(), 0);
1295
1296            state
1297                .emit_message(
1298                    &ctx,
1299                    roothash::Message::Staking(Versioned::new(
1300                        0,
1301                        roothash::StakingMessage::Transfer(staking::Transfer::default()),
1302                    )),
1303                    MessageEventHookInvocation::new("test".to_string(), ""),
1304                )
1305                .expect("message emission should succeed");
1306            assert_eq!(state.emitted_messages_count(), 2);
1307            assert_eq!(state.emitted_messages_local_count(), 1);
1308
1309            state.commit(); // Commit.
1310
1311            assert_eq!(
1312                state.emitted_messages_count(),
1313                2,
1314                "emitted message should have been committed"
1315            );
1316
1317            // Emit some more messages.
1318            for _ in 0..max_messages - 2 {
1319                state
1320                    .emit_message(
1321                        &ctx,
1322                        roothash::Message::Staking(Versioned::new(
1323                            0,
1324                            roothash::StakingMessage::Transfer(staking::Transfer::default()),
1325                        )),
1326                        MessageEventHookInvocation::new("test".to_string(), ""),
1327                    )
1328                    .expect("message emission should succeed");
1329            }
1330            assert_eq!(state.emitted_messages_count(), max_messages);
1331
1332            // Emitting one more message should be rejected.
1333            state
1334                .emit_message(
1335                    &ctx,
1336                    roothash::Message::Staking(Versioned::new(
1337                        0,
1338                        roothash::StakingMessage::Transfer(staking::Transfer::default()),
1339                    )),
1340                    MessageEventHookInvocation::new("test".to_string(), ""),
1341                )
1342                .expect_err("message emission should fail due to out of slots");
1343            assert_eq!(state.emitted_messages_count(), max_messages);
1344
1345            state.rollback(); // Rollback.
1346
1347            assert_eq!(state.emitted_messages_count(), 0);
1348        });
1349
1350        // Change the maximum amount of messages.
1351        let mut tx = mock::transaction();
1352        tx.auth_info.fee.consensus_messages = 1; // Limit amount of messages.
1353        CurrentState::with_transaction_opts(Options::new().with_tx(tx.into()), || {
1354            CurrentState::with(|state| {
1355                assert_eq!(state.emitted_messages_max(&ctx), 1);
1356            });
1357        });
1358
1359        let mut tx = mock::transaction();
1360        tx.auth_info.fee.consensus_messages = 0; // Zero means an implicit limit by gas use.
1361        CurrentState::with_transaction_opts(Options::new().with_tx(tx.into()), || {
1362            CurrentState::with(|state| {
1363                assert_eq!(state.emitted_messages_max(&ctx), max_messages as u32);
1364            });
1365        });
1366    }
1367
1368    #[test]
1369    fn test_emit_events() {
1370        CurrentState::init_local_fallback();
1371
1372        CurrentState::with(|state| {
1373            state.open();
1374
1375            state.open();
1376
1377            state.emit_event(Event::GasUsed { amount: 41 });
1378            state.emit_event(Event::GasUsed { amount: 42 });
1379            state.emit_event(Event::GasUsed { amount: 43 });
1380
1381            state.emit_unconditional_event(Event::GasUsed { amount: 10 });
1382
1383            state.commit();
1384
1385            let events = state.take_events();
1386            assert_eq!(events.len(), 1, "events should have been propagated");
1387            let event_key = b"core\x00\x00\x00\x01".to_vec();
1388            assert_eq!(events[&event_key].len(), 3);
1389
1390            let events = state.take_unconditional_events();
1391            assert_eq!(
1392                events.len(),
1393                1,
1394                "unconditional events should have been propagated"
1395            );
1396            let event_key = b"core\x00\x00\x00\x01".to_vec();
1397            assert_eq!(events[&event_key].len(), 1);
1398
1399            state.emit_event(Event::GasUsed { amount: 41 });
1400            state.emit_event(Event::GasUsed { amount: 42 });
1401            state.emit_event(Event::GasUsed { amount: 43 });
1402
1403            state.emit_unconditional_event(Event::GasUsed { amount: 20 });
1404
1405            state.rollback();
1406
1407            let events = state.take_events();
1408            assert_eq!(events.len(), 0, "events should not have been propagated");
1409
1410            let events = state.take_unconditional_events();
1411            assert_eq!(
1412                events.len(),
1413                0,
1414                "unconditional events should not have been propagated"
1415            );
1416        });
1417    }
1418
1419    fn test_store_basic() {
1420        CurrentState::start_transaction();
1421
1422        assert!(
1423            !CurrentState::with(|state| state.has_pending_store_updates()),
1424            "should not have pending updates"
1425        );
1426
1427        CurrentState::with_store(|store| {
1428            store.insert(b"test", b"value");
1429        });
1430
1431        assert!(
1432            CurrentState::with(|state| state.has_pending_store_updates()),
1433            "should have pending updates after insert"
1434        );
1435
1436        // Transaction helper.
1437        CurrentState::with_transaction(|| {
1438            assert!(
1439                !CurrentState::with(|state| state.has_pending_store_updates()),
1440                "should not have pending updates"
1441            );
1442
1443            CurrentState::with_store(|store| {
1444                store.insert(b"test", b"b0rken");
1445            });
1446
1447            assert!(
1448                CurrentState::with(|state| state.has_pending_store_updates()),
1449                "should have pending updates after insert"
1450            );
1451
1452            TransactionResult::Rollback(())
1453        });
1454
1455        // Transaction helper with options.
1456        CurrentState::with_transaction_opts(
1457            Options::new()
1458                .with_mode(Mode::Check)
1459                .with_internal(true)
1460                .with_tx(Arc::new(TransactionInfo {
1461                    size: 888,
1462                    index: 42,
1463                    ..TransactionInfo::internal(mock::transaction()).0
1464                })),
1465            || {
1466                CurrentState::with_env(|env| {
1467                    assert!(env.is_check_only(), "environment should be updated");
1468                    assert!(env.is_internal(), "environment should be updated");
1469                    assert!(env.is_transaction(), "environment should be updated");
1470                    assert_eq!(env.tx_index(), 42, "environment should be updated");
1471                    assert_eq!(env.tx_size(), 888, "environment should be updated");
1472                });
1473
1474                CurrentState::with_env_origin(|env_origin| {
1475                    assert!(
1476                        !env_origin.is_check_only(),
1477                        "origin environment should be correct"
1478                    );
1479                    assert!(
1480                        !env_origin.is_transaction(),
1481                        "origin environment should be correct"
1482                    );
1483                });
1484
1485                CurrentState::with_transaction(|| {
1486                    // Check environment propagation.
1487                    CurrentState::with_env(|env| {
1488                        assert!(env.is_check_only(), "environment should propagate");
1489                        assert!(env.is_internal(), "environment should propagate");
1490                        assert!(env.is_transaction(), "environment should propagate");
1491                        assert_eq!(env.tx_index(), 42, "environment should propagate");
1492                        assert_eq!(env.tx_size(), 888, "environment should propagate");
1493                    });
1494
1495                    TransactionResult::Rollback(())
1496                });
1497
1498                TransactionResult::Rollback(())
1499            },
1500        );
1501
1502        CurrentState::with_env(|env| {
1503            assert!(!env.is_transaction(), "environment should not leak");
1504        });
1505
1506        // Nested entering, but with a different store.
1507        let unrelated = mkvs::OverlayTree::new(
1508            mkvs::Tree::builder()
1509                .with_root_type(mkvs::RootType::State)
1510                .build(Box::new(mkvs::sync::NoopReadSyncer)),
1511        );
1512        let mut unrelated = MKVSStore::new(unrelated);
1513
1514        CurrentState::enter(&mut unrelated, || {
1515            CurrentState::start_transaction();
1516
1517            CurrentState::with_store(|store| {
1518                store.insert(b"test", b"should not touch the original root");
1519            });
1520
1521            CurrentState::commit_transaction();
1522        });
1523
1524        CurrentState::with_store(|store| {
1525            store.insert(b"another", b"value 2");
1526        });
1527
1528        CurrentState::commit_transaction();
1529    }
1530
1531    #[test]
1532    fn test_basic() {
1533        let root = mkvs::OverlayTree::new(
1534            mkvs::Tree::builder()
1535                .with_root_type(mkvs::RootType::State)
1536                .build(Box::new(mkvs::sync::NoopReadSyncer)),
1537        );
1538        let mut root = MKVSStore::new(root);
1539
1540        CurrentState::enter(&mut root, || {
1541            test_store_basic();
1542        });
1543
1544        let value = root.get(b"test").unwrap();
1545        assert_eq!(value, b"value");
1546    }
1547
1548    #[test]
1549    fn test_local_fallback() {
1550        // Initialize the local fallback store.
1551        CurrentState::init_local_fallback();
1552        CurrentState::init_local_fallback(); // Should be no-op.
1553
1554        // Test the basic store -- note, no need to enter as fallback current store is available.
1555        test_store_basic();
1556
1557        CurrentState::with_store(|store| {
1558            let value = store.get(b"test").unwrap();
1559            assert_eq!(value, b"value");
1560        });
1561
1562        // It should be possible to override the fallback by entering explicitly.
1563        let root = mkvs::OverlayTree::new(
1564            mkvs::Tree::builder()
1565                .with_root_type(mkvs::RootType::State)
1566                .build(Box::new(mkvs::sync::NoopReadSyncer)),
1567        );
1568        let mut root = MKVSStore::new(root);
1569
1570        CurrentState::enter(&mut root, || {
1571            CurrentState::with_store(|store| {
1572                assert!(store.get(b"test").is_none(), "store should be empty");
1573                store.insert(b"unrelated", b"unrelated");
1574            });
1575
1576            test_store_basic();
1577        });
1578
1579        let value = root.get(b"test").unwrap();
1580        assert_eq!(value, b"value");
1581        let value = root.get(b"unrelated").unwrap();
1582        assert_eq!(value, b"unrelated");
1583
1584        // Changes should not leak to fallback store.
1585        CurrentState::with_store(|store| {
1586            assert!(store.get(b"unrelated").is_none(), "changes should not leak");
1587        });
1588    }
1589
1590    #[test]
1591    #[should_panic(expected = "must enter context")]
1592    fn test_fail_not_entered() {
1593        test_store_basic(); // Should panic due to no current store being available.
1594    }
1595
1596    #[test]
1597    #[should_panic(expected = "must not re-enter with")]
1598    fn test_fail_reenter_with() {
1599        CurrentState::init_local_fallback();
1600
1601        CurrentState::with(|_| {
1602            CurrentState::with(|_| {
1603                // Should panic.
1604            });
1605        });
1606    }
1607
1608    #[test]
1609    #[should_panic(expected = "must not re-enter with")]
1610    fn test_fail_reenter_with_start_transaction() {
1611        CurrentState::init_local_fallback();
1612
1613        CurrentState::with(|_| {
1614            CurrentState::start_transaction(); // Should panic.
1615        });
1616    }
1617
1618    #[test]
1619    #[should_panic(expected = "must not re-enter with")]
1620    fn test_fail_reenter_with_commit_transaction() {
1621        CurrentState::init_local_fallback();
1622
1623        CurrentState::with(|_| {
1624            CurrentState::commit_transaction(); // Should panic.
1625        });
1626    }
1627
1628    #[test]
1629    #[should_panic(expected = "must not re-enter with")]
1630    fn test_fail_reenter_with_rollback_transaction() {
1631        CurrentState::init_local_fallback();
1632
1633        CurrentState::with(|_| {
1634            CurrentState::rollback_transaction(); // Should panic.
1635        });
1636    }
1637
1638    #[test]
1639    #[should_panic(expected = "must not re-enter from with block")]
1640    fn test_fail_reenter_with_enter() {
1641        CurrentState::init_local_fallback();
1642
1643        CurrentState::with(|_| {
1644            let unrelated = mkvs::OverlayTree::new(
1645                mkvs::Tree::builder()
1646                    .with_root_type(mkvs::RootType::State)
1647                    .build(Box::new(mkvs::sync::NoopReadSyncer)),
1648            );
1649            let mut unrelated = MKVSStore::new(unrelated);
1650
1651            CurrentState::enter(&mut unrelated, || {
1652                // Should panic.
1653            });
1654        });
1655    }
1656
1657    #[test]
1658    #[should_panic(expected = "must not re-enter from with block")]
1659    fn test_fail_local_fallback_within_with() {
1660        let root = mkvs::OverlayTree::new(
1661            mkvs::Tree::builder()
1662                .with_root_type(mkvs::RootType::State)
1663                .build(Box::new(mkvs::sync::NoopReadSyncer)),
1664        );
1665        let mut root = MKVSStore::new(root);
1666
1667        CurrentState::enter(&mut root, || {
1668            CurrentState::with(|_| {
1669                CurrentState::init_local_fallback(); // Should panic.
1670            })
1671        });
1672    }
1673
1674    #[test]
1675    #[should_panic(expected = "must have no prior states attached to local thread")]
1676    fn test_fail_local_fallback_within_enter() {
1677        let root = mkvs::OverlayTree::new(
1678            mkvs::Tree::builder()
1679                .with_root_type(mkvs::RootType::State)
1680                .build(Box::new(mkvs::sync::NoopReadSyncer)),
1681        );
1682        let mut root = MKVSStore::new(root);
1683
1684        CurrentState::enter(&mut root, || {
1685            CurrentState::init_local_fallback(); // Should panic.
1686        });
1687    }
1688
1689    #[test]
1690    #[should_panic(expected = "cannot commit on root state")]
1691    fn test_fail_commit_transaction_must_exist() {
1692        CurrentState::init_local_fallback();
1693
1694        CurrentState::commit_transaction(); // Should panic.
1695    }
1696
1697    #[test]
1698    #[should_panic(expected = "cannot rollback on root state")]
1699    fn test_fail_rollback_transaction_must_exist() {
1700        CurrentState::init_local_fallback();
1701
1702        CurrentState::rollback_transaction(); // Should panic.
1703    }
1704}