fedimint_gwv2_client/
receive_sm.rs

1use core::fmt;
2use std::collections::BTreeMap;
3
4use anyhow::anyhow;
5use fedimint_api_client::api::{FederationApiExt, PeerError};
6use fedimint_api_client::query::FilterMapThreshold;
7use fedimint_client_module::DynGlobalClientContext;
8use fedimint_client_module::sm::{ClientSMDatabaseTransaction, State, StateTransition};
9use fedimint_client_module::transaction::{ClientInput, ClientInputBundle};
10use fedimint_core::core::OperationId;
11use fedimint_core::encoding::{Decodable, Encodable};
12use fedimint_core::module::ApiRequestErased;
13use fedimint_core::secp256k1::Keypair;
14use fedimint_core::{NumPeersExt, OutPoint, PeerId};
15use fedimint_lnv2_common::contracts::IncomingContract;
16use fedimint_lnv2_common::endpoint_constants::DECRYPTION_KEY_SHARE_ENDPOINT;
17use fedimint_lnv2_common::{LightningInput, LightningInputV0};
18use fedimint_logging::LOG_CLIENT_MODULE_GW;
19use tpe::{AggregatePublicKey, DecryptionKeyShare, PublicKeyShare, aggregate_dk_shares};
20use tracing::warn;
21
22use super::events::{IncomingPaymentFailed, IncomingPaymentSucceeded};
23use crate::GatewayClientContextV2;
24
25#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
26pub struct ReceiveStateMachine {
27    pub common: ReceiveSMCommon,
28    pub state: ReceiveSMState,
29}
30
31impl ReceiveStateMachine {
32    pub fn update(&self, state: ReceiveSMState) -> Self {
33        Self {
34            common: self.common.clone(),
35            state,
36        }
37    }
38}
39
40impl fmt::Display for ReceiveStateMachine {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        write!(
43            f,
44            "Receive State Machine Operation ID: {:?} State: {}",
45            self.common.operation_id, self.state
46        )
47    }
48}
49
50#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
51pub struct ReceiveSMCommon {
52    pub operation_id: OperationId,
53    pub contract: IncomingContract,
54    pub outpoint: OutPoint,
55    pub refund_keypair: Keypair,
56}
57
58#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
59pub enum ReceiveSMState {
60    Funding,
61    Rejected(String),
62    Success([u8; 32]),
63    Failure,
64    Refunding(Vec<OutPoint>),
65}
66
67impl fmt::Display for ReceiveSMState {
68    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
69        match self {
70            ReceiveSMState::Funding => write!(f, "Funding"),
71            ReceiveSMState::Rejected(_) => write!(f, "Rejected"),
72            ReceiveSMState::Success(_) => write!(f, "Success"),
73            ReceiveSMState::Failure => write!(f, "Failure"),
74            ReceiveSMState::Refunding(_) => write!(f, "Refunding"),
75        }
76    }
77}
78
79#[cfg_attr(doc, aquamarine::aquamarine)]
80/// State machine that handles the relay of an incoming Lightning payment.
81///
82/// ```mermaid
83/// graph LR
84/// classDef virtual fill:#fff,stroke-dasharray: 5 5
85///
86///     Funding -- funding transaction is rejected --> Rejected
87///     Funding -- aggregated decryption key is invalid --> Failure
88///     Funding -- decrypted preimage is valid --> Success
89///     Funding -- decrypted preimage is invalid --> Refunding
90/// ```
91impl State for ReceiveStateMachine {
92    type ModuleContext = GatewayClientContextV2;
93
94    fn transitions(
95        &self,
96        context: &Self::ModuleContext,
97        global_context: &DynGlobalClientContext,
98    ) -> Vec<StateTransition<Self>> {
99        let gc = global_context.clone();
100        let tpe_agg_pk = context.tpe_agg_pk;
101        let gateway_context_ready = context.clone();
102
103        match &self.state {
104            ReceiveSMState::Funding => {
105                vec![StateTransition::new(
106                    Self::await_decryption_shares(
107                        global_context.clone(),
108                        context.tpe_pks.clone(),
109                        self.common.outpoint,
110                        self.common.contract.clone(),
111                    ),
112                    move |dbtx, output_outcomes, old_state| {
113                        Box::pin(Self::transition_decryption_shares(
114                            dbtx,
115                            output_outcomes,
116                            old_state,
117                            gc.clone(),
118                            tpe_agg_pk,
119                            gateway_context_ready.clone(),
120                        ))
121                    },
122                )]
123            }
124            ReceiveSMState::Success(..)
125            | ReceiveSMState::Rejected(..)
126            | ReceiveSMState::Refunding(..)
127            | ReceiveSMState::Failure => {
128                vec![]
129            }
130        }
131    }
132
133    fn operation_id(&self) -> OperationId {
134        self.common.operation_id
135    }
136}
137
138impl ReceiveStateMachine {
139    async fn await_decryption_shares(
140        global_context: DynGlobalClientContext,
141        tpe_pks: BTreeMap<PeerId, PublicKeyShare>,
142        outpoint: OutPoint,
143        contract: IncomingContract,
144    ) -> Result<BTreeMap<PeerId, DecryptionKeyShare>, String> {
145        global_context.await_tx_accepted(outpoint.txid).await?;
146
147        Ok(global_context
148            .module_api()
149            .request_with_strategy_retry(
150                FilterMapThreshold::new(
151                    move |peer_id, share: DecryptionKeyShare| {
152                        if !contract.verify_decryption_share(
153                            tpe_pks.get(&peer_id).ok_or(PeerError::InternalClientError(
154                                anyhow!("Missing TPE PK for peer {peer_id}?!"),
155                            ))?,
156                            &share,
157                        ) {
158                            return Err(fedimint_api_client::api::PeerError::InvalidResponse(
159                                anyhow!("Invalid decryption share"),
160                            ));
161                        }
162
163                        Ok(share)
164                    },
165                    global_context.api().all_peers().to_num_peers(),
166                ),
167                DECRYPTION_KEY_SHARE_ENDPOINT.to_owned(),
168                ApiRequestErased::new(outpoint),
169            )
170            .await)
171    }
172
173    async fn transition_decryption_shares(
174        dbtx: &mut ClientSMDatabaseTransaction<'_, '_>,
175        decryption_shares: Result<BTreeMap<PeerId, DecryptionKeyShare>, String>,
176        old_state: ReceiveStateMachine,
177        global_context: DynGlobalClientContext,
178        tpe_agg_pk: AggregatePublicKey,
179        client_ctx: GatewayClientContextV2,
180    ) -> ReceiveStateMachine {
181        let decryption_shares = match decryption_shares {
182            Ok(decryption_shares) => decryption_shares
183                .into_iter()
184                .map(|(peer, share)| (peer.to_usize() as u64, share))
185                .collect(),
186            Err(error) => {
187                client_ctx
188                    .module
189                    .client_ctx
190                    .log_event(
191                        &mut dbtx.module_tx(),
192                        IncomingPaymentFailed {
193                            payment_image: old_state
194                                .common
195                                .contract
196                                .commitment
197                                .payment_image
198                                .clone(),
199                            error: error.clone(),
200                        },
201                    )
202                    .await;
203
204                return old_state.update(ReceiveSMState::Rejected(error));
205            }
206        };
207
208        let agg_decryption_key = aggregate_dk_shares(&decryption_shares);
209
210        if !old_state
211            .common
212            .contract
213            .verify_agg_decryption_key(&tpe_agg_pk, &agg_decryption_key)
214        {
215            warn!(target: LOG_CLIENT_MODULE_GW, "Failed to obtain decryption key. Client config's public keys are inconsistent");
216
217            client_ctx
218                .module
219                .client_ctx
220                .log_event(
221                    &mut dbtx.module_tx(),
222                    IncomingPaymentFailed {
223                        payment_image: old_state.common.contract.commitment.payment_image.clone(),
224                        error: "Client config's public keys are inconsistent".to_string(),
225                    },
226                )
227                .await;
228
229            return old_state.update(ReceiveSMState::Failure);
230        }
231
232        if let Some(preimage) = old_state
233            .common
234            .contract
235            .decrypt_preimage(&agg_decryption_key)
236        {
237            client_ctx
238                .module
239                .client_ctx
240                .log_event(
241                    &mut dbtx.module_tx(),
242                    IncomingPaymentSucceeded {
243                        payment_image: old_state.common.contract.commitment.payment_image.clone(),
244                    },
245                )
246                .await;
247
248            return old_state.update(ReceiveSMState::Success(preimage));
249        }
250
251        let client_input = ClientInput::<LightningInput> {
252            input: LightningInput::V0(LightningInputV0::Incoming(
253                old_state.common.outpoint,
254                agg_decryption_key,
255            )),
256            amount: old_state.common.contract.commitment.amount,
257            keys: vec![old_state.common.refund_keypair],
258        };
259
260        let outpoints = global_context
261            .claim_inputs(
262                dbtx,
263                // The input of the refund tx is managed by this state machine
264                ClientInputBundle::new_no_sm(vec![client_input]),
265            )
266            .await
267            .expect("Cannot claim input, additional funding needed")
268            .into_iter()
269            .collect();
270
271        client_ctx
272            .module
273            .client_ctx
274            .log_event(
275                &mut dbtx.module_tx(),
276                IncomingPaymentFailed {
277                    payment_image: old_state.common.contract.commitment.payment_image.clone(),
278                    error: "Failed to decrypt preimage".to_string(),
279                },
280            )
281            .await;
282
283        old_state.update(ReceiveSMState::Refunding(outpoints))
284    }
285}