Skip to content

Commit

Permalink
State Machine Manager (#79)
Browse files Browse the repository at this point in the history
Co-authored-by: David Salami <[email protected]>
  • Loading branch information
dharjeezy and Wizdave97 authored Jan 24, 2024
1 parent ed40dd6 commit 8009dd1
Show file tree
Hide file tree
Showing 18 changed files with 714 additions and 1,357 deletions.
1,766 changes: 456 additions & 1,310 deletions Cargo.lock

Large diffs are not rendered by default.

9 changes: 6 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,14 @@ members = [
"parachain/modules/consensus/geth-primitives",

"parachain/modules/consensus/bnb-pos/verifier",
"parachain/modules/consensus/bnb-pos/prover", "parachain/modules/ismp/bnb-pos",
"parachain/modules/consensus/bnb-pos/prover",
"parachain/modules/ismp/bnb-pos",
"parachain/modules/state-machine-manager",

# evm stuff
"evm/integration-tests",
"evm/abi", "parachain/modules/relayer-fees",
"evm/integration-tests",
"evm/abi",
"parachain/modules/relayer-fees",
]

# Config for 'cargo dist'
Expand Down
1 change: 0 additions & 1 deletion evm/src/HandlerV1.sol
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ contract HandlerV1 is IHandler, Context {
*/
function handleConsensus(IIsmpHost host, bytes memory proof) external notFrozen(host) {
uint256 delay = host.timestamp() - host.consensusUpdateTime();
require(delay > host.challengePeriod(), "IHandler: still in challenge period");

// not today, time traveling validators
require(delay < host.unStakingPeriod() || _msgSender() == host.admin(), "IHandler: still in challenge period");
Expand Down
6 changes: 3 additions & 3 deletions parachain/modules/ismp/core/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
//! ISMP error definitions

use crate::{
consensus::{ConsensusClientId, ConsensusStateId, StateMachineHeight},
consensus::{ConsensusClientId, ConsensusStateId, StateMachineHeight, StateMachineId},
host::StateMachine,
};
use alloc::{string::String, vec::Vec};
Expand Down Expand Up @@ -58,8 +58,8 @@ pub enum Error {
},
/// The given state machine has been frozen
FrozenStateMachine {
/// The given state machine height
height: StateMachineHeight,
/// The given state machine id
id: StateMachineId,
},
/// The given request was not found
RequestCommitmentNotFound {
Expand Down
2 changes: 1 addition & 1 deletion parachain/modules/ismp/core/src/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ where
host.is_consensus_client_frozen(proof_height.id.consensus_state_id)?;

// Ensure state machine is not frozen
host.is_state_machine_frozen(proof_height)?;
host.is_state_machine_frozen(proof_height.id)?;

// Ensure delay period has elapsed
if !verify_delay_passed(host, &proof_height)? {
Expand Down
2 changes: 1 addition & 1 deletion parachain/modules/ismp/core/src/handlers/consensus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ where
for commitment_height in commitment_heights.iter() {
let state_height = StateMachineHeight { id, height: commitment_height.height };
// If a state machine is frozen, we skip it
if host.is_state_machine_frozen(state_height).is_err() {
if host.is_state_machine_frozen(id).is_err() {
continue;
}

Expand Down
9 changes: 6 additions & 3 deletions parachain/modules/ismp/core/src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,9 @@ pub trait IsmpHost: Keccak256 {
/// Should return the current timestamp on the host
fn timestamp(&self) -> Duration;

/// Checks if a state machine is frozen at the provided height, should return Ok(()) if it isn't
/// Checks if a state machine is frozen, should return Ok(()) if it isn't
/// or [`Error::FrozenStateMachine`] if it is.
fn is_state_machine_frozen(&self, machine: StateMachineHeight) -> Result<(), Error>;
fn is_state_machine_frozen(&self, machine: StateMachineId) -> Result<(), Error>;

/// Checks if a consensus state is frozen
fn is_consensus_client_frozen(&self, consensus_state_id: ConsensusStateId)
Expand Down Expand Up @@ -141,7 +141,10 @@ pub trait IsmpHost: Keccak256 {
) -> Result<(), Error>;

/// Freeze a state machine at the given height
fn freeze_state_machine(&self, height: StateMachineHeight) -> Result<(), Error>;
fn freeze_state_machine(&self, state_machine: StateMachineId) -> Result<(), Error>;

/// UnFreeze a state machine at the given height
fn unfreeze_state_machine(&self, state_machine: StateMachineId) -> Result<(), Error>;

/// Freeze a consensus state with the given identifier
fn freeze_consensus_client(&self, consensus_state_id: ConsensusStateId) -> Result<(), Error>;
Expand Down
7 changes: 3 additions & 4 deletions parachain/modules/ismp/pallet/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
//! Ismp Errors conversions
use codec::{Decode, Encode};
use ismp::{
consensus::{ConsensusClientId, StateMachineHeight},
consensus::{ConsensusClientId, StateMachineHeight, StateMachineId},
error::Error as IsmpError,
host::StateMachine,
module::DispatchResult,
Expand All @@ -42,7 +42,7 @@ pub enum HandlingError {
id: ConsensusClientId,
},
FrozenStateMachine {
height: StateMachineHeight,
id: StateMachineId,
},
RequestCommitmentNotFound {
nonce: u64,
Expand Down Expand Up @@ -123,8 +123,7 @@ impl From<ismp::error::Error> for HandlingError {
HandlingError::StateCommitmentNotFound { height },
IsmpError::FrozenConsensusClient { consensus_state_id } =>
HandlingError::FrozenConsensusClient { id: consensus_state_id },
IsmpError::FrozenStateMachine { height } =>
HandlingError::FrozenStateMachine { height },
IsmpError::FrozenStateMachine { id } => HandlingError::FrozenStateMachine { id },
IsmpError::RequestCommitmentNotFound { nonce, source, dest } =>
HandlingError::RequestCommitmentNotFound { nonce, source, dest },
IsmpError::RequestVerificationFailed { nonce, source, dest } =>
Expand Down
21 changes: 13 additions & 8 deletions parachain/modules/ismp/pallet/src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@
use crate::{
primitives::ConsensusClientProvider, AllowedProxies, ChallengePeriod, Config,
ConsensusClientUpdateTime, ConsensusStateClient, ConsensusStates, FrozenConsensusClients,
FrozenHeights, LatestStateMachineHeight, Nonce, RequestCommitments, RequestReceipts, Responded,
ResponseCommitments, ResponseReceipt, ResponseReceipts, StateCommitments,
FrozenStateMachine, LatestStateMachineHeight, Nonce, RequestCommitments, RequestReceipts,
Responded, ResponseCommitments, ResponseReceipt, ResponseReceipts, StateCommitments,
StateMachineUpdateTime, UnbondingPeriod,
};
use alloc::{format, string::ToString};
Expand Down Expand Up @@ -102,10 +102,10 @@ impl<T: Config> IsmpHost for Host<T> {
<T::TimeProvider as UnixTime>::now()
}

fn is_state_machine_frozen(&self, machine: StateMachineHeight) -> Result<(), Error> {
if let Some(frozen_height) = FrozenHeights::<T>::get(machine.id) {
if machine.height >= frozen_height {
Err(Error::FrozenStateMachine { height: machine })?
fn is_state_machine_frozen(&self, machine: StateMachineId) -> Result<(), Error> {
if let Some(frozen) = FrozenStateMachine::<T>::get(machine) {
if frozen {
Err(Error::FrozenStateMachine { id: machine })?
}
}
Ok(())
Expand Down Expand Up @@ -217,8 +217,13 @@ impl<T: Config> IsmpHost for Host<T> {
Ok(())
}

fn freeze_state_machine(&self, height: StateMachineHeight) -> Result<(), Error> {
FrozenHeights::<T>::insert(height.id, height.height);
fn freeze_state_machine(&self, state_machine: StateMachineId) -> Result<(), Error> {
FrozenStateMachine::<T>::insert(state_machine, true);
Ok(())
}

fn unfreeze_state_machine(&self, state_machine: StateMachineId) -> Result<(), Error> {
FrozenStateMachine::<T>::remove(&state_machine);
Ok(())
}

Expand Down
6 changes: 3 additions & 3 deletions parachain/modules/ismp/pallet/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,9 +171,9 @@ pub mod pallet {
/// Holds a map of state machines to the height at which they've been frozen due to byzantine
/// behaviour
#[pallet::storage]
#[pallet::getter(fn frozen_heights)]
pub type FrozenHeights<T: Config> =
StorageMap<_, Blake2_128Concat, StateMachineId, u64, OptionQuery>;
#[pallet::getter(fn frozen_state_machine)]
pub type FrozenStateMachine<T: Config> =
StorageMap<_, Blake2_128Concat, StateMachineId, bool, OptionQuery>;

/// Holds a map of state machines to the latest height we've processed requests for
#[pallet::storage]
Expand Down
8 changes: 6 additions & 2 deletions parachain/modules/ismp/sync-committee/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ impl IsmpHost for Host {
todo!()
}

fn is_state_machine_frozen(&self, machine: StateMachineHeight) -> Result<(), Error> {
fn is_state_machine_frozen(&self, machine: StateMachineId) -> Result<(), Error> {
todo!()
}

Expand Down Expand Up @@ -154,7 +154,11 @@ impl IsmpHost for Host {
todo!()
}

fn freeze_state_machine(&self, height: StateMachineHeight) -> Result<(), Error> {
fn freeze_state_machine(&self, state_machine: StateMachineId) -> Result<(), Error> {
todo!()
}

fn unfreeze_state_machine(&self, state_machine: StateMachineId) -> Result<(), Error> {
todo!()
}

Expand Down
6 changes: 1 addition & 5 deletions parachain/modules/ismp/testsuite/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,11 +162,7 @@ pub fn frozen_check<H: IsmpHost>(host: &H) -> Result<(), &'static str> {
.unwrap();
host.store_state_machine_update_time(intermediate_state.height, previous_update_time)
.unwrap();
let frozen_height = StateMachineHeight {
id: intermediate_state.height.id,
height: intermediate_state.height.height - 1,
};
host.freeze_state_machine(frozen_height).unwrap();
host.freeze_state_machine(intermediate_state.height.id).unwrap();

let post = Post {
source: host.host_state_machine(),
Expand Down
25 changes: 13 additions & 12 deletions parachain/modules/ismp/testsuite/src/mocks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ pub struct Host {
consensus_states: Rc<RefCell<HashMap<ConsensusStateId, Vec<u8>>>>,
state_commitments: Rc<RefCell<HashMap<StateMachineHeight, StateCommitment>>>,
consensus_update_time: Rc<RefCell<HashMap<ConsensusStateId, Duration>>>,
frozen_state_machines: Rc<RefCell<HashMap<StateMachineId, StateMachineHeight>>>,
frozen_state_machines: Rc<RefCell<HashMap<StateMachineId, bool>>>,
latest_state_height: Rc<RefCell<HashMap<StateMachineId, u64>>>,
nonce: Rc<RefCell<u64>>,
}
Expand Down Expand Up @@ -162,15 +162,11 @@ impl IsmpHost for Host {
SystemTime::now().duration_since(UNIX_EPOCH).unwrap()
}

fn is_state_machine_frozen(&self, machine: StateMachineHeight) -> Result<(), Error> {
let val = self
.frozen_state_machines
.borrow()
.get(&machine.id)
.map(|frozen_height| machine.height >= frozen_height.height)
.unwrap_or(false);
if val {
Err(Error::FrozenStateMachine { height: machine })?;
fn is_state_machine_frozen(&self, machine: StateMachineId) -> Result<(), Error> {
let binding = self.frozen_state_machines.borrow();
let val = binding.get(&machine).unwrap_or(&false);
if *val {
Err(Error::FrozenStateMachine { id: machine })?;
}

Ok(())
Expand Down Expand Up @@ -260,8 +256,13 @@ impl IsmpHost for Host {
Ok(())
}

fn freeze_state_machine(&self, height: StateMachineHeight) -> Result<(), Error> {
self.frozen_state_machines.borrow_mut().insert(height.id, height);
fn freeze_state_machine(&self, state_machine: StateMachineId) -> Result<(), Error> {
self.frozen_state_machines.borrow_mut().insert(state_machine, true);
Ok(())
}

fn unfreeze_state_machine(&self, state_machine: StateMachineId) -> Result<(), Error> {
self.frozen_state_machines.borrow_mut().remove(&state_machine);
Ok(())
}

Expand Down
34 changes: 34 additions & 0 deletions parachain/modules/state-machine-manager/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
[package]
name = "state-machine-manager"
version = "0.1.0"
edition = "2021"
description = "Manager for freezing and unfreezing State Machines"
authors = ["Polytope Labs <[email protected]>"]

[dependencies]
# substrate
frame-support = { workspace = true }
frame-system = { workspace = true }
sp-runtime = { workspace = true }
pallet-ismp = { path = "../ismp/pallet", default-features = false }

# polytope labs
ismp = { package = "ismp", path = "../ismp/core", default-features = false }

# crates.io
codec = { package = "parity-scale-codec", version = "3.1.3", default-features = false }
scale-info = { version = "2.1.1", default-features = false, features = ["derive"] }

[features]
default = ["std"]
std = [
"codec/std",
"scale-info/std",
"frame-support/std",
"frame-system/std",
"sp-runtime/std",
"ismp/std",
"pallet-ismp/std",
]


Loading

0 comments on commit 8009dd1

Please sign in to comment.