Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions crates/app/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,14 @@ pub trait VoidStream: Stream {
}
}

/// Trait for updating the latest block height and hash in state.
pub trait UpdateLatestBlock {
/// Error type for update_latest_block.
type Error;
/// Update the latest block height and hash in state.
fn update_latest_block(&mut self, height: u64, hash: [u8; 32]) -> Result<(), Self::Error>;
}

impl<T: ?Sized> VoidStream for T where T: Stream {}

pin_project! {
Expand Down Expand Up @@ -728,3 +736,32 @@ impl Default for Notification {
Self::new()
}
}

/// Apply a state transition function with a block and update state.
/// Updates the latest block height and hash in the state.
/// Derives T from the updated state.
/// Returns the height.
pub fn apply_transition<S, T, F, Fe, E>(
block: Block,
state: &mut S,
state_transition_function: F,
) -> Result<(Block, Height<T>), E>
where
F: FnOnce(&Block, &mut S) -> Result<(), Fe>,
T: for<'a> TryFrom<&'a mut S>,
E: From<Fe>
+ From<<S as UpdateLatestBlock>::Error>
+ for<'a> From<<T as TryFrom<&'a mut S>>::Error>,
S: UpdateLatestBlock,
{
state_transition_function(&block, state)?;
state.update_latest_block(block.height, void_hash::Hash::hash(&block))?;
let height = block.height;
Ok((
block,
Height {
data: T::try_from(state)?,
block_height: height,
},
))
}