use std::sync::Arc;
use anyhow::{Error, Result};
use thiserror::Error;
use crate::{
protocol::Protocol,
storage::mkvs::{sync::HostReadSyncer, ImmutableMKVS, Root, Tree},
types::{self, HostStorageEndpoint},
};
pub mod beacon;
pub mod keymanager;
pub mod registry;
pub mod roothash;
pub mod staking;
#[derive(Error, Debug)]
pub enum StateError {
#[error("consensus state: unavailable/corrupted state: {0}")]
Unavailable(#[from] Error),
}
impl From<StateError> for types::Error {
fn from(e: StateError) -> Self {
Self {
module: "consensus".to_string(),
code: 1,
message: e.to_string(),
}
}
}
pub struct ConsensusState {
height: u64,
mkvs: Tree,
}
impl ConsensusState {
pub fn new(height: u64, tree: Tree) -> Self {
Self { height, mkvs: tree }
}
pub fn from_protocol(protocol: Arc<Protocol>, height: u64, root: Root) -> Self {
let read_syncer = HostReadSyncer::new(protocol, HostStorageEndpoint::Consensus);
Self {
height,
mkvs: Tree::builder()
.with_capacity(100_000, 10_000_000)
.with_root(root)
.build(Box::new(read_syncer)),
}
}
pub fn height(&self) -> u64 {
self.height
}
}
impl ImmutableMKVS for ConsensusState {
fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>> {
self.mkvs.get(key)
}
fn get_proof(&self, key: &[u8]) -> Result<Option<crate::storage::mkvs::sync::Proof>> {
self.mkvs.get_proof(key)
}
fn prefetch_prefixes(
&self,
prefixes: &[crate::storage::mkvs::Prefix],
limit: u16,
) -> Result<()> {
self.mkvs.prefetch_prefixes(prefixes, limit)
}
fn iter(&self) -> Box<dyn crate::storage::mkvs::Iterator + '_> {
Box::new(self.mkvs.iter())
}
}
impl ImmutableMKVS for &ConsensusState {
fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>> {
self.mkvs.get(key)
}
fn get_proof(&self, key: &[u8]) -> Result<Option<crate::storage::mkvs::sync::Proof>> {
self.mkvs.get_proof(key)
}
fn prefetch_prefixes(
&self,
prefixes: &[crate::storage::mkvs::Prefix],
limit: u16,
) -> Result<()> {
self.mkvs.prefetch_prefixes(prefixes, limit)
}
fn iter(&self) -> Box<dyn crate::storage::mkvs::Iterator + '_> {
Box::new(self.mkvs.iter())
}
}