Skip to content

Commit

Permalink
random
Browse files Browse the repository at this point in the history
  • Loading branch information
atacann committed Feb 27, 2025
1 parent 1574473 commit e4be72d
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 44 deletions.
16 changes: 6 additions & 10 deletions core/src/states/kickoff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use statig::prelude::*;

use crate::{rpc::clementine::KickoffId, states::Duty};

use super::{BlockCache, BlockMatcher, DutyHandler, Matcher, StateContext};
use super::{BlockCache, BlockMatcher, Matcher, Owner, StateContext};

#[derive(Debug, Clone)]
pub enum KickoffEvent {
Expand All @@ -25,13 +25,13 @@ impl KickoffMatcher {
}

#[derive(Debug, Clone)]
pub struct KickoffStateMachine<T: DutyHandler> {
pub struct KickoffStateMachine<T: Owner> {
pub(crate) kickoff_id: KickoffId,
pub(crate) matchers: HashMap<Matcher, KickoffMatcher>,
phantom: std::marker::PhantomData<T>,
}

impl<T: DutyHandler> BlockMatcher for KickoffStateMachine<T> {
impl<T: Owner> BlockMatcher for KickoffStateMachine<T> {
type Event = KickoffEvent;

fn match_block(&self, block: &BlockCache) -> Vec<Self::Event> {
Expand All @@ -48,7 +48,7 @@ impl<T: DutyHandler> BlockMatcher for KickoffStateMachine<T> {
}
}

impl<T: DutyHandler> KickoffStateMachine<T> {
impl<T: Owner> KickoffStateMachine<T> {
pub fn new(kickoff_id: KickoffId) -> Self {
Self {
kickoff_id,
Expand All @@ -58,12 +58,8 @@ impl<T: DutyHandler> KickoffStateMachine<T> {
}
}

#[state_machine(
initial = "State::idle()",
state(derive(Debug, Clone)),
// context = "BridgeContext<T>"
)]
impl<T: DutyHandler> KickoffStateMachine<T> {
#[state_machine(initial = "State::idle()", state(derive(Debug, Clone)))]
impl<T: Owner> KickoffStateMachine<T> {
// Kickoff process state handlers

#[state]
Expand Down
57 changes: 32 additions & 25 deletions core/src/states/mod.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
use crate::builder::transaction::{OperatorData, TransactionType, TxHandler};
use crate::config::protocol::ProtocolParamset;
use crate::database::Database;
use crate::errors::BridgeError;
use bitcoin::{Block, OutPoint, Transaction, Txid};
use futures::TryFuture;
use statig::awaitable::InitializedStateMachine;
use statig::prelude::*;
use std::collections::{HashMap, HashSet};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::future::Future;
use std::sync::Arc;
use tonic::async_trait;
Expand Down Expand Up @@ -81,30 +83,33 @@ pub enum Duty {

// DutyHandler trait with async handling
#[async_trait]
pub trait DutyHandler: Send + Sync + Clone + Default {
pub trait Owner: Send + Sync + Clone + Default {
async fn handle_duty(&self, duty: Duty) -> Result<(), BridgeError>;
async fn create_txhandlers(&self) -> Result<BTreeMap<TransactionType, TxHandler>, BridgeError>;
}

// Context shared between state machines
#[derive(Debug, Clone)]
pub struct StateContext<T: DutyHandler> {
pub struct StateContext<T: Owner> {
pub db: Database,
pub owner: T,
pub cache: BlockCache,
pub new_round_machines: Vec<InitializedStateMachine<round::RoundStateMachine<T>>>,
pub new_kickoff_machines: Vec<InitializedStateMachine<kickoff::KickoffStateMachine<T>>>,
pub errors: Vec<Arc<BridgeError>>,
pub paramset: &'static ProtocolParamset,
}

impl<T: DutyHandler> StateContext<T> {
pub fn new(db: Database, owner: T) -> Self {
impl<T: Owner> StateContext<T> {
pub fn new(db: Database, owner: T, paramset: &'static ProtocolParamset) -> Self {
Self {
db,
owner,
cache: BlockCache::new(),
new_round_machines: Vec::new(),
new_kickoff_machines: Vec::new(),
errors: Vec::new(),
paramset,
}
}

Expand All @@ -130,9 +135,7 @@ impl<T: DutyHandler> StateContext<T> {
self.new_kickoff_machines.push(machine);
}

pub async fn try_run<
Func: AsyncFnOnce(&mut Self) -> Result<(), BridgeError>,
>(
pub async fn try_run<Func: AsyncFnOnce(&mut Self) -> Result<(), BridgeError>>(
&mut self,
fnc: Func,
) {
Expand All @@ -145,22 +148,26 @@ impl<T: DutyHandler> StateContext<T> {

// New state manager to hold and coordinate state machines
#[derive(Debug)]
pub struct StateManager<T: DutyHandler> {
pub struct StateManager<T: Owner> {
db: Database,
handler: T,
round_machines: Vec<InitializedStateMachine<round::RoundStateMachine<T>>>,
kickoff_machines: Vec<InitializedStateMachine<kickoff::KickoffStateMachine<T>>>,
cache: BlockCache,
paramset: &'static ProtocolParamset,
context: StateContext<T>,
}

impl<T: DutyHandler> StateManager<T> {
pub fn new(db: Database, handler: T) -> Self {
impl<T: Owner> StateManager<T> {
pub fn new(db: Database, handler: T, paramset: &'static ProtocolParamset) -> Self {
Self {
db,
handler,
round_machines: Vec::new(),
kickoff_machines: Vec::new(),
cache: BlockCache::new(),
context: StateContext::new(db.clone(), handler.clone(), paramset),
db,
paramset,
handler,
}
}

Expand All @@ -169,24 +176,26 @@ impl<T: DutyHandler> StateManager<T> {
kickoff_id: crate::rpc::clementine::KickoffId,
) -> Result<(), BridgeError> {
let machine = kickoff::KickoffStateMachine::<T>::new(kickoff_id);
let mut context = self.create_context();

let initialized_machine = machine
.uninitialized_state_machine()
.init_with_context(&mut context)
.init_with_context(&mut self.context)
.await;

self.kickoff_machines.push(initialized_machine);
Ok(())
}

pub async fn add_round_machine(&mut self) -> Result<(), BridgeError> {
let machine = round::RoundStateMachine::<T>::new();
let mut context = self.create_context();
pub async fn add_round_machine(
&mut self,
operator_data: OperatorData,
operator_idx: u32,
) -> Result<(), BridgeError> {
let machine = round::RoundStateMachine::<T>::new(operator_data, operator_idx);

let initialized_machine = machine
.uninitialized_state_machine()
.init_with_context(&mut context)
.init_with_context(&mut self.context)
.await;

self.round_machines.push(initialized_machine);
Expand All @@ -198,6 +207,7 @@ impl<T: DutyHandler> StateManager<T> {
db: self.db.clone(),
owner: self.handler.clone(),
cache: self.cache.clone(),
paramset: self.paramset,
new_kickoff_machines: Vec::new(),
new_round_machines: Vec::new(),
errors: Vec::new(),
Expand All @@ -206,18 +216,15 @@ impl<T: DutyHandler> StateManager<T> {

pub async fn process_block(&mut self, block: &Block) -> Result<(), BridgeError> {
// Update cache with new block data
self.cache.update_with_block(block);

// Create a context with updated cache
let mut context = self.create_context();
self.context.cache.update_with_block(block);

// Process all kickoff machines
for machine in &mut self.kickoff_machines {
let events = machine.match_block(&self.cache);

// TODO: we should order events by their presence in the block
for event in events {
machine.handle_with_context(&event, &mut context).await;
machine.handle_with_context(&event, &mut self.context).await;
}
}

Expand All @@ -227,7 +234,7 @@ impl<T: DutyHandler> StateManager<T> {

// TODO: we should order events by their presence in the block
for event in events {
machine.handle_with_context(&event, &mut context).await;
machine.handle_with_context(&event, &mut self.context).await;
}
}

Expand Down
46 changes: 37 additions & 9 deletions core/src/states/round.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,16 @@ use std::collections::HashMap;

use statig::prelude::*;

use crate::{rpc::clementine::KickoffId, states::Duty};
use crate::{
builder::transaction::{
create_round_txhandlers, create_txhandlers, KickoffWinternitzKeys, OperatorData,
TransactionType, TxHandler,
},
rpc::clementine::KickoffId,
states::Duty,
};

use super::{BlockCache, BlockMatcher, DutyHandler, Matcher, StateContext};
use super::{BlockCache, BlockMatcher, Matcher, Owner, StateContext};

#[derive(Debug, Clone)]
pub enum RoundEvent {
Expand All @@ -14,7 +21,7 @@ pub enum RoundEvent {
}

#[derive(Debug, Clone)]
enum RoundMatcher {
pub(crate) enum RoundMatcher {
KickoffSent(KickoffId),
ReadyToReimburseSent { round_idx: u32 },
RoundSent { round_idx: u32 },
Expand All @@ -35,12 +42,14 @@ impl RoundMatcher {
}

#[derive(Debug, Clone)]
pub struct RoundStateMachine<T: DutyHandler> {
pub struct RoundStateMachine<T: Owner> {
pub(crate) matchers: HashMap<Matcher, RoundMatcher>,
operator_data: OperatorData,
operator_idx: u32,
phantom: std::marker::PhantomData<T>,
}

impl<T: DutyHandler> BlockMatcher for RoundStateMachine<T> {
impl<T: Owner> BlockMatcher for RoundStateMachine<T> {
type Event = RoundEvent;

fn match_block(&self, block: &BlockCache) -> Vec<Self::Event> {
Expand All @@ -57,17 +66,19 @@ impl<T: DutyHandler> BlockMatcher for RoundStateMachine<T> {
}
}

impl<T: DutyHandler> RoundStateMachine<T> {
pub fn new() -> Self {
impl<T: Owner> RoundStateMachine<T> {
pub fn new(operator_data: OperatorData, operator_idx: u32) -> Self {
Self {
matchers: HashMap::new(),
operator_data,
operator_idx,
phantom: std::marker::PhantomData,
}
}
}

#[state_machine(initial = "State::initial_collateral()", state(derive(Debug, Clone)))]
impl<T: DutyHandler> RoundStateMachine<T> {
impl<T: Owner> RoundStateMachine<T> {
// State handlers with proper statig approach

#[state(entry_action = "on_initial_collateral_entry")]
Expand All @@ -77,37 +88,54 @@ impl<T: DutyHandler> RoundStateMachine<T> {
context: &mut StateContext<T>,
) -> Response<State> {
match event {
RoundEvent::RoundSent { round_idx } => Transition(State::round_tx(*round_idx)),
_ => Super,
}
}

#[action]
pub(crate) async fn on_initial_collateral_entry(&mut self, context: &mut StateContext<T>) {
println!("Entered Initial Collateral state");
self.matchers = HashMap::new();
self.matchers.insert(
Matcher::SpentUtxo(self.operator_data.collateral_funding_outpoint),
RoundMatcher::RoundSent { round_idx: 0 },
);
}

#[state(entry_action = "on_round_tx_entry")]
pub(crate) async fn round_tx(
&mut self,
round_idx: &mut u32,
event: &RoundEvent,
context: &mut StateContext<T>,
) -> Response<State> {
match event {
RoundEvent::ReadyToReimburseSent { round_idx } => {
Transition(State::ready_to_reimburse(*round_idx))
}
_ => Super,
}
}

#[action]
pub(crate) async fn on_round_tx_entry(&mut self, context: &mut StateContext<T>) {
pub(crate) async fn on_round_tx_entry(
&mut self,
context: &mut StateContext<T>,
round_idx: &mut u32,
) {
println!("Entered Round Tx state");
// Assuming context.dispatch_duty is called elsewhere in the code
self.matchers = HashMap::new();
let x = context.owner.create_txhandlers();
}

#[state(entry_action = "on_ready_to_reimburse_entry")]
pub(crate) async fn ready_to_reimburse(
&mut self,
event: &RoundEvent,
context: &mut StateContext<T>,
round_idx: &mut u32,
) -> Response<State> {
match event {
_ => Super,
Expand Down

0 comments on commit e4be72d

Please sign in to comment.