ln_gateway/state_machine/
complete.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
use std::fmt;
use std::time::Duration;

use bitcoin_hashes::Hash;
use fedimint_client::sm::{State, StateTransition};
use fedimint_client::DynGlobalClientContext;
use fedimint_core::core::OperationId;
use fedimint_core::encoding::{Decodable, Encodable};
use fedimint_core::task::sleep;
use fedimint_ln_client::incoming::IncomingSmStates;
use fedimint_ln_common::contracts::Preimage;
use futures::StreamExt;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use tracing::{debug, info, warn};

use super::{GatewayClientContext, GatewayClientStateMachines};
use crate::gateway_lnrpc::intercept_htlc_response::{Action, Cancel, Settle};
use crate::gateway_lnrpc::InterceptHtlcResponse;

#[derive(Error, Debug, Serialize, Deserialize, Encodable, Decodable, Clone, Eq, PartialEq)]
enum CompleteHtlcError {
    #[error("Incoming contract was not funded")]
    IncomingContractNotFunded,
    #[error("Failed to complete HTLC")]
    FailedToCompleteHtlc,
}

#[cfg_attr(doc, aquamarine::aquamarine)]
/// State machine that completes the incoming payment by contacting the
/// lightning node when the incoming contract has been funded and the preimage
/// is available.
///
/// ```mermaid
/// graph LR
/// classDef virtual fill:#fff,stroke-dasharray: 5 5
///
///    WaitForPreimage -- incoming contract not funded --> Failure
///    WaitForPreimage -- successfully retrieved preimage --> CompleteHtlc
///    CompleteHtlc -- successfully completed or canceled htlc --> HtlcFinished
///    CompleteHtlc -- failed to finish htlc --> Failure
/// ```
#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
pub enum GatewayCompleteStates {
    WaitForPreimage(WaitForPreimageState),
    CompleteHtlc(CompleteHtlcState),
    HtlcFinished,
    Failure,
}

impl fmt::Display for GatewayCompleteStates {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            GatewayCompleteStates::WaitForPreimage(_) => write!(f, "WaitForPreimage"),
            GatewayCompleteStates::CompleteHtlc(_) => write!(f, "CompleteHtlc"),
            GatewayCompleteStates::HtlcFinished => write!(f, "HtlcFinished"),
            GatewayCompleteStates::Failure => write!(f, "Failure"),
        }
    }
}

#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
pub struct GatewayCompleteCommon {
    pub operation_id: OperationId,
    pub payment_hash: bitcoin_hashes::sha256::Hash,
    pub incoming_chan_id: u64,
    pub htlc_id: u64,
}

#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
pub struct GatewayCompleteStateMachine {
    pub common: GatewayCompleteCommon,
    pub state: GatewayCompleteStates,
}

impl fmt::Display for GatewayCompleteStateMachine {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Gateway Complete State Machine Operation ID: {:?} State: {}",
            self.common.operation_id, self.state
        )
    }
}

impl State for GatewayCompleteStateMachine {
    type ModuleContext = GatewayClientContext;

    fn transitions(
        &self,
        context: &Self::ModuleContext,
        _global_context: &DynGlobalClientContext,
    ) -> Vec<fedimint_client::sm::StateTransition<Self>> {
        match &self.state {
            GatewayCompleteStates::WaitForPreimage(_state) => {
                WaitForPreimageState::transitions(context.clone(), self.common.clone())
            }
            GatewayCompleteStates::CompleteHtlc(state) => {
                state.transitions(context.clone(), self.common.clone())
            }
            _ => vec![],
        }
    }

    fn operation_id(&self) -> fedimint_core::core::OperationId {
        self.common.operation_id
    }
}

#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
pub struct WaitForPreimageState;

impl WaitForPreimageState {
    fn transitions(
        context: GatewayClientContext,
        common: GatewayCompleteCommon,
    ) -> Vec<StateTransition<GatewayCompleteStateMachine>> {
        vec![StateTransition::new(
            Self::await_preimage(context, common.clone()),
            move |_dbtx, result, _old_state| {
                let common = common.clone();
                Box::pin(async { Self::transition_complete_htlc(result, common) })
            },
        )]
    }

    async fn await_preimage(
        context: GatewayClientContext,
        common: GatewayCompleteCommon,
    ) -> Result<Preimage, CompleteHtlcError> {
        let mut stream = context.notifier.subscribe(common.operation_id).await;
        loop {
            debug!("Waiting for preimage for {common:?}");
            if let Some(GatewayClientStateMachines::Receive(state)) = stream.next().await {
                match state.state {
                    IncomingSmStates::Preimage(preimage) => {
                        debug!("Received preimage for {common:?}");
                        return Ok(preimage);
                    }
                    IncomingSmStates::RefundSubmitted { out_points, error } => {
                        info!("Refund submitted for {common:?}: {out_points:?} {error}");
                        return Err(CompleteHtlcError::IncomingContractNotFunded);
                    }
                    IncomingSmStates::FundingFailed { error } => {
                        warn!("Funding failed for {common:?}: {error}");
                        return Err(CompleteHtlcError::IncomingContractNotFunded);
                    }
                    _ => {}
                }
            }
        }
    }

    fn transition_complete_htlc(
        result: Result<Preimage, CompleteHtlcError>,
        common: GatewayCompleteCommon,
    ) -> GatewayCompleteStateMachine {
        match result {
            Ok(preimage) => GatewayCompleteStateMachine {
                common,
                state: GatewayCompleteStates::CompleteHtlc(CompleteHtlcState {
                    outcome: HtlcOutcome::Success(preimage),
                }),
            },
            Err(e) => GatewayCompleteStateMachine {
                common,
                state: GatewayCompleteStates::CompleteHtlc(CompleteHtlcState {
                    outcome: HtlcOutcome::Failure(e.to_string()),
                }),
            },
        }
    }
}

#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
enum HtlcOutcome {
    Success(Preimage),
    Failure(String),
}

#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
pub struct CompleteHtlcState {
    outcome: HtlcOutcome,
}

impl CompleteHtlcState {
    fn transitions(
        &self,
        context: GatewayClientContext,
        common: GatewayCompleteCommon,
    ) -> Vec<StateTransition<GatewayCompleteStateMachine>> {
        vec![StateTransition::new(
            Self::await_complete_htlc(context, common.clone(), self.outcome.clone()),
            move |_dbtx, result, _| {
                let common = common.clone();
                Box::pin(async move { Self::transition_success(&result, common) })
            },
        )]
    }

    async fn await_complete_htlc(
        context: GatewayClientContext,
        common: GatewayCompleteCommon,
        outcome: HtlcOutcome,
    ) -> Result<(), CompleteHtlcError> {
        // Wait until the lightning node is online to complete the HTLC
        loop {
            let htlc_outcome = outcome.clone();
            let lightning_context = context.gateway.get_lightning_context().await;
            match lightning_context {
                Ok(lightning_context) => {
                    let htlc = match htlc_outcome {
                        HtlcOutcome::Success(preimage) => InterceptHtlcResponse {
                            action: Some(Action::Settle(Settle {
                                preimage: preimage.0.to_vec(),
                            })),
                            payment_hash: common.payment_hash.to_byte_array().to_vec(),
                            incoming_chan_id: common.incoming_chan_id,
                            htlc_id: common.htlc_id,
                        },
                        HtlcOutcome::Failure(reason) => InterceptHtlcResponse {
                            action: Some(Action::Cancel(Cancel { reason })),
                            payment_hash: common.payment_hash.to_byte_array().to_vec(),
                            incoming_chan_id: common.incoming_chan_id,
                            htlc_id: common.htlc_id,
                        },
                    };

                    lightning_context
                        .lnrpc
                        .complete_htlc(htlc)
                        .await
                        .map_err(|_| CompleteHtlcError::FailedToCompleteHtlc)?;
                    return Ok(());
                }
                Err(e) => {
                    warn!("Trying to complete HTLC but got {e}, will keep retrying...");
                    sleep(Duration::from_secs(5)).await;
                }
            }
        }
    }

    fn transition_success(
        result: &Result<(), CompleteHtlcError>,
        common: GatewayCompleteCommon,
    ) -> GatewayCompleteStateMachine {
        match result {
            Ok(()) => GatewayCompleteStateMachine {
                common,
                state: GatewayCompleteStates::HtlcFinished,
            },
            Err(_) => GatewayCompleteStateMachine {
                common,
                state: GatewayCompleteStates::Failure,
            },
        }
    }
}