fedimint_ln_client/
receive.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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
use std::sync::Arc;
use std::time::Duration;

use bitcoin::key::KeyPair;
use fedimint_api_client::api::DynModuleApi;
use fedimint_client::sm::{ClientSMDatabaseTransaction, DynState, State, StateTransition};
use fedimint_client::transaction::ClientInput;
use fedimint_client::DynGlobalClientContext;
use fedimint_core::core::{IntoDynInstance, ModuleInstanceId, OperationId};
use fedimint_core::encoding::{Decodable, Encodable};
use fedimint_core::task::sleep;
use fedimint_core::{OutPoint, TransactionId};
use fedimint_ln_common::contracts::incoming::IncomingContractAccount;
use fedimint_ln_common::contracts::{DecryptedPreimage, FundedContract};
use fedimint_ln_common::federation_endpoint_constants::ACCOUNT_ENDPOINT;
use fedimint_ln_common::LightningInput;
use lightning_invoice::Bolt11Invoice;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use tracing::{debug, error, info};

use crate::api::LnFederationApi;
use crate::{LightningClientContext, LightningClientStateMachines, ReceivingKey};

const RETRY_DELAY: Duration = Duration::from_secs(1);

#[cfg_attr(doc, aquamarine::aquamarine)]
/// State machine that waits on the receipt of a Lightning payment.
///
/// ```mermaid
/// graph LR
/// classDef virtual fill:#fff,stroke-dasharray: 5 5
///
///     SubmittedOffer -- await transaction rejection --> Canceled
///     SubmittedOffer -- await invoice confirmation --> ConfirmedInvoice
///     ConfirmedInvoice -- await contract creation + decryption  --> Funded
///     ConfirmedInvoice -- await offer timeout --> Canceled
///     Funded -- await claim tx acceptance --> Success
///     Funded -- await claim tx rejection --> Canceled
/// ```
#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
pub enum LightningReceiveStates {
    SubmittedOffer(LightningReceiveSubmittedOffer),
    Canceled(LightningReceiveError),
    ConfirmedInvoice(LightningReceiveConfirmedInvoice),
    Funded(LightningReceiveFunded),
    Success(Vec<OutPoint>),
}

#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
pub struct LightningReceiveStateMachine {
    pub operation_id: OperationId,
    pub state: LightningReceiveStates,
}

impl State for LightningReceiveStateMachine {
    type ModuleContext = LightningClientContext;

    fn transitions(
        &self,
        _context: &Self::ModuleContext,
        global_context: &DynGlobalClientContext,
    ) -> Vec<StateTransition<Self>> {
        match &self.state {
            LightningReceiveStates::SubmittedOffer(submitted_offer) => {
                submitted_offer.transitions(global_context)
            }
            LightningReceiveStates::ConfirmedInvoice(confirmed_invoice) => {
                confirmed_invoice.transitions(global_context)
            }
            LightningReceiveStates::Funded(funded) => funded.transitions(global_context),
            LightningReceiveStates::Success(_) | LightningReceiveStates::Canceled(_) => {
                vec![]
            }
        }
    }

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

impl IntoDynInstance for LightningReceiveStateMachine {
    type DynType = DynState;

    fn into_dyn(self, instance_id: ModuleInstanceId) -> Self::DynType {
        DynState::from_typed(instance_id, self)
    }
}

/// Old version of `LightningReceiveSubmittedOffer`, used for migrations
#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
pub struct LightningReceiveSubmittedOfferV0 {
    pub offer_txid: TransactionId,
    pub invoice: Bolt11Invoice,
    pub payment_keypair: KeyPair,
}

#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
pub struct LightningReceiveSubmittedOffer {
    pub offer_txid: TransactionId,
    pub invoice: Bolt11Invoice,
    pub receiving_key: ReceivingKey,
}

#[derive(
    Error, Clone, Debug, Serialize, Deserialize, Encodable, Decodable, Eq, PartialEq, Hash,
)]
#[serde(rename_all = "snake_case")]
pub enum LightningReceiveError {
    #[error("Offer transaction was rejected")]
    Rejected,
    #[error("Incoming Lightning invoice was not paid within the timeout")]
    Timeout,
    #[error("Claim transaction was rejected")]
    ClaimRejected,
    #[error("The decrypted preimage was invalid")]
    InvalidPreimage,
}

impl LightningReceiveSubmittedOffer {
    fn transitions(
        &self,
        global_context: &DynGlobalClientContext,
    ) -> Vec<StateTransition<LightningReceiveStateMachine>> {
        let global_context = global_context.clone();
        let txid = self.offer_txid;
        let invoice = self.invoice.clone();
        let receiving_key = self.receiving_key;
        vec![StateTransition::new(
            Self::await_invoice_confirmation(global_context, txid),
            move |_dbtx, result, old_state| {
                let invoice = invoice.clone();
                Box::pin(async move {
                    Self::transition_confirmed_invoice(&result, &old_state, invoice, receiving_key)
                })
            },
        )]
    }

    async fn await_invoice_confirmation(
        global_context: DynGlobalClientContext,
        txid: TransactionId,
    ) -> Result<(), String> {
        // No network calls are done here, we just await other state machines, so no
        // retry logic is needed
        global_context.await_tx_accepted(txid).await
    }

    fn transition_confirmed_invoice(
        result: &Result<(), String>,
        old_state: &LightningReceiveStateMachine,
        invoice: Bolt11Invoice,
        receiving_key: ReceivingKey,
    ) -> LightningReceiveStateMachine {
        match result {
            Ok(()) => LightningReceiveStateMachine {
                operation_id: old_state.operation_id,
                state: LightningReceiveStates::ConfirmedInvoice(LightningReceiveConfirmedInvoice {
                    invoice,
                    receiving_key,
                }),
            },
            Err(_) => LightningReceiveStateMachine {
                operation_id: old_state.operation_id,
                state: LightningReceiveStates::Canceled(LightningReceiveError::Rejected),
            },
        }
    }
}

#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
pub struct LightningReceiveConfirmedInvoice {
    pub(crate) invoice: Bolt11Invoice,
    pub(crate) receiving_key: ReceivingKey,
}

impl LightningReceiveConfirmedInvoice {
    fn transitions(
        &self,
        global_context: &DynGlobalClientContext,
    ) -> Vec<StateTransition<LightningReceiveStateMachine>> {
        let invoice = self.invoice.clone();
        let receiving_key = self.receiving_key;
        let global_context = global_context.clone();
        vec![StateTransition::new(
            Self::await_incoming_contract_account(invoice, global_context.clone()),
            move |dbtx, contract, old_state| {
                Box::pin(Self::transition_funded(
                    old_state,
                    receiving_key,
                    contract,
                    dbtx,
                    global_context.clone(),
                ))
            },
        )]
    }

    async fn await_incoming_contract_account(
        invoice: Bolt11Invoice,
        global_context: DynGlobalClientContext,
    ) -> Result<IncomingContractAccount, LightningReceiveError> {
        let contract_id = (*invoice.payment_hash()).into();
        loop {
            // Consider time before the api call to account for network delays
            let now_epoch = fedimint_core::time::duration_since_epoch();
            match get_incoming_contract(global_context.module_api(), contract_id).await {
                Ok(Some(incoming_contract_account)) => {
                    match incoming_contract_account.contract.decrypted_preimage {
                        DecryptedPreimage::Pending => {
                            // Previously we would time out here but we may miss a payment if we do
                            // so
                            info!("Waiting for preimage decryption for contract {contract_id}");
                        }
                        DecryptedPreimage::Some(_) => return Ok(incoming_contract_account),
                        DecryptedPreimage::Invalid => {
                            return Err(LightningReceiveError::InvalidPreimage)
                        }
                    }
                }
                Ok(None) => {
                    // only when we are sure that the invoice is still pending that we can
                    // check for a timeout
                    const CLOCK_SKEW_TOLERANCE: Duration = Duration::from_secs(60);
                    if has_invoice_expired(&invoice, now_epoch, CLOCK_SKEW_TOLERANCE) {
                        return Err(LightningReceiveError::Timeout);
                    }
                    debug!("Still waiting preimage decryption for contract {contract_id}");
                }
                Err(error) => {
                    error.report_if_important();
                    info!("External LN payment retryable error waiting for preimage decryption: {error:?}");
                }
            }
            sleep(RETRY_DELAY).await;
        }
    }

    async fn transition_funded(
        old_state: LightningReceiveStateMachine,
        receiving_key: ReceivingKey,
        result: Result<IncomingContractAccount, LightningReceiveError>,
        dbtx: &mut ClientSMDatabaseTransaction<'_, '_>,
        global_context: DynGlobalClientContext,
    ) -> LightningReceiveStateMachine {
        match result {
            Ok(contract) => {
                match receiving_key {
                    ReceivingKey::Personal(keypair) => {
                        let (txid, out_points) =
                            Self::claim_incoming_contract(dbtx, contract, keypair, global_context)
                                .await;
                        LightningReceiveStateMachine {
                            operation_id: old_state.operation_id,
                            state: LightningReceiveStates::Funded(LightningReceiveFunded {
                                txid,
                                out_points,
                            }),
                        }
                    }
                    ReceivingKey::External(_) => {
                        // Claim successful
                        LightningReceiveStateMachine {
                            operation_id: old_state.operation_id,
                            state: LightningReceiveStates::Success(vec![]),
                        }
                    }
                }
            }
            Err(e) => LightningReceiveStateMachine {
                operation_id: old_state.operation_id,
                state: LightningReceiveStates::Canceled(e),
            },
        }
    }

    async fn claim_incoming_contract(
        dbtx: &mut ClientSMDatabaseTransaction<'_, '_>,
        contract: IncomingContractAccount,
        keypair: KeyPair,
        global_context: DynGlobalClientContext,
    ) -> (TransactionId, Vec<OutPoint>) {
        let input = contract.claim();
        let client_input = ClientInput::<LightningInput, LightningClientStateMachines> {
            input,
            amount: contract.amount,
            keys: vec![keypair],
            // The input of the refund tx is managed by this state machine, so no new state machines
            // need to be created
            state_machines: Arc::new(|_, _| vec![]),
        };

        global_context
            .claim_input(dbtx, client_input)
            .await
            .expect("Cannot claim input, additional funding needed")
    }
}

fn has_invoice_expired(
    invoice: &Bolt11Invoice,
    now_epoch: Duration,
    clock_skew_tolerance: Duration,
) -> bool {
    assert!(now_epoch >= clock_skew_tolerance);
    // tolerate some clock skew
    invoice.would_expire(now_epoch - clock_skew_tolerance)
}

pub async fn get_incoming_contract(
    module_api: DynModuleApi,
    contract_id: fedimint_ln_common::contracts::ContractId,
) -> Result<Option<IncomingContractAccount>, fedimint_api_client::api::FederationError> {
    match module_api.fetch_contract(contract_id).await {
        Ok(Some(contract)) => {
            if let FundedContract::Incoming(incoming) = contract.contract {
                Ok(Some(IncomingContractAccount {
                    amount: contract.amount,
                    contract: incoming.contract,
                }))
            } else {
                Err(fedimint_api_client::api::FederationError::general(
                    ACCOUNT_ENDPOINT,
                    contract_id,
                    anyhow::anyhow!("Contract {contract_id} is not an incoming contract"),
                ))
            }
        }
        Ok(None) => Ok(None),
        Err(e) => Err(e),
    }
}

#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
pub struct LightningReceiveFunded {
    txid: TransactionId,
    out_points: Vec<OutPoint>,
}

impl LightningReceiveFunded {
    fn transitions(
        &self,
        global_context: &DynGlobalClientContext,
    ) -> Vec<StateTransition<LightningReceiveStateMachine>> {
        let out_points = self.out_points.clone();
        vec![StateTransition::new(
            Self::await_claim_success(global_context.clone(), self.txid),
            move |_dbtx, result, old_state| {
                let out_points = out_points.clone();
                Box::pin(
                    async move { Self::transition_claim_success(&result, &old_state, out_points) },
                )
            },
        )]
    }

    async fn await_claim_success(
        global_context: DynGlobalClientContext,
        txid: TransactionId,
    ) -> Result<(), String> {
        // No network calls are done here, we just await other state machines, so no
        // retry logic is needed
        global_context.await_tx_accepted(txid).await
    }

    fn transition_claim_success(
        result: &Result<(), String>,
        old_state: &LightningReceiveStateMachine,
        out_points: Vec<OutPoint>,
    ) -> LightningReceiveStateMachine {
        match result {
            Ok(()) => {
                // Claim successful
                LightningReceiveStateMachine {
                    operation_id: old_state.operation_id,
                    state: LightningReceiveStates::Success(out_points),
                }
            }
            Err(_) => {
                // Claim rejection
                LightningReceiveStateMachine {
                    operation_id: old_state.operation_id,
                    state: LightningReceiveStates::Canceled(LightningReceiveError::ClaimRejected),
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use bitcoin::hashes::{sha256, Hash};
    use lightning_invoice::{Currency, InvoiceBuilder, PaymentSecret};
    use secp256k1::SecretKey;

    use super::*;

    #[test]
    fn test_invoice_expiration() -> anyhow::Result<()> {
        let now = fedimint_core::time::duration_since_epoch();
        let one_second = Duration::from_secs(1);
        for expiration in [one_second, Duration::from_secs(3600)] {
            for tolerance in [one_second, Duration::from_secs(60)] {
                let invoice = invoice(now, expiration)?;
                assert!(!has_invoice_expired(&invoice, now - one_second, tolerance));
                assert!(!has_invoice_expired(&invoice, now, tolerance));
                assert!(!has_invoice_expired(&invoice, now + expiration, tolerance));
                assert!(!has_invoice_expired(
                    &invoice,
                    now + expiration + tolerance - one_second,
                    tolerance
                ));
                assert!(has_invoice_expired(
                    &invoice,
                    now + expiration + tolerance,
                    tolerance
                ));
                assert!(has_invoice_expired(
                    &invoice,
                    now + expiration + tolerance + one_second,
                    tolerance
                ));
            }
        }
        Ok(())
    }

    fn invoice(now_epoch: Duration, expiry_time: Duration) -> anyhow::Result<Bolt11Invoice> {
        let ctx = secp256k1::Secp256k1::new();
        let secret_key = SecretKey::new(&mut rand::thread_rng());
        Ok(InvoiceBuilder::new(Currency::Regtest)
            .description(String::new())
            .payment_hash(sha256::Hash::hash(&[0; 32]))
            .duration_since_epoch(now_epoch)
            .min_final_cltv_expiry_delta(0)
            .payment_secret(PaymentSecret([0; 32]))
            .amount_milli_satoshis(1000)
            .expiry_time(expiry_time)
            .build_signed(|m| ctx.sign_ecdsa_recoverable(m, &secret_key))?)
    }
}