Skip to content

Commit

Permalink
runtime: Add beacon::MutableState for easier testing
Browse files Browse the repository at this point in the history
  • Loading branch information
kostko committed Sep 5, 2022
1 parent 8cd3594 commit d2e2788
Showing 1 changed file with 80 additions and 1 deletion.
81 changes: 80 additions & 1 deletion runtime/src/consensus/state/beacon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use crate::{
state::StateError,
},
key_format,
storage::mkvs::ImmutableMKVS,
storage::mkvs::{FallibleMKVS, ImmutableMKVS},
};

/// Consensus beacon state wrapper.
Expand Down Expand Up @@ -65,6 +65,39 @@ impl<'a, T: ImmutableMKVS> ImmutableState<'a, T> {
}
}

/// Mutable consensus beacon state wrapper.
pub struct MutableState;

impl MutableState {
/// Set current epoch state.
pub fn set_epoch_state<S: FallibleMKVS>(
mkvs: &mut S,
ctx: Context,
epoch_state: EpochTimeState,
) -> Result<(), StateError> {
mkvs.insert(
ctx,
&CurrentEpochKeyFmt(()).encode(),
&cbor::to_vec(epoch_state),
)?;
Ok(())
}

/// Set future epoch state.
pub fn set_future_epoch_state<S: FallibleMKVS>(
mkvs: &mut S,
ctx: Context,
epoch_state: EpochTimeState,
) -> Result<(), StateError> {
mkvs.insert(
ctx,
&FutureEpochKeyFmt(()).encode(),
&cbor::to_vec(epoch_state),
)?;
Ok(())
}
}

#[cfg(test)]
mod test {
use std::sync::Arc;
Expand All @@ -73,12 +106,58 @@ mod test {
common::crypto::hash::Hash,
storage::mkvs::{
interop::{Fixture, ProtocolServer},
sync::NoopReadSyncer,
Root, RootType, Tree,
},
};

use super::*;

#[test]
fn test_mutable_state() {
let mut mkvs = Tree::builder()
.with_root_type(RootType::State)
.build(Box::new(NoopReadSyncer));

let ctx = Arc::new(Context::background());

MutableState::set_epoch_state(
&mut mkvs,
Context::create_child(&ctx),
EpochTimeState {
epoch: 10,
height: 100,
},
)
.unwrap();

MutableState::set_future_epoch_state(
&mut mkvs,
Context::create_child(&ctx),
EpochTimeState {
epoch: 11,
height: 110,
},
)
.unwrap();

let beacon_state = ImmutableState::new(&mkvs);

// Test current epoch state.
let epoch_state = beacon_state
.epoch_state(Context::create_child(&ctx))
.expect("epoch state query should work");
assert_eq!(10u64, epoch_state.epoch, "expected epoch should match");
assert_eq!(100i64, epoch_state.height, "expected height should match");

// Test future epoch state.
let epoch_state = beacon_state
.future_epoch_state(Context::create_child(&ctx))
.expect("future epoch state query should work");
assert_eq!(11u64, epoch_state.epoch, "expected epoch should match");
assert_eq!(110i64, epoch_state.height, "expected height should match");
}

#[test]
fn test_beacon_state_interop() {
// Keep in sync with go/consensus/tendermint/apps/beacon/state/interop/interop.go.
Expand Down

0 comments on commit d2e2788

Please sign in to comment.