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#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)]
24#[repr(u8)]
25pub enum Mode {
26 #[default]
28 Execute,
29 Check,
31 Simulate,
33 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#[derive(Clone, Default, Debug)]
61pub struct Environment {
62 mode: Mode,
63 tx: Option<Arc<TransactionInfo>>,
64 internal: bool,
65}
66
67impl Environment {
68 pub fn mode(&self) -> Mode {
70 self.mode
71 }
72
73 pub fn is_check_only(&self) -> bool {
75 matches!(self.mode, Mode::Check | Mode::PreSchedule)
76 }
77
78 pub fn is_pre_schedule(&self) -> bool {
80 matches!(self.mode, Mode::PreSchedule)
81 }
82
83 pub fn is_simulation(&self) -> bool {
85 matches!(self.mode, Mode::Simulate)
86 }
87
88 pub fn is_execute(&self) -> bool {
90 matches!(self.mode, Mode::Execute)
91 }
92
93 pub fn is_transaction(&self) -> bool {
95 self.tx.is_some()
96 }
97
98 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 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 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 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 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 pub fn is_internal(&self) -> bool {
160 self.internal
161 }
162
163 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 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#[derive(Clone, Debug)]
201pub struct TransactionInfo {
202 pub auth_info: transaction::AuthInfo,
204 pub call_format: transaction::CallFormat,
206 pub read_only: bool,
208 pub size: u32,
210 pub index: usize,
212 pub hash: Hash,
214}
215
216impl TransactionInfo {
217 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 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) }
249}
250
251#[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 pub fn new() -> Self {
263 Self::default()
264 }
265
266 pub fn with_mode(self, mode: Mode) -> Self {
268 Self {
269 mode: Some(mode),
270 ..self
271 }
272 }
273
274 pub fn with_tx(self, tx: Arc<TransactionInfo>) -> Self {
276 Self {
277 tx: Some(tx),
278 ..self
279 }
280 }
281
282 pub fn with_internal(self, internal: bool) -> Self {
284 Self {
285 internal: Some(internal),
286 ..self
287 }
288 }
289
290 pub fn with_rng_local_entropy(self) -> Self {
298 Self {
299 rng_local_entropy: true,
300 ..self
301 }
302 }
303}
304
305pub 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 fn init(&mut self, opts: Options) {
331 if let Some(mode) = opts.mode {
332 self.env.mode = mode;
334 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 self.rng.as_mut().unwrap().append_tx(tx.hash);
345 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 self.rng.as_mut().unwrap().append_local_entropy();
359 }
360
361 if !matches!(self.env.mode, Mode::PreSchedule) {
362 self.rng.as_mut().unwrap().append_subcontext();
364 } else {
365 self.disable_rng();
367 }
368 }
369
370 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 self.store = parent
390 .store
391 .take()
392 .map(|pstore| OverlayStore::new(Box::new(pstore) as Box<dyn Store>));
393
394 mem::swap(&mut parent.block_values, &mut self.block_values);
396 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 *Box::from_raw(raw as *mut OverlayStore<Box<dyn Store>>)
407 }
408 }
409
410 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 self.store = child
429 .store
430 .take()
431 .map(|cstore| Self::convert_store(cstore.commit()));
432
433 self.messages.extend(child.messages);
435
436 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 if let Some(mut block_values) = child.hidden_block_values {
448 mem::swap(&mut block_values, &mut self.block_values); } else {
450 mem::swap(&mut child.block_values, &mut self.block_values);
451 }
452 if child.hidden_rng.is_some() {
456 mem::swap(&mut child.hidden_rng, &mut self.rng); } else {
458 mem::swap(&mut child.rng, &mut self.rng);
459 }
460 }
461
462 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 self.store = child
473 .store
474 .take()
475 .map(|cstore| Self::convert_store(cstore.rollback()));
476
477 if let Some(mut block_values) = child.hidden_block_values {
479 mem::swap(&mut block_values, &mut self.block_values); } else {
481 mem::swap(&mut child.block_values, &mut self.block_values);
482 }
483 if child.hidden_rng.is_some() {
487 mem::swap(&mut child.hidden_rng, &mut self.rng); } else {
489 mem::swap(&mut child.rng, &mut self.rng);
490 }
491 }
492
493 pub fn block_value<V: Any>(&mut self, key: &'static str) -> StateValue<'_, V> {
498 StateValue::new(self.block_values.entry(key))
499 }
500
501 pub fn local_value<V: Any>(&mut self, key: &'static str) -> StateValue<'_, V> {
507 StateValue::new(self.local_values.entry(key))
508 }
509
510 pub fn hide_block_values(&mut self) {
513 if self.parent.is_none() {
514 panic!("cannot hide block values on root state");
516 }
517 if self.hidden_block_values.is_some() {
518 return; }
520
521 self.hidden_block_values = Some(mem::take(&mut self.block_values));
522 }
523
524 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 pub fn emitted_messages_local_count(&self) -> usize {
538 self.messages.len()
539 }
540
541 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() }
550 } else {
551 ctx.max_messages()
552 }
553 }
554
555 pub fn emit_message<C: Context>(
557 &mut self,
558 ctx: &C,
559 msg: roothash::Message,
560 hook: MessageEventHookInvocation,
561 ) -> Result<(), Error> {
562 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 pub fn take_messages(&mut self) -> Vec<(roothash::Message, MessageEventHookInvocation)> {
574 mem::take(&mut self.messages)
575 }
576
577 pub fn emit_event<E: Event>(&mut self, event: E) {
579 self.emit_event_raw(event.into_event_tag());
580 }
581
582 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 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 pub fn take_events(&mut self) -> EventTags {
599 mem::take(&mut self.events)
600 }
601
602 pub fn take_unconditional_events(&mut self) -> EventTags {
604 mem::take(&mut self.unconditional_events)
605 }
606
607 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 pub fn store(&mut self) -> &mut dyn Store {
626 self.store.as_mut().unwrap()
627 }
628
629 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 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 pub fn rng(&mut self) -> &mut RootRng {
647 self.rng.as_mut().unwrap()
648 }
649
650 fn disable_rng(&mut self) {
652 if self.parent.is_none() {
653 panic!("cannot hide the RNG on root state");
655 }
656 if self.hidden_rng.is_some() {
657 return; }
659
660 self.hidden_rng = self.rng.replace(RootRng::invalid());
661 }
662
663 pub fn env(&self) -> &Environment {
665 &self.env
666 }
667
668 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 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 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 level == self.0 {
715 CurrentState::rollback_transaction();
716 }
717 }
718}
719
720pub 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
741pub struct CurrentState;
743
744impl CurrentState {
745 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()), ..Options::default()
761 },
762 root,
763 f,
764 )
765 }
766
767 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 std::mem::transmute::<&mut dyn Store, &mut (dyn Store + 'static)>(
785 &mut root as &mut dyn Store,
786 )
787 };
788 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 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; f()
817 }
818
819 #[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 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 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 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 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 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 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 pub fn start_transaction() {
941 Self::with(|state| state.open());
942 }
943
944 pub fn commit_transaction() {
952 Self::with(|state| state.commit());
953 }
954
955 pub fn rollback_transaction() {
963 Self::with(|state| state.rollback());
964 }
965
966 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 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); 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
1007pub 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 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 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 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 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 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(); 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(); 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(); 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(); 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(); 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(); 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(); assert_eq!(
1312 state.emitted_messages_count(),
1313 2,
1314 "emitted message should have been committed"
1315 );
1316
1317 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 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(); assert_eq!(state.emitted_messages_count(), 0);
1348 });
1349
1350 let mut tx = mock::transaction();
1352 tx.auth_info.fee.consensus_messages = 1; 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; 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 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 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 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 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 CurrentState::init_local_fallback();
1552 CurrentState::init_local_fallback(); 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 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 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(); }
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 });
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(); });
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(); });
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(); });
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 });
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(); })
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(); });
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(); }
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(); }
1704}