clementine_core/states/context.rs
1use crate::config::BridgeConfig;
2use crate::database::DatabaseTransaction;
3use crate::deposit::{DepositData, KickoffData};
4use crate::operator::RoundIndex;
5use crate::utils::NamedEntity;
6
7use bitcoin::BlockHash;
8use bitcoin::Transaction;
9use bitcoin::Txid;
10use bitcoin::Witness;
11use bitcoin::XOnlyPublicKey;
12use statig::awaitable::InitializedStateMachine;
13use tokio::sync::Mutex;
14use tonic::async_trait;
15
16use std::collections::HashMap;
17use std::sync::Arc;
18
19use crate::builder::transaction::TxHandler;
20
21use std::collections::BTreeMap;
22
23use crate::builder::transaction::ContractContext;
24
25use crate::builder::transaction::TransactionType;
26
27use crate::errors::BridgeError;
28
29use std::collections::HashSet;
30
31use super::block_cache;
32use super::kickoff;
33use super::round;
34
35#[derive(Debug, Clone)]
36/// Duties are notifications that are sent to the owner (verifier or operator) of the state machine to notify them on changes to the current
37/// contract state that require action.
38/// Note that for all kickoff state duties, they are only sent if withdrawal process is still going on, meaning the burn connector and
39/// kickoff finalizer is still on-chain/unspent.
40pub enum Duty {
41 /// -- Round state duties --
42 /// This duty is sent after a new ready to reimburse tx is sent by the corresponding operator.
43 /// used_kickoffs is a set of kickoff indexes that have been used in the previous round.
44 /// If there are unspent kickoffs, the owner can send a unspent kickoff connector tx.
45 NewReadyToReimburse {
46 round_idx: RoundIndex,
47 operator_xonly_pk: XOnlyPublicKey,
48 used_kickoffs: HashSet<usize>,
49 },
50 /// This duty is sent after a kickoff utxo is spent by the operator.
51 /// It includes the txid in which the utxo was spent, so that the owner can verify if this is an actual kickoff sent by operator.
52 /// Witness is also sent as if tx is an actual kickoff, the witness includes payout blockhash.
53 CheckIfKickoff {
54 txid: Txid,
55 block_height: u32,
56 witness: Witness,
57 challenged_before: bool,
58 },
59 /// -- Kickoff state duties --
60 /// This duty is only sent if a kickoff was challenged.
61 /// This duty is sent after some time (config.time_to_send_watchtower_challenge number of blocks) passes after a kickoff was sent to chain.
62 /// It denotes to the owner that it is time to send a watchtower challenge to the corresponding kickoff.
63 WatchtowerChallenge {
64 kickoff_data: KickoffData,
65 deposit_data: DepositData,
66 },
67 /// This duty is only sent if a kickoff was challenged.
68 /// This duty is sent only after latest blockhash is committed. Latest blockhash is committed after all watchtower challenges are sent
69 /// or timed out so that it is certain no new watchtower challenges can be sent.
70 /// The duty denotes that it is time to start sending operator asserts to the corresponding kickoff.
71 /// It includes the all watchtower challenges and the payout blockhash so that they can be used in the proof.
72 SendOperatorAsserts {
73 kickoff_data: KickoffData,
74 deposit_data: DepositData,
75 watchtower_challenges: HashMap<usize, Transaction>,
76 payout_blockhash: Witness,
77 latest_blockhash: Witness,
78 },
79 /// This duty is only sent if a kickoff was challenged.
80 /// This duty is sent after all asserts and latest blockhash commit are finalized on chain, and all watchtower challenge
81 /// utxos are spent.
82 /// It denotes to the owner that it is time to send a disprove to the corresponding kickoff.
83 /// It includes the operator asserts, operator acks and the payout blockhash so that they can be used in the disprove tx if the proof
84 /// is invalid.
85 VerifierDisprove {
86 kickoff_data: KickoffData,
87 deposit_data: DepositData,
88 operator_asserts: HashMap<usize, Witness>,
89 operator_acks: HashMap<usize, Witness>,
90 payout_blockhash: Witness,
91 latest_blockhash: Witness,
92 },
93 /// This duty is only sent if a kickoff was challenged.
94 /// This duty is sent after every watchtower challenge is either sent or timed out.
95 /// It denotes to the owner that it is time to send a latest blockhash to the corresponding kickoff to be used in the proof.
96 SendLatestBlockhash {
97 kickoff_data: KickoffData,
98 deposit_data: DepositData,
99 latest_blockhash: BlockHash,
100 },
101}
102
103/// Result of handling a duty
104#[derive(Debug, Clone)]
105pub enum DutyResult {
106 /// Duty was handled, no return value is necessary
107 Handled,
108 /// Result of checking if a kickoff contains if a challenge was sent because the kickoff was determined as malicious
109 CheckIfKickoff { challenged: bool },
110}
111
112/// Owner trait with async handling and tx handler creation
113#[async_trait]
114pub trait Owner: Clone + NamedEntity {
115 /// Handle a protocol-related duty
116 async fn handle_duty(
117 &self,
118 dbtx: DatabaseTransaction<'_, '_>,
119 duty: Duty,
120 ) -> Result<DutyResult, BridgeError>;
121
122 /// Create the transactions for an instance of the L1 contract
123 async fn create_txhandlers(
124 &self,
125 dbtx: DatabaseTransaction<'_, '_>,
126 tx_type: TransactionType,
127 contract_context: ContractContext,
128 ) -> Result<BTreeMap<TransactionType, TxHandler>, BridgeError>;
129
130 /// Handle a new finalized block
131 async fn handle_finalized_block(
132 &self,
133 dbtx: DatabaseTransaction<'_, '_>,
134 block_id: u32,
135 block_height: u32,
136 block_cache: Arc<block_cache::BlockCache>,
137 _light_client_proof_wait_interval_secs: Option<u32>,
138 ) -> Result<(), BridgeError>;
139}
140
141/// Context for the state machine
142/// Every state can access the context
143#[derive(Debug, Clone)]
144pub struct StateContext<T: Owner> {
145 pub owner: Arc<T>,
146 pub cache: Arc<block_cache::BlockCache>,
147 pub new_round_machines: Vec<InitializedStateMachine<round::RoundStateMachine<T>>>,
148 pub new_kickoff_machines: Vec<InitializedStateMachine<kickoff::KickoffStateMachine<T>>>,
149 pub errors: Vec<Arc<eyre::Report>>,
150 pub config: BridgeConfig,
151 pub owner_type: String,
152 pub shared_dbtx: Arc<Mutex<sqlx::Transaction<'static, sqlx::Postgres>>>,
153}
154
155impl<T: Owner> StateContext<T> {
156 pub fn new(
157 shared_dbtx: Arc<Mutex<sqlx::Transaction<'static, sqlx::Postgres>>>,
158 owner: Arc<T>,
159 cache: Arc<block_cache::BlockCache>,
160 config: BridgeConfig,
161 ) -> Self {
162 // Get the owner type string from the owner instance
163 let owner_type = T::ENTITY_NAME.to_string();
164
165 Self {
166 shared_dbtx,
167 owner,
168 cache,
169 new_round_machines: Vec::new(),
170 new_kickoff_machines: Vec::new(),
171 errors: Vec::new(),
172 config,
173 owner_type,
174 }
175 }
176
177 pub async fn dispatch_duty(&self, duty: Duty) -> Result<DutyResult, BridgeError> {
178 let mut guard = self.shared_dbtx.lock().await;
179 self.owner.handle_duty(&mut guard, duty).await
180 }
181
182 /// Run an async closure and capture any errors in execution.
183 ///
184 /// It will store the error report in the context's `errors` field. The
185 /// errors are later collected by the state manager and reported. This
186 /// ensures that all errors are collected and reported in a single place.
187 /// In general, it's expected that the closure attaches context about the
188 /// state machine to the error report. You may check
189 /// `KickoffStateMachine::wrap_err` and `RoundStateMachine::wrap_err`
190 /// for an example implementation of an error wrapper utility function.
191 ///
192 /// # Parameters
193 /// * `fnc`: An async closure that takes a mutable reference to the state context and returns a result.
194 ///
195 /// # Returns
196 /// * `()`
197 pub async fn capture_error(
198 &mut self,
199 fnc: impl AsyncFnOnce(&mut Self) -> Result<(), eyre::Report>,
200 ) {
201 let result = fnc(self).await;
202 if let Err(e) = result {
203 self.errors.push(e.into());
204 }
205 }
206}