Skip to content
This repository has been archived by the owner on Nov 10, 2023. It is now read-only.

Commit

Permalink
StateMachine encoding (#62)
Browse files Browse the repository at this point in the history
  • Loading branch information
seunlanlege authored Jul 11, 2023
1 parent 823da35 commit 93271cb
Show file tree
Hide file tree
Showing 6 changed files with 70 additions and 58 deletions.
24 changes: 12 additions & 12 deletions ismp-testsuite/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,8 @@ pub fn check_challenge_period<H: IsmpHost>(host: &H) -> Result<(), &'static str>
assert!(matches!(res, Err(ismp::error::Error::ChallengePeriodNotElapsed { .. })));

let post = Post {
source_chain: host.host_state_machine(),
dest_chain: StateMachine::Kusama(2000),
source: host.host_state_machine(),
dest: StateMachine::Kusama(2000),
nonce: 0,
from: vec![0u8; 32],
to: vec![0u8; 32],
Expand Down Expand Up @@ -154,8 +154,8 @@ pub fn frozen_check<H: IsmpHost>(host: &H) -> Result<(), &'static str> {
host.freeze_state_machine(frozen_height).unwrap();

let post = Post {
source_chain: host.host_state_machine(),
dest_chain: StateMachine::Kusama(2000),
source: host.host_state_machine(),
dest: StateMachine::Kusama(2000),
nonce: 0,
from: vec![0u8; 32],
to: vec![0u8; 32],
Expand Down Expand Up @@ -204,15 +204,15 @@ pub fn timeout_post_processing_check<H: IsmpHost>(
let previous_update_time = host.timestamp() - (challenge_period * 2);
host.store_consensus_update_time(mock_consensus_state_id(), previous_update_time).unwrap();
let dispatch_post = DispatchPost {
dest_chain: StateMachine::Kusama(2000),
dest: StateMachine::Kusama(2000),
from: vec![0u8; 32],
to: vec![0u8; 32],
timeout_timestamp: intermediate_state.commitment.timestamp,
data: vec![0u8; 64],
};
let post = Post {
source_chain: host.host_state_machine(),
dest_chain: StateMachine::Kusama(2000),
source: host.host_state_machine(),
dest: StateMachine::Kusama(2000),
nonce: 0,
from: vec![0u8; 32],
to: vec![0u8; 32],
Expand Down Expand Up @@ -249,7 +249,7 @@ pub fn write_outgoing_commitments<H: IsmpHost>(
dispatcher: &dyn IsmpDispatcher,
) -> Result<(), &'static str> {
let post = DispatchPost {
dest_chain: StateMachine::Kusama(2000),
dest: StateMachine::Kusama(2000),
from: vec![0u8; 32],
to: vec![0u8; 32],
timeout_timestamp: 0,
Expand All @@ -262,8 +262,8 @@ pub fn write_outgoing_commitments<H: IsmpHost>(
.map_err(|_| "Dispatcher failed to dispatch request")?;
// Fetch commitment from storage
let post = Post {
source_chain: host.host_state_machine(),
dest_chain: StateMachine::Kusama(2000),
source: host.host_state_machine(),
dest: StateMachine::Kusama(2000),
nonce: 0,
from: vec![0u8; 32],
to: vec![0u8; 32],
Expand All @@ -275,8 +275,8 @@ pub fn write_outgoing_commitments<H: IsmpHost>(
host.request_commitment(commitment)
.map_err(|_| "Expected Request commitment to be found in storage")?;
let post = Post {
source_chain: StateMachine::Kusama(2000),
dest_chain: host.host_state_machine(),
source: StateMachine::Kusama(2000),
dest: host.host_state_machine(),
nonce: 0,
from: vec![0u8; 32],
to: vec![0u8; 32],
Expand Down
16 changes: 12 additions & 4 deletions ismp-testsuite/src/mocks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,14 @@ impl IsmpHost for Host {
Some(Duration::from_secs(60 * 60))
}

fn store_challenge_period(
&self,
_consensus_state_id: ConsensusStateId,
_period: u64,
) -> Result<(), Error> {
todo!()
}

fn unbonding_period(&self, _consensus_state_id: ConsensusStateId) -> Option<Duration> {
Some(Duration::from_secs(60 * 60 * 60))
}
Expand Down Expand Up @@ -325,8 +333,8 @@ impl IsmpDispatcher for MockDispatcher {
let request = match request {
DispatchRequest::Get(dispatch_get) => {
let get = Get {
source_chain: host.host_state_machine(),
dest_chain: dispatch_get.dest_chain,
source: host.host_state_machine(),
dest: dispatch_get.dest,
nonce: host.next_nonce(),
from: dispatch_get.from,
keys: dispatch_get.keys,
Expand All @@ -337,8 +345,8 @@ impl IsmpDispatcher for MockDispatcher {
}
DispatchRequest::Post(dispatch_post) => {
let post = Post {
source_chain: host.host_state_machine(),
dest_chain: dispatch_post.dest_chain,
source: host.host_state_machine(),
dest: dispatch_post.dest,
nonce: host.next_nonce(),
from: dispatch_post.from,
to: dispatch_post.to,
Expand Down
8 changes: 4 additions & 4 deletions ismp/src/handlers/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,15 +55,15 @@ where
let res = cb
.on_accept(request.clone())
.map(|_| DispatchSuccess {
dest_chain: request.dest_chain,
source_chain: request.source_chain,
dest_chain: request.dest,
source_chain: request.source,
nonce: request.nonce,
})
.map_err(|e| DispatchError {
msg: format!("{e:?}"),
nonce: request.nonce,
source_chain: request.source_chain,
dest_chain: request.dest_chain,
source_chain: request.source,
dest_chain: request.dest,
});
host.store_request_receipt(&Request::Post(request))?;
Ok(res)
Expand Down
40 changes: 22 additions & 18 deletions ismp/src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,13 @@ pub trait IsmpHost {
/// Should return the configured delay period for a consensus state
fn challenge_period(&self, consensus_state_id: ConsensusStateId) -> Option<Duration>;

/// Set the challenge period in seconds for a consensus state.
fn store_challenge_period(
&self,
consensus_state_id: ConsensusStateId,
period: u64,
) -> Result<(), Error>;

/// Check if the client has expired since the last update
fn is_expired(&self, consensus_state_id: ConsensusStateId) -> Result<(), Error> {
let host_timestamp = self.timestamp();
Expand Down Expand Up @@ -205,10 +212,10 @@ pub enum StateMachine {
/// Kusama parachains
#[codec(index = 2)]
Kusama(u32),
/// We identify
/// We identify standalone state machines by their consensus state
#[codec(index = 3)]
Grandpa(ConsensusStateId),
/// State machines chains running on beefy consensus client
/// State machines chains running on beefy consensus state
#[codec(index = 4)]
Beefy(ConsensusStateId),
}
Expand All @@ -217,21 +224,15 @@ impl ToString for StateMachine {
fn to_string(&self) -> String {
match self {
StateMachine::Ethereum(ethereum) => match ethereum {
Ethereum::ExecutionLayer => "ETHEREUM".to_string(),
Ethereum::Arbitrum => "ARBITRUM".to_string(),
Ethereum::Optimism => "OPTIMISM".to_string(),
Ethereum::ExecutionLayer => "ETHE".to_string(),
Ethereum::Arbitrum => "ARBI".to_string(),
Ethereum::Optimism => "OPTI".to_string(),
Ethereum::Base => "BASE".to_string(),
},
StateMachine::Polkadot(id) => format!("POLKADOT-{id}"),
StateMachine::Kusama(id) => format!("KUSAMA-{id}"),
StateMachine::Grandpa(id) => format!(
"GRANDPA-{}",
serde_json::to_string(id).expect("Array to string is infallible")
),
StateMachine::Beefy(id) => format!(
"BEEFY-{}",
serde_json::to_string(id).expect("Array to string is infallible")
),
StateMachine::Grandpa(id) => format!("GRANDPA-{}", u32::from_be_bytes(*id)),
StateMachine::Beefy(id) => format!("BEEFY-{}", u32::from_be_bytes(*id)),
}
}
}
Expand All @@ -241,9 +242,9 @@ impl FromStr for StateMachine {

fn from_str(s: &str) -> Result<Self, Self::Err> {
let s = match s {
"ETHEREUM" => StateMachine::Ethereum(Ethereum::ExecutionLayer),
"ARBITRUM" => StateMachine::Ethereum(Ethereum::Arbitrum),
"OPTIMISM" => StateMachine::Ethereum(Ethereum::Optimism),
"ETHE" => StateMachine::Ethereum(Ethereum::ExecutionLayer),
"ARBI" => StateMachine::Ethereum(Ethereum::Arbitrum),
"OPTI" => StateMachine::Ethereum(Ethereum::Optimism),
"BASE" => StateMachine::Ethereum(Ethereum::Base),
name if name.starts_with("POLKADOT-") => {
let id = name
Expand All @@ -265,15 +266,15 @@ impl FromStr for StateMachine {
let id = name
.split('-')
.last()
.and_then(|id| serde_json::from_str(id).ok())
.and_then(|id| u32::from_str(id).ok().map(u32::to_be_bytes))
.ok_or_else(|| format!("invalid state machine: {name}"))?;
StateMachine::Grandpa(id)
}
name if name.starts_with("BEEFY-") => {
let id = name
.split('-')
.last()
.and_then(|id| serde_json::from_str(id).ok())
.and_then(|id| u32::from_str(id).ok().map(u32::to_be_bytes))
.ok_or_else(|| format!("invalid state machine: {name}"))?;
StateMachine::Beefy(id)
}
Expand All @@ -298,6 +299,9 @@ mod tests {
let grandpa_string = grandpa.to_string();
let beefy_string = beefy.to_string();

dbg!(&grandpa_string);
dbg!(&beefy_string);

assert_eq!(grandpa, StateMachine::from_str(&grandpa_string).unwrap());
assert_eq!(beefy, StateMachine::from_str(&beefy_string).unwrap());
}
Expand Down
28 changes: 14 additions & 14 deletions ismp/src/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ use core::time::Duration;
#[cfg_attr(feature = "std", derive(serde::Deserialize, serde::Serialize))]
pub struct Post {
/// The source state machine of this request.
pub source_chain: StateMachine,
pub source: StateMachine,
/// The destination state machine of this request.
pub dest_chain: StateMachine,
pub dest: StateMachine,
/// The nonce of this request on the source chain
pub nonce: u64,
/// Module Id of the sending module
Expand All @@ -45,9 +45,9 @@ pub struct Post {
#[cfg_attr(feature = "std", derive(serde::Deserialize, serde::Serialize))]
pub struct Get {
/// The source state machine of this request.
pub source_chain: StateMachine,
pub source: StateMachine,
/// The destination state machine of this request.
pub dest_chain: StateMachine,
pub dest: StateMachine,
/// The nonce of this request on the source chain
pub nonce: u64,
/// Module Id of the sending module
Expand Down Expand Up @@ -84,8 +84,8 @@ impl Request {
/// Get the source chain
pub fn source_chain(&self) -> StateMachine {
match self {
Request::Get(get) => get.source_chain,
Request::Post(post) => post.source_chain,
Request::Get(get) => get.source,
Request::Post(post) => post.source,
}
}

Expand All @@ -108,8 +108,8 @@ impl Request {
/// Get the destination chain
pub fn dest_chain(&self) -> StateMachine {
match self {
Request::Get(get) => get.dest_chain,
Request::Post(post) => post.dest_chain,
Request::Get(get) => get.dest,
Request::Post(post) => post.dest,
}
}

Expand Down Expand Up @@ -226,16 +226,16 @@ impl Response {
/// Get the source chain for this response
pub fn source_chain(&self) -> StateMachine {
match self {
Response::Get(res) => res.get.dest_chain,
Response::Post(res) => res.post.dest_chain,
Response::Get(res) => res.get.dest,
Response::Post(res) => res.post.dest,
}
}

/// Get the destination chain for this response
pub fn dest_chain(&self) -> StateMachine {
match self {
Response::Get(res) => res.get.source_chain,
Response::Post(res) => res.post.source_chain,
Response::Get(res) => res.get.source,
Response::Post(res) => res.post.source,
}
}

Expand Down Expand Up @@ -268,7 +268,7 @@ pub trait IsmpRouter {
#[derive(Clone)]
pub struct DispatchPost {
/// The destination state machine of this request.
pub dest_chain: StateMachine,
pub dest: StateMachine,
/// Module Id of the sending module
pub from: Vec<u8>,
/// Module ID of the receiving module
Expand All @@ -283,7 +283,7 @@ pub struct DispatchPost {
#[derive(Clone)]
pub struct DispatchGet {
/// The destination state machine of this request.
pub dest_chain: StateMachine,
pub dest: StateMachine,
/// Module Id of the sending module
pub from: Vec<u8>,
/// Raw Storage keys that would be used to fetch the values from the counterparty
Expand Down
12 changes: 6 additions & 6 deletions ismp/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ pub fn hash_request<H: IsmpHost>(req: &Request) -> H256 {
Request::Post(post) => {
let mut buf = Vec::new();

let source_chain = post.source_chain.to_string();
let dest_chain = post.dest_chain.to_string();
let source_chain = post.source.to_string();
let dest_chain = post.dest.to_string();
let nonce = post.nonce.to_be_bytes();
let timestamp = post.timeout_timestamp.to_be_bytes();
buf.extend_from_slice(source_chain.as_bytes());
Expand All @@ -30,8 +30,8 @@ pub fn hash_request<H: IsmpHost>(req: &Request) -> H256 {
Request::Get(get) => {
let mut buf = Vec::new();

let source_chain = get.source_chain.to_string();
let dest_chain = get.dest_chain.to_string();
let source_chain = get.source.to_string();
let dest_chain = get.dest.to_string();
let nonce = get.nonce.to_be_bytes();
let height = get.height.to_be_bytes();
let timestamp = get.timeout_timestamp.to_be_bytes();
Expand All @@ -55,8 +55,8 @@ pub fn hash_response<H: IsmpHost>(res: &Response) -> H256 {
_ => return Default::default(),
};
let mut buf = Vec::new();
let source_chain = req.source_chain.to_string();
let dest_chain = req.dest_chain.to_string();
let source_chain = req.source.to_string();
let dest_chain = req.dest.to_string();
let nonce = req.nonce.to_be_bytes();
let timestamp = req.timeout_timestamp.to_be_bytes();
buf.extend_from_slice(source_chain.as_bytes());
Expand Down

0 comments on commit 93271cb

Please sign in to comment.