Skip to main content

fedimint_ln_client/
lib.rs

1#![deny(clippy::pedantic)]
2#![allow(clippy::cast_possible_truncation)]
3#![allow(clippy::missing_errors_doc)]
4#![allow(clippy::missing_panics_doc)]
5#![allow(clippy::module_name_repetitions)]
6#![allow(clippy::must_use_candidate)]
7#![allow(clippy::too_many_lines)]
8
9pub use fedimint_ln_common as common;
10
11pub mod api;
12#[cfg(feature = "cli")]
13pub mod cli;
14pub mod db;
15pub mod events;
16pub mod incoming;
17pub mod pay;
18pub mod receive;
19/// Implements recurring payment codes (e.g. LNURL, BOLT12)
20pub mod recurring;
21
22use std::collections::{BTreeMap, BTreeSet};
23use std::iter::once;
24use std::str::FromStr;
25use std::sync::Arc;
26use std::time::Duration;
27
28use anyhow::{Context, anyhow, bail, ensure, format_err};
29use api::LnFederationApi;
30use async_stream::{stream, try_stream};
31use bitcoin::Network;
32use bitcoin::hashes::{Hash, HashEngine, Hmac, HmacEngine, sha256};
33use db::{
34    DbKeyPrefix, LightningGatewayKey, LightningGatewayKeyPrefix, PaymentResult, PaymentResultKey,
35    RecurringPaymentCodeKeyPrefix,
36};
37use fedimint_api_client::api::{DynModuleApi, ServerError};
38use fedimint_client_module::db::{ClientModuleMigrationFn, migrate_state};
39use fedimint_client_module::module::init::{ClientModuleInit, ClientModuleInitArgs};
40use fedimint_client_module::module::recovery::NoModuleBackup;
41use fedimint_client_module::module::{ClientContext, ClientModule, IClientModule, OutPointRange};
42use fedimint_client_module::oplog::UpdateStreamOrOutcome;
43use fedimint_client_module::sm::{DynState, ModuleNotifier, State, StateTransition};
44use fedimint_client_module::transaction::{
45    ClientInput, ClientInputBundle, ClientOutput, ClientOutputBundle, ClientOutputSM,
46    TransactionBuilder,
47};
48use fedimint_client_module::{DynGlobalClientContext, sm_enum_variant_translation};
49use fedimint_core::config::FederationId;
50use fedimint_core::core::{Decoder, IntoDynInstance, ModuleInstanceId, ModuleKind, OperationId};
51use fedimint_core::db::{DatabaseTransaction, DatabaseVersion, IDatabaseTransactionOpsCoreTyped};
52use fedimint_core::encoding::{Decodable, Encodable};
53use fedimint_core::module::{
54    Amounts, ApiVersion, CommonModuleInit, ModuleCommon, ModuleInit, MultiApiVersion,
55};
56use fedimint_core::secp256k1::{
57    All, Keypair, PublicKey, Scalar, Secp256k1, SecretKey, Signing, Verification,
58};
59use fedimint_core::task::{MaybeSend, MaybeSync, timeout};
60use fedimint_core::util::update_merge::UpdateMerge;
61use fedimint_core::util::{BoxStream, FmtCompactAnyhow as _, backoff_util, retry};
62use fedimint_core::{
63    Amount, OutPoint, apply, async_trait_maybe_send, push_db_pair_items, runtime, secp256k1,
64};
65use fedimint_derive_secret::{ChildId, DerivableSecret};
66use fedimint_ln_common::client::GatewayApi;
67use fedimint_ln_common::config::{FeeToAmount, LightningClientConfig};
68use fedimint_ln_common::contracts::incoming::{IncomingContract, IncomingContractOffer};
69use fedimint_ln_common::contracts::outgoing::{
70    OutgoingContract, OutgoingContractAccount, OutgoingContractData,
71};
72use fedimint_ln_common::contracts::{
73    Contract, ContractId, DecryptedPreimage, EncryptedPreimage, IdentifiableContract, Preimage,
74    PreimageKey,
75};
76use fedimint_ln_common::gateway_endpoint_constants::{
77    GET_GATEWAY_ID_ENDPOINT, PAY_INVOICE_ENDPOINT,
78};
79use fedimint_ln_common::{
80    ContractOutput, KIND, LightningCommonInit, LightningGateway, LightningGatewayAnnouncement,
81    LightningGatewayRegistration, LightningInput, LightningModuleTypes, LightningOutput,
82    LightningOutputV0,
83};
84use fedimint_logging::LOG_CLIENT_MODULE_LN;
85use futures::{Future, StreamExt};
86use incoming::IncomingSmError;
87use itertools::Itertools;
88use lightning_invoice::{
89    Bolt11Invoice, Currency, InvoiceBuilder, PaymentSecret, RouteHint, RouteHintHop, RoutingFees,
90};
91use pay::PayInvoicePayload;
92use rand::rngs::OsRng;
93use rand::seq::IteratorRandom as _;
94use rand::{CryptoRng, Rng, RngCore};
95use reqwest::Method;
96use serde::{Deserialize, Serialize};
97use strum::IntoEnumIterator;
98use tokio::sync::Notify;
99use tracing::{debug, error, info};
100
101use crate::db::PaymentResultPrefix;
102use crate::incoming::{
103    FundingOfferState, IncomingSmCommon, IncomingSmStates, IncomingStateMachine,
104};
105use crate::pay::lightningpay::LightningPayStates;
106use crate::pay::{
107    GatewayPayError, LightningPayCommon, LightningPayCreatedOutgoingLnContract,
108    LightningPayStateMachine,
109};
110use crate::receive::{
111    LightningReceiveError, LightningReceiveStateMachine, LightningReceiveStates,
112    LightningReceiveSubmittedOffer, get_incoming_contract,
113};
114use crate::recurring::RecurringPaymentCodeEntry;
115
116/// Number of blocks until outgoing lightning contracts times out and user
117/// client can get refund
118const OUTGOING_LN_CONTRACT_TIMELOCK: u64 = 500;
119
120// 24 hours. Many wallets default to 1 hour, but it's a bad user experience if
121// invoices expire too quickly
122const DEFAULT_INVOICE_EXPIRY_TIME: Duration = Duration::from_hours(24);
123
124#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize, Encodable, Decodable)]
125#[serde(rename_all = "snake_case")]
126pub enum PayType {
127    // Payment from this client to another user within the federation
128    Internal(OperationId),
129    // Payment from this client to another user, facilitated by a gateway
130    Lightning(OperationId),
131}
132
133impl PayType {
134    pub fn operation_id(&self) -> OperationId {
135        match self {
136            PayType::Internal(operation_id) | PayType::Lightning(operation_id) => *operation_id,
137        }
138    }
139
140    pub fn payment_type(&self) -> String {
141        match self {
142            PayType::Internal(_) => "internal",
143            PayType::Lightning(_) => "lightning",
144        }
145        .into()
146    }
147}
148
149/// Where to receive the payment to, either to ourselves or to another user
150#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Serialize, Deserialize, Encodable, Decodable)]
151pub enum ReceivingKey {
152    /// The keypair used to receive payments for ourselves, we will use this to
153    /// sweep to our own ecash wallet on success
154    Personal(Keypair),
155    /// A public key of another user, the lightning payment will be locked to
156    /// this key for them to claim on success
157    External(PublicKey),
158}
159
160impl ReceivingKey {
161    /// The public key of the receiving key
162    pub fn public_key(&self) -> PublicKey {
163        match self {
164            ReceivingKey::Personal(keypair) => keypair.public_key(),
165            ReceivingKey::External(public_key) => *public_key,
166        }
167    }
168}
169
170#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
171pub enum LightningPaymentOutcome {
172    Success { preimage: String },
173    Failure { error_message: String },
174}
175
176/// The high-level state of an pay operation internal to the federation,
177/// started with [`LightningClientModule::pay_bolt11_invoice`].
178#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
179#[serde(rename_all = "snake_case")]
180pub enum InternalPayState {
181    Funding,
182    Preimage(Preimage),
183    RefundSuccess {
184        out_points: Vec<OutPoint>,
185        error: IncomingSmError,
186    },
187    RefundError {
188        error_message: String,
189        error: IncomingSmError,
190    },
191    FundingFailed {
192        error: IncomingSmError,
193    },
194    UnexpectedError(String),
195}
196
197/// The high-level state of a pay operation over lightning,
198/// started with [`LightningClientModule::pay_bolt11_invoice`].
199#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
200#[serde(rename_all = "snake_case")]
201pub enum LnPayState {
202    Created,
203    Canceled,
204    Funded { block_height: u32 },
205    WaitingForRefund { error_reason: String },
206    AwaitingChange,
207    Success { preimage: String },
208    Refunded { gateway_error: GatewayPayError },
209    UnexpectedError { error_message: String },
210}
211
212/// The high-level state of a reissue operation started with
213/// [`LightningClientModule::create_bolt11_invoice`].
214#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
215#[serde(rename_all = "snake_case")]
216pub enum LnReceiveState {
217    Created,
218    WaitingForPayment { invoice: String, timeout: Duration },
219    Canceled { reason: LightningReceiveError },
220    Funded,
221    AwaitingFunds,
222    Claimed,
223}
224
225fn invoice_has_internal_payment_markers(
226    invoice: &Bolt11Invoice,
227    markers: (fedimint_core::secp256k1::PublicKey, u64),
228) -> bool {
229    // Asserts that the invoice src_node_id and short_channel_id match known
230    // values used as internal payment markers
231    invoice
232        .route_hints()
233        .first()
234        .and_then(|rh| rh.0.last())
235        .map(|hop| (hop.src_node_id, hop.short_channel_id))
236        == Some(markers)
237}
238
239fn invoice_routes_back_to_federation(
240    invoice: &Bolt11Invoice,
241    gateways: Vec<LightningGateway>,
242) -> bool {
243    gateways.into_iter().any(|gateway| {
244        invoice
245            .route_hints()
246            .first()
247            .and_then(|rh| rh.0.last())
248            .map(|hop| (hop.src_node_id, hop.short_channel_id))
249            == Some((gateway.node_pub_key, gateway.federation_index))
250    })
251}
252
253#[derive(Debug, Clone, Serialize, Deserialize)]
254#[serde(rename_all = "snake_case")]
255pub struct LightningOperationMetaPay {
256    pub out_point: OutPoint,
257    pub invoice: Bolt11Invoice,
258    pub fee: Amount,
259    pub change: Vec<OutPoint>,
260    pub is_internal_payment: bool,
261    pub contract_id: ContractId,
262    pub gateway_id: Option<secp256k1::PublicKey>,
263}
264
265#[derive(Debug, Clone, Serialize, Deserialize)]
266pub struct LightningOperationMeta {
267    pub variant: LightningOperationMetaVariant,
268    pub extra_meta: serde_json::Value,
269}
270
271pub use deprecated_variant_hack::LightningOperationMetaVariant;
272
273/// This is a hack to allow us to use the deprecated variant in the database
274/// without the serde derived implementation throwing warnings.
275///
276/// See <https://github.com/serde-rs/serde/issues/2195>
277#[allow(deprecated)]
278mod deprecated_variant_hack {
279    use super::{
280        Bolt11Invoice, Deserialize, LightningOperationMetaPay, OutPoint, Serialize, secp256k1,
281    };
282    use crate::recurring::ReurringPaymentReceiveMeta;
283
284    #[derive(Debug, Clone, Serialize, Deserialize)]
285    #[serde(rename_all = "snake_case")]
286    pub enum LightningOperationMetaVariant {
287        Pay(LightningOperationMetaPay),
288        Receive {
289            out_point: OutPoint,
290            invoice: Bolt11Invoice,
291            gateway_id: Option<secp256k1::PublicKey>,
292        },
293        #[deprecated(
294            since = "0.7.0",
295            note = "Use recurring payment functionality instead instead"
296        )]
297        Claim {
298            out_points: Vec<OutPoint>,
299        },
300        RecurringPaymentReceive(ReurringPaymentReceiveMeta),
301    }
302}
303
304#[derive(Debug, Clone, Default)]
305pub struct LightningClientInit {
306    pub gateway_conn: Option<Arc<dyn GatewayConnection + Send + Sync>>,
307}
308
309impl ModuleInit for LightningClientInit {
310    type Common = LightningCommonInit;
311
312    async fn dump_database(
313        &self,
314        dbtx: &mut DatabaseTransaction<'_>,
315        prefix_names: Vec<String>,
316    ) -> Box<dyn Iterator<Item = (String, Box<dyn erased_serde::Serialize + Send>)> + '_> {
317        let mut ln_client_items: BTreeMap<String, Box<dyn erased_serde::Serialize + Send>> =
318            BTreeMap::new();
319        let filtered_prefixes = DbKeyPrefix::iter().filter(|f| {
320            prefix_names.is_empty() || prefix_names.contains(&f.to_string().to_lowercase())
321        });
322
323        for table in filtered_prefixes {
324            #[allow(clippy::match_same_arms)]
325            match table {
326                DbKeyPrefix::ActiveGateway | DbKeyPrefix::MetaOverridesDeprecated => {
327                    // Deprecated
328                }
329                DbKeyPrefix::PaymentResult => {
330                    push_db_pair_items!(
331                        dbtx,
332                        PaymentResultPrefix,
333                        PaymentResultKey,
334                        PaymentResult,
335                        ln_client_items,
336                        "Payment Result"
337                    );
338                }
339                DbKeyPrefix::LightningGateway => {
340                    push_db_pair_items!(
341                        dbtx,
342                        LightningGatewayKeyPrefix,
343                        LightningGatewayKey,
344                        LightningGatewayRegistration,
345                        ln_client_items,
346                        "Lightning Gateways"
347                    );
348                }
349                DbKeyPrefix::RecurringPaymentKey => {
350                    push_db_pair_items!(
351                        dbtx,
352                        RecurringPaymentCodeKeyPrefix,
353                        RecurringPaymentCodeKey,
354                        RecurringPaymentCodeEntry,
355                        ln_client_items,
356                        "Recurring Payment Code"
357                    );
358                }
359                DbKeyPrefix::ExternalReservedStart
360                | DbKeyPrefix::CoreInternalReservedStart
361                | DbKeyPrefix::CoreInternalReservedEnd => {}
362            }
363        }
364
365        Box::new(ln_client_items.into_iter())
366    }
367}
368
369#[derive(Debug)]
370#[repr(u64)]
371pub enum LightningChildKeys {
372    RedeemKey = 0,
373    PreimageAuthentication = 1,
374    RecurringPaymentCodeSecret = 2,
375}
376
377#[apply(async_trait_maybe_send!)]
378impl ClientModuleInit for LightningClientInit {
379    type Module = LightningClientModule;
380
381    fn supported_api_versions(&self) -> MultiApiVersion {
382        MultiApiVersion::try_from_iter([ApiVersion { major: 0, minor: 0 }])
383            .expect("no version conflicts")
384    }
385
386    async fn init(&self, args: &ClientModuleInitArgs<Self>) -> anyhow::Result<Self::Module> {
387        let gateway_conn = if let Some(gateway_conn) = self.gateway_conn.clone() {
388            gateway_conn
389        } else {
390            let api = GatewayApi::new(None, args.connector_registry.clone());
391            Arc::new(RealGatewayConnection { api })
392        };
393        Ok(LightningClientModule::new(args, gateway_conn))
394    }
395
396    fn get_database_migrations(&self) -> BTreeMap<DatabaseVersion, ClientModuleMigrationFn> {
397        let mut migrations: BTreeMap<DatabaseVersion, ClientModuleMigrationFn> = BTreeMap::new();
398        migrations.insert(DatabaseVersion(0), |dbtx, _, _| {
399            Box::pin(async {
400                dbtx.remove_entry(&crate::db::ActiveGatewayKey).await;
401                Ok(None)
402            })
403        });
404
405        migrations.insert(DatabaseVersion(1), |_, active_states, inactive_states| {
406            Box::pin(async {
407                migrate_state(active_states, inactive_states, db::get_v1_migrated_state)
408            })
409        });
410
411        migrations.insert(DatabaseVersion(2), |_, active_states, inactive_states| {
412            Box::pin(async {
413                migrate_state(active_states, inactive_states, db::get_v2_migrated_state)
414            })
415        });
416
417        migrations.insert(DatabaseVersion(3), |_, active_states, inactive_states| {
418            Box::pin(async {
419                migrate_state(active_states, inactive_states, db::get_v3_migrated_state)
420            })
421        });
422
423        migrations
424    }
425
426    fn used_db_prefixes(&self) -> Option<BTreeSet<u8>> {
427        Some(
428            DbKeyPrefix::iter()
429                .map(|p| p as u8)
430                .chain(
431                    DbKeyPrefix::ExternalReservedStart as u8
432                        ..=DbKeyPrefix::CoreInternalReservedEnd as u8,
433                )
434                .collect(),
435        )
436    }
437}
438
439/// Client side lightning module
440///
441/// Note that lightning gateways use a different version
442/// of client side module.
443#[derive(Debug)]
444pub struct LightningClientModule {
445    pub cfg: LightningClientConfig,
446    notifier: ModuleNotifier<LightningClientStateMachines>,
447    redeem_key: Keypair,
448    recurring_payment_code_secret: DerivableSecret,
449    secp: Secp256k1<All>,
450    module_api: DynModuleApi,
451    preimage_auth: Keypair,
452    client_ctx: ClientContext<Self>,
453    update_gateway_cache_merge: UpdateMerge,
454    gateway_conn: Arc<dyn GatewayConnection + Send + Sync>,
455    new_recurring_payment_code: Arc<Notify>,
456}
457
458#[apply(async_trait_maybe_send!)]
459impl ClientModule for LightningClientModule {
460    type Init = LightningClientInit;
461    type Common = LightningModuleTypes;
462    type Backup = NoModuleBackup;
463    type ModuleStateMachineContext = LightningClientContext;
464    type States = LightningClientStateMachines;
465
466    fn context(&self) -> Self::ModuleStateMachineContext {
467        LightningClientContext {
468            ln_decoder: self.decoder(),
469            redeem_key: self.redeem_key,
470            gateway_conn: self.gateway_conn.clone(),
471            client_ctx: Some(self.client_ctx.clone()),
472        }
473    }
474
475    fn input_fee(
476        &self,
477        _amount: &Amounts,
478        _input: &<Self::Common as ModuleCommon>::Input,
479    ) -> Option<Amounts> {
480        Some(Amounts::new_bitcoin(self.cfg.fee_consensus.contract_input))
481    }
482
483    fn output_fee(
484        &self,
485        _amount: &Amounts,
486        output: &<Self::Common as ModuleCommon>::Output,
487    ) -> Option<Amounts> {
488        match output.maybe_v0_ref()? {
489            LightningOutputV0::Contract(_) => {
490                Some(Amounts::new_bitcoin(self.cfg.fee_consensus.contract_output))
491            }
492            LightningOutputV0::Offer(_) | LightningOutputV0::CancelOutgoing { .. } => {
493                Some(Amounts::ZERO)
494            }
495        }
496    }
497
498    #[cfg(feature = "cli")]
499    async fn handle_cli_command(
500        &self,
501        args: &[std::ffi::OsString],
502    ) -> anyhow::Result<serde_json::Value> {
503        cli::handle_cli_command(self, args).await
504    }
505
506    async fn handle_rpc(
507        &self,
508        method: String,
509        payload: serde_json::Value,
510    ) -> BoxStream<'_, anyhow::Result<serde_json::Value>> {
511        Box::pin(try_stream! {
512            match method.as_str() {
513                "create_bolt11_invoice" => {
514                    let req: CreateBolt11InvoiceRequest = serde_json::from_value(payload)?;
515                    let (op, invoice, _) = self
516                        .create_bolt11_invoice(
517                            req.amount,
518                            lightning_invoice::Bolt11InvoiceDescription::Direct(
519                                lightning_invoice::Description::new(req.description)?,
520                            ),
521                            req.expiry_time,
522                            req.extra_meta,
523                            req.gateway,
524                        )
525                        .await?;
526                    yield serde_json::json!({
527                        "operation_id": op,
528                        "invoice": invoice,
529                    });
530                }
531                "pay_bolt11_invoice" => {
532                    let req: PayBolt11InvoiceRequest = serde_json::from_value(payload)?;
533                    let outgoing_payment = self
534                        .pay_bolt11_invoice(req.maybe_gateway, req.invoice, req.extra_meta)
535                        .await?;
536                    yield serde_json::to_value(outgoing_payment)?;
537                }
538                "select_available_gateway" => {
539                    let req: SelectAvailableGatewayRequest = serde_json::from_value(payload)?;
540                    let gateway = self.select_available_gateway(req.maybe_gateway,req.maybe_invoice).await?;
541                    yield serde_json::to_value(gateway)?;
542                }
543                "subscribe_ln_pay" => {
544                    let req: SubscribeLnPayRequest = serde_json::from_value(payload)?;
545                    for await state in self.subscribe_ln_pay(req.operation_id).await?.into_stream() {
546                        yield serde_json::to_value(state)?;
547                    }
548                }
549                "subscribe_internal_pay" => {
550                    let req: SubscribeInternalPayRequest = serde_json::from_value(payload)?;
551                    for await state in self.subscribe_internal_pay(req.operation_id).await?.into_stream() {
552                        yield serde_json::to_value(state)?;
553                    }
554                }
555                "subscribe_ln_receive" => {
556                    let req: SubscribeLnReceiveRequest = serde_json::from_value(payload)?;
557                    for await state in self.subscribe_ln_receive(req.operation_id).await?.into_stream()
558                    {
559                        yield serde_json::to_value(state)?;
560                    }
561                }
562                "create_bolt11_invoice_for_user_tweaked" => {
563                    let req: CreateBolt11InvoiceForUserTweakedRequest = serde_json::from_value(payload)?;
564                    let (op, invoice, _) = self
565                        .create_bolt11_invoice_for_user_tweaked(
566                            req.amount,
567                            lightning_invoice::Bolt11InvoiceDescription::Direct(
568                                lightning_invoice::Description::new(req.description)?,
569                            ),
570                            req.expiry_time,
571                            req.user_key,
572                            req.index,
573                            req.extra_meta,
574                            req.gateway,
575                        )
576                        .await?;
577                    yield serde_json::json!({
578                        "operation_id": op,
579                        "invoice": invoice,
580                    });
581                }
582                #[allow(deprecated)]
583                "scan_receive_for_user_tweaked" => {
584                    let req: ScanReceiveForUserTweakedRequest = serde_json::from_value(payload)?;
585                    let keypair = Keypair::from_secret_key(&self.secp, &req.user_key);
586                    let operation_ids = self.scan_receive_for_user_tweaked(keypair, req.indices, req.extra_meta).await;
587                    yield serde_json::to_value(operation_ids)?;
588                }
589                #[allow(deprecated)]
590                "subscribe_ln_claim" => {
591                    let req: SubscribeLnClaimRequest = serde_json::from_value(payload)?;
592                    for await state in self.subscribe_ln_claim(req.operation_id).await?.into_stream() {
593                        yield serde_json::to_value(state)?;
594                    }
595                }
596                "get_gateway" => {
597                    let req: GetGatewayRequest = serde_json::from_value(payload)?;
598                    let gateway = self.get_gateway(req.gateway_id, req.force_internal).await?;
599                    yield serde_json::to_value(gateway)?;
600                }
601                "list_gateways" => {
602                    let gateways = self.list_gateways().await;
603                    yield serde_json::to_value(gateways)?;
604                }
605                "update_gateway_cache" => {
606                    self.update_gateway_cache().await?;
607                    yield serde_json::Value::Null;
608                }
609                "pay_lightning_address" => {
610                    let req: PayLightningAddressRequest = serde_json::from_value(payload)?;
611                    let invoice = get_invoice(&req.address, Some(Amount::from_msats(req.amount)), None).await?;
612                    let gateway = self.get_gateway(None, false).await?;
613                    let output = self.pay_bolt11_invoice(gateway, invoice, ()).await?;
614
615                    yield serde_json::to_value(output)?;
616                }
617                _ => {
618                    Err(anyhow::format_err!("Unknown method: {method}"))?;
619                    unreachable!()
620                },
621            }
622        })
623    }
624}
625
626#[derive(Deserialize)]
627struct CreateBolt11InvoiceRequest {
628    amount: Amount,
629    description: String,
630    expiry_time: Option<u64>,
631    extra_meta: serde_json::Value,
632    gateway: Option<LightningGateway>,
633}
634
635#[derive(Deserialize)]
636struct PayBolt11InvoiceRequest {
637    maybe_gateway: Option<LightningGateway>,
638    invoice: Bolt11Invoice,
639    extra_meta: Option<serde_json::Value>,
640}
641
642#[derive(Deserialize)]
643struct SubscribeLnPayRequest {
644    operation_id: OperationId,
645}
646
647#[derive(Deserialize)]
648struct SubscribeInternalPayRequest {
649    operation_id: OperationId,
650}
651
652#[derive(Deserialize)]
653struct SubscribeLnReceiveRequest {
654    operation_id: OperationId,
655}
656
657#[derive(Debug, Serialize, Deserialize)]
658pub struct SelectAvailableGatewayRequest {
659    maybe_gateway: Option<LightningGateway>,
660    maybe_invoice: Option<Bolt11Invoice>,
661}
662
663#[derive(Deserialize)]
664struct CreateBolt11InvoiceForUserTweakedRequest {
665    amount: Amount,
666    description: String,
667    expiry_time: Option<u64>,
668    user_key: PublicKey,
669    index: u64,
670    extra_meta: serde_json::Value,
671    gateway: Option<LightningGateway>,
672}
673
674#[derive(Deserialize)]
675struct ScanReceiveForUserTweakedRequest {
676    user_key: SecretKey,
677    indices: Vec<u64>,
678    extra_meta: serde_json::Value,
679}
680
681#[derive(Deserialize)]
682struct SubscribeLnClaimRequest {
683    operation_id: OperationId,
684}
685
686#[derive(Deserialize)]
687struct GetGatewayRequest {
688    gateway_id: Option<secp256k1::PublicKey>,
689    force_internal: bool,
690}
691
692#[derive(Deserialize)]
693struct PayLightningAddressRequest {
694    address: String,
695    amount: u64,
696}
697
698#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
699pub enum GatewayStatus {
700    OnlineVetted,
701    OnlineNonVetted,
702}
703
704#[derive(thiserror::Error, Debug, Clone)]
705pub enum PayBolt11InvoiceError {
706    #[error("Previous payment attempt({}) still in progress", .operation_id.fmt_full())]
707    PreviousPaymentAttemptStillInProgress { operation_id: OperationId },
708    #[error("No LN gateway available")]
709    NoLnGatewayAvailable,
710    #[error("Funded contract already exists: {}", .contract_id)]
711    FundedContractAlreadyExists { contract_id: ContractId },
712}
713
714impl LightningClientModule {
715    fn new(
716        args: &ClientModuleInitArgs<LightningClientInit>,
717        gateway_conn: Arc<dyn GatewayConnection + Send + Sync>,
718    ) -> Self {
719        let secp = Secp256k1::new();
720
721        let new_recurring_payment_code = Arc::new(Notify::new());
722        args.task_group().spawn_cancellable(
723            "Recurring payment sync",
724            Self::scan_recurring_payment_code_invoices(
725                args.context(),
726                new_recurring_payment_code.clone(),
727            ),
728        );
729
730        Self {
731            cfg: args.cfg().clone(),
732            notifier: args.notifier().clone(),
733            redeem_key: args
734                .module_root_secret()
735                .child_key(ChildId(LightningChildKeys::RedeemKey as u64))
736                .to_secp_key(&secp),
737            recurring_payment_code_secret: args.module_root_secret().child_key(ChildId(
738                LightningChildKeys::RecurringPaymentCodeSecret as u64,
739            )),
740            module_api: args.module_api().clone(),
741            preimage_auth: args
742                .module_root_secret()
743                .child_key(ChildId(LightningChildKeys::PreimageAuthentication as u64))
744                .to_secp_key(&secp),
745            secp,
746            client_ctx: args.context(),
747            update_gateway_cache_merge: UpdateMerge::default(),
748            gateway_conn,
749            new_recurring_payment_code,
750        }
751    }
752
753    pub async fn get_prev_payment_result(
754        &self,
755        payment_hash: &sha256::Hash,
756        dbtx: &mut DatabaseTransaction<'_>,
757    ) -> PaymentResult {
758        let prev_result = dbtx
759            .get_value(&PaymentResultKey {
760                payment_hash: *payment_hash,
761            })
762            .await;
763        prev_result.unwrap_or(PaymentResult {
764            index: 0,
765            completed_payment: None,
766        })
767    }
768
769    fn get_payment_operation_id(payment_hash: &sha256::Hash, index: u16) -> OperationId {
770        // Copy the 32 byte payment hash and a 2 byte index to make every payment
771        // attempt have a unique `OperationId`
772        let mut bytes = [0; 34];
773        bytes[0..32].copy_from_slice(&payment_hash.to_byte_array());
774        bytes[32..34].copy_from_slice(&index.to_le_bytes());
775        let hash: sha256::Hash = Hash::hash(&bytes);
776        OperationId(hash.to_byte_array())
777    }
778
779    /// Hashes the client's preimage authentication secret with the provided
780    /// `payment_hash`. The resulting hash is used when contacting the
781    /// gateway to determine if this client is allowed to be shown the
782    /// preimage.
783    fn get_preimage_authentication(&self, payment_hash: &sha256::Hash) -> sha256::Hash {
784        let mut bytes = [0; 64];
785        bytes[0..32].copy_from_slice(&payment_hash.to_byte_array());
786        bytes[32..64].copy_from_slice(&self.preimage_auth.secret_bytes());
787        Hash::hash(&bytes)
788    }
789
790    /// Create an output that incentivizes a Lightning gateway to pay an invoice
791    /// for us. It has time till the block height defined by `timelock`,
792    /// after that we can claim our money back.
793    async fn create_outgoing_output<'a, 'b>(
794        &'a self,
795        operation_id: OperationId,
796        invoice: Bolt11Invoice,
797        gateway: LightningGateway,
798        fed_id: FederationId,
799        mut rng: impl RngCore + CryptoRng + 'a,
800    ) -> anyhow::Result<(
801        ClientOutput<LightningOutputV0>,
802        ClientOutputSM<LightningClientStateMachines>,
803        ContractId,
804    )> {
805        let federation_currency: Currency = self.cfg.network.0.into();
806        let invoice_currency = invoice.currency();
807        ensure!(
808            federation_currency == invoice_currency,
809            "Invalid invoice currency: expected={federation_currency:?}, got={invoice_currency:?}"
810        );
811
812        // Do not create the funding transaction if the gateway is not currently
813        // available
814        self.gateway_conn
815            .verify_gateway_availability(&gateway)
816            .await?;
817
818        let consensus_count = self
819            .module_api
820            .fetch_consensus_block_count()
821            .await?
822            .ok_or(format_err!("Cannot get consensus block count"))?;
823
824        // Add the timelock to the current block count and the invoice's
825        // `min_cltv_delta`
826        let min_final_cltv = invoice.min_final_cltv_expiry_delta();
827        let absolute_timelock =
828            consensus_count + min_final_cltv + OUTGOING_LN_CONTRACT_TIMELOCK - 1;
829
830        // Compute amount to lock in the outgoing contract
831        let invoice_amount = Amount::from_msats(
832            invoice
833                .amount_milli_satoshis()
834                .context("MissingInvoiceAmount")?,
835        );
836
837        let gateway_fee = gateway.fees.to_amount(&invoice_amount);
838        let contract_amount = invoice_amount + gateway_fee;
839
840        let user_sk = Keypair::new(&self.secp, &mut rng);
841
842        let payment_hash = *invoice.payment_hash();
843        let preimage_auth = self.get_preimage_authentication(&payment_hash);
844        let contract = OutgoingContract {
845            hash: payment_hash,
846            gateway_key: gateway.gateway_redeem_key,
847            timelock: absolute_timelock as u32,
848            user_key: user_sk.public_key(),
849            cancelled: false,
850        };
851
852        let outgoing_payment = OutgoingContractData {
853            recovery_key: user_sk,
854            contract_account: OutgoingContractAccount {
855                amount: contract_amount,
856                contract: contract.clone(),
857            },
858        };
859
860        let contract_id = contract.contract_id();
861        let sm_gen = Arc::new(move |out_point_range: OutPointRange| {
862            vec![LightningClientStateMachines::LightningPay(
863                LightningPayStateMachine {
864                    common: LightningPayCommon {
865                        operation_id,
866                        federation_id: fed_id,
867                        contract: outgoing_payment.clone(),
868                        gateway_fee,
869                        preimage_auth,
870                        invoice: invoice.clone(),
871                    },
872                    state: LightningPayStates::CreatedOutgoingLnContract(
873                        LightningPayCreatedOutgoingLnContract {
874                            funding_txid: out_point_range.txid(),
875                            contract_id,
876                            gateway: gateway.clone(),
877                        },
878                    ),
879                },
880            )]
881        });
882
883        let ln_output = LightningOutputV0::Contract(ContractOutput {
884            amount: contract_amount,
885            contract: Contract::Outgoing(contract),
886        });
887
888        Ok((
889            ClientOutput {
890                output: ln_output,
891                amounts: Amounts::new_bitcoin(contract_amount),
892            },
893            ClientOutputSM {
894                state_machines: sm_gen,
895            },
896            contract_id,
897        ))
898    }
899
900    /// Create an output that funds an incoming contract within the federation
901    /// This directly completes a transaction between users, without involving a
902    /// gateway
903    async fn create_incoming_output(
904        &self,
905        operation_id: OperationId,
906        invoice: Bolt11Invoice,
907    ) -> anyhow::Result<(
908        ClientOutput<LightningOutputV0>,
909        ClientOutputSM<LightningClientStateMachines>,
910        ContractId,
911    )> {
912        let payment_hash = *invoice.payment_hash();
913        let invoice_amount = Amount {
914            msats: invoice
915                .amount_milli_satoshis()
916                .ok_or(IncomingSmError::AmountError {
917                    invoice: invoice.clone(),
918                })?,
919        };
920
921        let (incoming_output, amount, contract_id) = create_incoming_contract_output(
922            &self.module_api,
923            payment_hash,
924            invoice_amount,
925            &self.redeem_key,
926        )
927        .await?;
928
929        let client_output = ClientOutput::<LightningOutputV0> {
930            output: incoming_output,
931            amounts: Amounts::new_bitcoin(amount),
932        };
933
934        let client_output_sm = ClientOutputSM::<LightningClientStateMachines> {
935            state_machines: Arc::new(move |out_point_range| {
936                vec![LightningClientStateMachines::InternalPay(
937                    IncomingStateMachine {
938                        common: IncomingSmCommon {
939                            operation_id,
940                            contract_id,
941                            payment_hash,
942                        },
943                        state: IncomingSmStates::FundingOffer(FundingOfferState {
944                            txid: out_point_range.txid(),
945                        }),
946                    },
947                )]
948            }),
949        };
950
951        Ok((client_output, client_output_sm, contract_id))
952    }
953
954    async fn await_receive_success(
955        &self,
956        operation_id: OperationId,
957    ) -> Result<(), LightningReceiveError> {
958        let mut stream = self.notifier.subscribe(operation_id).await;
959        loop {
960            if let Some(LightningClientStateMachines::Receive(state)) = stream.next().await {
961                match state.state {
962                    LightningReceiveStates::Success(_) => return Ok(()),
963                    LightningReceiveStates::Canceled(e) => {
964                        return Err(e);
965                    }
966                    _ => {}
967                }
968            }
969        }
970    }
971
972    async fn await_claim_acceptance(
973        &self,
974        operation_id: OperationId,
975    ) -> Result<Vec<OutPoint>, LightningReceiveError> {
976        let mut stream = self.notifier.subscribe(operation_id).await;
977        loop {
978            if let Some(LightningClientStateMachines::Receive(state)) = stream.next().await {
979                match state.state {
980                    LightningReceiveStates::Success(out_points) => return Ok(out_points),
981                    LightningReceiveStates::Canceled(e) => {
982                        return Err(e);
983                    }
984                    _ => {}
985                }
986            }
987        }
988    }
989
990    #[allow(clippy::too_many_arguments)]
991    #[allow(clippy::type_complexity)]
992    fn create_lightning_receive_output<'a>(
993        &'a self,
994        amount: Amount,
995        description: lightning_invoice::Bolt11InvoiceDescription,
996        receiving_key: ReceivingKey,
997        mut rng: impl RngCore + CryptoRng + 'a,
998        expiry_time: Option<u64>,
999        src_node_id: secp256k1::PublicKey,
1000        short_channel_id: u64,
1001        route_hints: &[fedimint_ln_common::route_hints::RouteHint],
1002        network: Network,
1003    ) -> anyhow::Result<(
1004        OperationId,
1005        Bolt11Invoice,
1006        ClientOutputBundle<LightningOutput, LightningClientStateMachines>,
1007        [u8; 32],
1008    )> {
1009        let preimage_key: [u8; 33] = receiving_key.public_key().serialize();
1010        let preimage = sha256::Hash::hash(&preimage_key);
1011        let payment_hash = sha256::Hash::hash(&preimage.to_byte_array());
1012
1013        // Temporary lightning node pubkey
1014        let (node_secret_key, node_public_key) = self.secp.generate_keypair(&mut rng);
1015
1016        // Route hint instructing payer how to route to gateway
1017        let route_hint_last_hop = RouteHintHop {
1018            src_node_id,
1019            short_channel_id,
1020            fees: RoutingFees {
1021                base_msat: 0,
1022                proportional_millionths: 0,
1023            },
1024            cltv_expiry_delta: 30,
1025            htlc_minimum_msat: None,
1026            htlc_maximum_msat: None,
1027        };
1028        let mut final_route_hints = vec![RouteHint(vec![route_hint_last_hop.clone()])];
1029        if !route_hints.is_empty() {
1030            let mut two_hop_route_hints: Vec<RouteHint> = route_hints
1031                .iter()
1032                .map(|rh| {
1033                    RouteHint(
1034                        rh.to_ldk_route_hint()
1035                            .0
1036                            .iter()
1037                            .cloned()
1038                            .chain(once(route_hint_last_hop.clone()))
1039                            .collect(),
1040                    )
1041                })
1042                .collect();
1043            final_route_hints.append(&mut two_hop_route_hints);
1044        }
1045
1046        let duration_since_epoch = fedimint_core::time::duration_since_epoch();
1047
1048        let mut invoice_builder = InvoiceBuilder::new(network.into())
1049            .amount_milli_satoshis(amount.msats)
1050            .invoice_description(description)
1051            .payment_hash(payment_hash)
1052            .payment_secret(PaymentSecret(rng.r#gen()))
1053            .duration_since_epoch(duration_since_epoch)
1054            .min_final_cltv_expiry_delta(18)
1055            .payee_pub_key(node_public_key)
1056            .expiry_time(Duration::from_secs(
1057                expiry_time.unwrap_or(DEFAULT_INVOICE_EXPIRY_TIME.as_secs()),
1058            ));
1059
1060        for rh in final_route_hints {
1061            invoice_builder = invoice_builder.private_route(rh);
1062        }
1063
1064        let invoice = invoice_builder
1065            .build_signed(|msg| self.secp.sign_ecdsa_recoverable(msg, &node_secret_key))?;
1066
1067        let operation_id = OperationId(*invoice.payment_hash().as_ref());
1068
1069        let sm_invoice = invoice.clone();
1070        let sm_gen = Arc::new(move |out_point_range: OutPointRange| {
1071            vec![LightningClientStateMachines::Receive(
1072                LightningReceiveStateMachine {
1073                    operation_id,
1074                    state: LightningReceiveStates::SubmittedOffer(LightningReceiveSubmittedOffer {
1075                        offer_txid: out_point_range.txid(),
1076                        invoice: sm_invoice.clone(),
1077                        receiving_key,
1078                    }),
1079                },
1080            )]
1081        });
1082
1083        let ln_output = LightningOutput::new_v0_offer(IncomingContractOffer {
1084            amount,
1085            hash: payment_hash,
1086            encrypted_preimage: EncryptedPreimage::new(
1087                &PreimageKey(preimage_key),
1088                &self.cfg.threshold_pub_key,
1089            ),
1090            expiry_time,
1091        });
1092
1093        Ok((
1094            operation_id,
1095            invoice,
1096            ClientOutputBundle::new(
1097                vec![ClientOutput {
1098                    output: ln_output,
1099                    amounts: Amounts::ZERO,
1100                }],
1101                vec![ClientOutputSM {
1102                    state_machines: sm_gen,
1103                }],
1104            ),
1105            *preimage.as_ref(),
1106        ))
1107    }
1108
1109    pub async fn select_available_gateway(
1110        &self,
1111        maybe_gateway: Option<LightningGateway>,
1112        maybe_invoice: Option<Bolt11Invoice>,
1113    ) -> anyhow::Result<LightningGateway> {
1114        if let Some(gw) = maybe_gateway {
1115            let gw_id = gw.gateway_id;
1116            if self
1117                .gateway_conn
1118                .verify_gateway_availability(&gw)
1119                .await
1120                .is_ok()
1121            {
1122                return Ok(gw);
1123            }
1124            return Err(anyhow::anyhow!("Specified gateway is offline: {gw_id}"));
1125        }
1126
1127        let gateways: Vec<LightningGatewayAnnouncement> = self.list_gateways().await;
1128        if gateways.is_empty() {
1129            return Err(anyhow::anyhow!("No gateways available"));
1130        }
1131
1132        let gateways_with_status =
1133            futures::future::join_all(gateways.into_iter().map(|gw| async {
1134                let online = self
1135                    .gateway_conn
1136                    .verify_gateway_availability(&gw.info)
1137                    .await
1138                    .is_ok();
1139                (gw, online)
1140            }))
1141            .await;
1142
1143        let sorted_gateways: Vec<(LightningGatewayAnnouncement, GatewayStatus)> =
1144            gateways_with_status
1145                .into_iter()
1146                .filter_map(|(ann, online)| {
1147                    if online {
1148                        let status = if ann.vetted {
1149                            GatewayStatus::OnlineVetted
1150                        } else {
1151                            GatewayStatus::OnlineNonVetted
1152                        };
1153                        Some((ann, status))
1154                    } else {
1155                        None
1156                    }
1157                })
1158                .collect();
1159
1160        if sorted_gateways.is_empty() {
1161            return Err(anyhow::anyhow!("No Lightning Gateway was reachable"));
1162        }
1163
1164        let amount_msat = maybe_invoice.and_then(|inv| inv.amount_milli_satoshis());
1165        let sorted_gateways = sorted_gateways
1166            .into_iter()
1167            .sorted_by_key(|(ann, status)| {
1168                let total_fee_msat: u64 =
1169                    amount_msat.map_or(u64::from(ann.info.fees.base_msat), |amt| {
1170                        u64::from(ann.info.fees.base_msat)
1171                            + ((u128::from(amt)
1172                                * u128::from(ann.info.fees.proportional_millionths))
1173                                / 1_000_000) as u64
1174                    });
1175                (status.clone(), total_fee_msat)
1176            })
1177            .collect::<Vec<_>>();
1178
1179        Ok(sorted_gateways[0].0.info.clone())
1180    }
1181
1182    /// Selects a Lightning Gateway from a given `gateway_id` from the gateway
1183    /// cache.
1184    pub async fn select_gateway(
1185        &self,
1186        gateway_id: &secp256k1::PublicKey,
1187    ) -> Option<LightningGateway> {
1188        let mut dbtx = self.client_ctx.module_db().begin_transaction_nc().await;
1189        let gateways = dbtx
1190            .find_by_prefix(&LightningGatewayKeyPrefix)
1191            .await
1192            .map(|(_, gw)| gw.info)
1193            .collect::<Vec<_>>()
1194            .await;
1195        gateways.into_iter().find(|g| &g.gateway_id == gateway_id)
1196    }
1197
1198    /// Updates the gateway cache by fetching the latest registered gateways
1199    /// from the federation.
1200    ///
1201    /// See also [`Self::update_gateway_cache_continuously`].
1202    pub async fn update_gateway_cache(&self) -> anyhow::Result<()> {
1203        self.update_gateway_cache_merge
1204            .merge(async {
1205                let gateways = self.module_api.fetch_gateways().await?;
1206                let mut dbtx = self.client_ctx.module_db().begin_transaction().await;
1207
1208                // Remove all previous gateway entries
1209                dbtx.remove_by_prefix(&LightningGatewayKeyPrefix).await;
1210
1211                for gw in &gateways {
1212                    dbtx.insert_entry(
1213                        &LightningGatewayKey(gw.info.gateway_id),
1214                        &gw.clone().anchor(),
1215                    )
1216                    .await;
1217                }
1218
1219                dbtx.commit_tx().await;
1220
1221                Ok(())
1222            })
1223            .await
1224    }
1225
1226    /// Continuously update the gateway cache whenever a gateway expires.
1227    ///
1228    /// The gateways returned by `gateway_filters` are checked for expiry.
1229    /// Client integrators are expected to call this function in a spawned task.
1230    pub async fn update_gateway_cache_continuously<Fut>(
1231        &self,
1232        gateways_filter: impl Fn(Vec<LightningGatewayAnnouncement>) -> Fut,
1233    ) -> !
1234    where
1235        Fut: Future<Output = Vec<LightningGatewayAnnouncement>>,
1236    {
1237        const ABOUT_TO_EXPIRE: Duration = Duration::from_secs(30);
1238        const EMPTY_GATEWAY_SLEEP: Duration = Duration::from_mins(10);
1239
1240        let mut first_time = true;
1241
1242        loop {
1243            let gateways = self.list_gateways().await;
1244            let sleep_time = gateways_filter(gateways)
1245                .await
1246                .into_iter()
1247                .map(|x| x.ttl.saturating_sub(ABOUT_TO_EXPIRE))
1248                .min()
1249                .unwrap_or(if first_time {
1250                    // retry immediately first time
1251                    Duration::ZERO
1252                } else {
1253                    EMPTY_GATEWAY_SLEEP
1254                });
1255            runtime::sleep(sleep_time).await;
1256
1257            // should never fail with usize::MAX attempts.
1258            let _ = retry(
1259                "update_gateway_cache",
1260                backoff_util::background_backoff(),
1261                || self.update_gateway_cache(),
1262            )
1263            .await;
1264            first_time = false;
1265        }
1266    }
1267
1268    /// Returns all gateways that are currently in the gateway cache.
1269    pub async fn list_gateways(&self) -> Vec<LightningGatewayAnnouncement> {
1270        let mut dbtx = self.client_ctx.module_db().begin_transaction_nc().await;
1271        dbtx.find_by_prefix(&LightningGatewayKeyPrefix)
1272            .await
1273            .map(|(_, gw)| gw.unanchor())
1274            .collect::<Vec<_>>()
1275            .await
1276    }
1277
1278    /// Pays a LN invoice with our available funds using the supplied `gateway`
1279    /// if one was provided and the invoice is not an internal one. If none is
1280    /// supplied only internal payments are possible.
1281    ///
1282    /// The `gateway` can be acquired by calling
1283    /// [`LightningClientModule::select_gateway`].
1284    ///
1285    /// Can return error of type [`PayBolt11InvoiceError`]
1286    pub async fn pay_bolt11_invoice<M: Serialize + MaybeSend + MaybeSync>(
1287        &self,
1288        maybe_gateway: Option<LightningGateway>,
1289        invoice: Bolt11Invoice,
1290        extra_meta: M,
1291    ) -> anyhow::Result<OutgoingLightningPayment> {
1292        if let Some(expires_at) = invoice.expires_at() {
1293            ensure!(
1294                expires_at.as_secs() > fedimint_core::time::duration_since_epoch().as_secs(),
1295                "Invoice has expired"
1296            );
1297        }
1298
1299        let mut dbtx = self.client_ctx.module_db().begin_transaction().await;
1300        let maybe_gateway_id = maybe_gateway.as_ref().map(|g| g.gateway_id);
1301        let prev_payment_result = self
1302            .get_prev_payment_result(invoice.payment_hash(), &mut dbtx.to_ref_nc())
1303            .await;
1304
1305        if let Some(completed_payment) = prev_payment_result.completed_payment {
1306            return Ok(completed_payment);
1307        }
1308
1309        // Verify that no previous payment attempt is still running
1310        let prev_operation_id = LightningClientModule::get_payment_operation_id(
1311            invoice.payment_hash(),
1312            prev_payment_result.index,
1313        );
1314        if self.client_ctx.has_active_states(prev_operation_id).await {
1315            bail!(
1316                PayBolt11InvoiceError::PreviousPaymentAttemptStillInProgress {
1317                    operation_id: prev_operation_id
1318                }
1319            )
1320        }
1321
1322        let next_index = prev_payment_result.index + 1;
1323        let operation_id =
1324            LightningClientModule::get_payment_operation_id(invoice.payment_hash(), next_index);
1325
1326        let new_payment_result = PaymentResult {
1327            index: next_index,
1328            completed_payment: None,
1329        };
1330
1331        dbtx.insert_entry(
1332            &PaymentResultKey {
1333                payment_hash: *invoice.payment_hash(),
1334            },
1335            &new_payment_result,
1336        )
1337        .await;
1338
1339        let markers = self.client_ctx.get_internal_payment_markers()?;
1340
1341        let mut is_internal_payment = invoice_has_internal_payment_markers(&invoice, markers);
1342        if !is_internal_payment {
1343            let gateways = dbtx
1344                .find_by_prefix(&LightningGatewayKeyPrefix)
1345                .await
1346                .map(|(_, gw)| gw.info)
1347                .collect::<Vec<_>>()
1348                .await;
1349            is_internal_payment = invoice_routes_back_to_federation(&invoice, gateways);
1350        }
1351
1352        let (pay_type, client_output, client_output_sm, contract_id) = if is_internal_payment {
1353            let (output, output_sm, contract_id) = self
1354                .create_incoming_output(operation_id, invoice.clone())
1355                .await?;
1356            (
1357                PayType::Internal(operation_id),
1358                output,
1359                output_sm,
1360                contract_id,
1361            )
1362        } else {
1363            let gateway = maybe_gateway.context(PayBolt11InvoiceError::NoLnGatewayAvailable)?;
1364            let (output, output_sm, contract_id) = self
1365                .create_outgoing_output(
1366                    operation_id,
1367                    invoice.clone(),
1368                    gateway,
1369                    self.client_ctx
1370                        .get_config()
1371                        .await
1372                        .global
1373                        .calculate_federation_id(),
1374                    rand::rngs::OsRng,
1375                )
1376                .await?;
1377            (
1378                PayType::Lightning(operation_id),
1379                output,
1380                output_sm,
1381                contract_id,
1382            )
1383        };
1384
1385        // Verify that no other outgoing contract exists or the value is empty
1386        if let Ok(Some(contract)) = self.module_api.fetch_contract(contract_id).await
1387            && contract.amount.msats != 0
1388        {
1389            bail!(PayBolt11InvoiceError::FundedContractAlreadyExists { contract_id });
1390        }
1391
1392        let amount_msat = invoice
1393            .amount_milli_satoshis()
1394            .ok_or(anyhow!("MissingInvoiceAmount"))?;
1395
1396        // TODO: return fee from create_outgoing_output or even let user supply
1397        // it/bounds for it
1398        let fee = match &client_output.output {
1399            LightningOutputV0::Contract(contract) => {
1400                let fee_msat = contract
1401                    .amount
1402                    .msats
1403                    .checked_sub(amount_msat)
1404                    .expect("Contract amount should be greater or equal than invoice amount");
1405                Amount::from_msats(fee_msat)
1406            }
1407            _ => unreachable!("User client will only create contract outputs on spend"),
1408        };
1409
1410        let output = self.client_ctx.make_client_outputs(ClientOutputBundle::new(
1411            vec![ClientOutput {
1412                output: LightningOutput::V0(client_output.output),
1413                amounts: client_output.amounts,
1414            }],
1415            vec![client_output_sm],
1416        ));
1417
1418        let tx = TransactionBuilder::new().with_outputs(output);
1419        let extra_meta =
1420            serde_json::to_value(extra_meta).context("Failed to serialize extra meta")?;
1421        let operation_meta_gen = move |change_range: OutPointRange| LightningOperationMeta {
1422            variant: LightningOperationMetaVariant::Pay(LightningOperationMetaPay {
1423                out_point: OutPoint {
1424                    txid: change_range.txid(),
1425                    out_idx: 0,
1426                },
1427                invoice: invoice.clone(),
1428                fee,
1429                change: change_range.into_iter().collect(),
1430                is_internal_payment,
1431                contract_id,
1432                gateway_id: maybe_gateway_id,
1433            }),
1434            extra_meta: extra_meta.clone(),
1435        };
1436
1437        // Write the new payment index into the database, fail the payment if the commit
1438        // to the database fails.
1439        dbtx.commit_tx_result().await?;
1440
1441        self.client_ctx
1442            .finalize_and_submit_transaction(
1443                operation_id,
1444                LightningCommonInit::KIND.as_str(),
1445                operation_meta_gen,
1446                tx,
1447            )
1448            .await?;
1449
1450        let mut event_dbtx = self.client_ctx.module_db().begin_transaction().await;
1451
1452        self.client_ctx
1453            .log_event(
1454                &mut event_dbtx,
1455                events::SendPaymentEvent {
1456                    operation_id,
1457                    amount: Amount::from_msats(amount_msat),
1458                    fee,
1459                },
1460            )
1461            .await;
1462
1463        event_dbtx.commit_tx().await;
1464
1465        Ok(OutgoingLightningPayment {
1466            payment_type: pay_type,
1467            contract_id,
1468            fee,
1469        })
1470    }
1471
1472    pub async fn get_ln_pay_details_for(
1473        &self,
1474        operation_id: OperationId,
1475    ) -> anyhow::Result<LightningOperationMetaPay> {
1476        let operation = self.client_ctx.get_operation(operation_id).await?;
1477        let LightningOperationMetaVariant::Pay(pay) =
1478            operation.meta::<LightningOperationMeta>().variant
1479        else {
1480            anyhow::bail!("Operation is not a lightning payment")
1481        };
1482        Ok(pay)
1483    }
1484
1485    pub async fn subscribe_internal_pay(
1486        &self,
1487        operation_id: OperationId,
1488    ) -> anyhow::Result<UpdateStreamOrOutcome<InternalPayState>> {
1489        let operation = self.client_ctx.get_operation(operation_id).await?;
1490
1491        let LightningOperationMetaVariant::Pay(LightningOperationMetaPay {
1492            out_point: _,
1493            invoice: _,
1494            change: _, // FIXME: why isn't this used here?
1495            is_internal_payment,
1496            ..
1497        }) = operation.meta::<LightningOperationMeta>().variant
1498        else {
1499            bail!("Operation is not a lightning payment")
1500        };
1501
1502        ensure!(
1503            is_internal_payment,
1504            "Subscribing to an external LN payment, expected internal LN payment"
1505        );
1506
1507        let mut stream = self.notifier.subscribe(operation_id).await;
1508        let client_ctx = self.client_ctx.clone();
1509
1510        Ok(self.client_ctx.outcome_or_updates(operation, operation_id, move || {
1511            stream! {
1512                yield InternalPayState::Funding;
1513
1514                let state = loop {
1515                    match stream.next().await { Some(LightningClientStateMachines::InternalPay(state)) => {
1516                        match state.state {
1517                            IncomingSmStates::Preimage(preimage) => break InternalPayState::Preimage(preimage),
1518                            IncomingSmStates::RefundSubmitted{ out_points, error } => {
1519                                match client_ctx.await_primary_module_outputs(operation_id, out_points.clone()).await {
1520                                    Ok(()) => break InternalPayState::RefundSuccess { out_points, error },
1521                                    Err(e) => break InternalPayState::RefundError{ error_message: e.to_string(), error },
1522                                }
1523                            },
1524                            IncomingSmStates::FundingFailed { error } => break InternalPayState::FundingFailed{ error },
1525                            _ => {}
1526                        }
1527                    } _ => {
1528                        break InternalPayState::UnexpectedError("Unexpected State! Expected an InternalPay state".to_string())
1529                    }}
1530                };
1531                yield state;
1532            }
1533        }))
1534    }
1535
1536    /// Subscribes to a stream of updates about a particular external Lightning
1537    /// payment operation specified by the `operation_id`.
1538    pub async fn subscribe_ln_pay(
1539        &self,
1540        operation_id: OperationId,
1541    ) -> anyhow::Result<UpdateStreamOrOutcome<LnPayState>> {
1542        async fn get_next_pay_state(
1543            stream: &mut BoxStream<'_, LightningClientStateMachines>,
1544        ) -> Option<LightningPayStates> {
1545            match stream.next().await {
1546                Some(LightningClientStateMachines::LightningPay(state)) => Some(state.state),
1547                Some(event) => {
1548                    // nosemgrep: use-err-formatting
1549                    error!(event = ?event, "Operation is not a lightning payment");
1550                    debug_assert!(false, "Operation is not a lightning payment: {event:?}");
1551                    None
1552                }
1553                None => None,
1554            }
1555        }
1556
1557        let operation = self.client_ctx.get_operation(operation_id).await?;
1558        let LightningOperationMetaVariant::Pay(LightningOperationMetaPay {
1559            out_point: _,
1560            invoice: _,
1561            change,
1562            is_internal_payment,
1563            ..
1564        }) = operation.meta::<LightningOperationMeta>().variant
1565        else {
1566            bail!("Operation is not a lightning payment")
1567        };
1568
1569        ensure!(
1570            !is_internal_payment,
1571            "Subscribing to an internal LN payment, expected external LN payment"
1572        );
1573
1574        let client_ctx = self.client_ctx.clone();
1575
1576        Ok(self.client_ctx.outcome_or_updates(operation, operation_id, move || {
1577            stream! {
1578                let self_ref = client_ctx.self_ref();
1579
1580                let mut stream = self_ref.notifier.subscribe(operation_id).await;
1581                let state = get_next_pay_state(&mut stream).await;
1582                match state {
1583                    Some(LightningPayStates::CreatedOutgoingLnContract(_)) => {
1584                        yield LnPayState::Created;
1585                    }
1586                    Some(LightningPayStates::FundingRejected) => {
1587                        yield LnPayState::Canceled;
1588                        return;
1589                    }
1590                    Some(state) => {
1591                        yield LnPayState::UnexpectedError { error_message: format!("Found unexpected state during lightning payment: {state:?}") };
1592                        return;
1593                    }
1594                    None => {
1595                        error!("Unexpected end of lightning pay state machine");
1596                        return;
1597                    }
1598                }
1599
1600                let state = get_next_pay_state(&mut stream).await;
1601                match state {
1602                    Some(LightningPayStates::Funded(funded)) => {
1603                        yield LnPayState::Funded { block_height: funded.timelock }
1604                    }
1605                    Some(state) => {
1606                        yield LnPayState::UnexpectedError { error_message: format!("Found unexpected state during lightning payment: {state:?}") };
1607                        return;
1608                    }
1609                    _ => {
1610                        error!("Unexpected end of lightning pay state machine");
1611                        return;
1612                    }
1613                }
1614
1615                let state = get_next_pay_state(&mut stream).await;
1616                match state {
1617                    Some(LightningPayStates::Success(preimage)) => {
1618                        if change.is_empty() {
1619                            yield LnPayState::Success { preimage };
1620                        } else {
1621                            yield LnPayState::AwaitingChange;
1622                            match client_ctx.await_primary_module_outputs(operation_id, change.clone()).await {
1623                                Ok(()) => {
1624                                    yield LnPayState::Success { preimage };
1625                                }
1626                                Err(e) => {
1627                                    yield LnPayState::UnexpectedError { error_message: format!("Error occurred while waiting for the change: {e:?}") };
1628                                }
1629                            }
1630                        }
1631                    }
1632                    Some(LightningPayStates::Refund(refund)) => {
1633                        yield LnPayState::WaitingForRefund {
1634                            error_reason: refund.error_reason.clone(),
1635                        };
1636
1637                        match client_ctx.await_primary_module_outputs(operation_id, refund.out_points).await {
1638                            Ok(()) => {
1639                                let gateway_error = GatewayPayError::GatewayInternalError { error_code: Some(500), error_message: refund.error_reason };
1640                                yield LnPayState::Refunded { gateway_error };
1641                            }
1642                            Err(e) => {
1643                                yield LnPayState::UnexpectedError {
1644                                    error_message: format!("Error occurred trying to get refund. Refund was not successful: {e:?}"),
1645                                };
1646                            }
1647                        }
1648                    }
1649                    Some(state) => {
1650                        yield LnPayState::UnexpectedError { error_message: format!("Found unexpected state during lightning payment: {state:?}") };
1651                    }
1652                    None => {
1653                        error!("Unexpected end of lightning pay state machine");
1654                        yield LnPayState::UnexpectedError { error_message: "Unexpected end of lightning pay state machine".to_string() };
1655                    }
1656                }
1657            }
1658        }))
1659    }
1660
1661    /// Scan unspent incoming contracts for a payment hash that matches a
1662    /// tweaked keys in the `indices` vector
1663    #[deprecated(since = "0.7.0", note = "Use recurring payment functionality instead")]
1664    #[allow(deprecated)]
1665    pub async fn scan_receive_for_user_tweaked<M: Serialize + Send + Sync + Clone>(
1666        &self,
1667        key_pair: Keypair,
1668        indices: Vec<u64>,
1669        extra_meta: M,
1670    ) -> Vec<OperationId> {
1671        let mut claims = Vec::new();
1672        for i in indices {
1673            let key_pair_tweaked = tweak_user_secret_key(&self.secp, key_pair, i);
1674            match self
1675                .scan_receive_for_user(key_pair_tweaked, extra_meta.clone())
1676                .await
1677            {
1678                Ok(operation_id) => claims.push(operation_id),
1679                Err(err) => {
1680                    error!(err = %err.fmt_compact_anyhow(), %i, "Failed to scan tweaked key at index i");
1681                }
1682            }
1683        }
1684
1685        claims
1686    }
1687
1688    /// Scan unspent incoming contracts for a payment hash that matches a public
1689    /// key and claim the incoming contract
1690    #[deprecated(since = "0.7.0", note = "Use recurring payment functionality instead")]
1691    #[allow(deprecated)]
1692    pub async fn scan_receive_for_user<M: Serialize + Send + Sync>(
1693        &self,
1694        key_pair: Keypair,
1695        extra_meta: M,
1696    ) -> anyhow::Result<OperationId> {
1697        let preimage_key: [u8; 33] = key_pair.public_key().serialize();
1698        let preimage = sha256::Hash::hash(&preimage_key);
1699        let contract_id = ContractId::from_raw_hash(sha256::Hash::hash(&preimage.to_byte_array()));
1700        self.claim_funded_incoming_contract(key_pair, contract_id, extra_meta)
1701            .await
1702    }
1703
1704    /// Claim the funded, unspent incoming contract by submitting a transaction
1705    /// to the federation and awaiting the primary module's outputs
1706    #[deprecated(since = "0.7.0", note = "Use recurring payment functionality instead")]
1707    #[allow(deprecated)]
1708    pub async fn claim_funded_incoming_contract<M: Serialize + Send + Sync>(
1709        &self,
1710        key_pair: Keypair,
1711        contract_id: ContractId,
1712        extra_meta: M,
1713    ) -> anyhow::Result<OperationId> {
1714        let incoming_contract_account = get_incoming_contract(self.module_api.clone(), contract_id)
1715            .await?
1716            .ok_or(anyhow!("No contract account found"))
1717            .with_context(|| format!("No contract found for {contract_id:?}"))?;
1718
1719        let input = incoming_contract_account.claim();
1720        let client_input = ClientInput::<LightningInput> {
1721            input,
1722            amounts: Amounts::new_bitcoin(incoming_contract_account.amount),
1723            keys: vec![key_pair],
1724        };
1725
1726        let tx = TransactionBuilder::new().with_inputs(
1727            self.client_ctx
1728                .make_client_inputs(ClientInputBundle::new_no_sm(vec![client_input])),
1729        );
1730        let extra_meta = serde_json::to_value(extra_meta).expect("extra_meta is serializable");
1731        let operation_meta_gen = move |change_range: OutPointRange| LightningOperationMeta {
1732            variant: LightningOperationMetaVariant::Claim {
1733                out_points: change_range.into_iter().collect(),
1734            },
1735            extra_meta: extra_meta.clone(),
1736        };
1737        let operation_id = OperationId::new_random();
1738        self.client_ctx
1739            .finalize_and_submit_transaction(
1740                operation_id,
1741                LightningCommonInit::KIND.as_str(),
1742                operation_meta_gen,
1743                tx,
1744            )
1745            .await?;
1746        Ok(operation_id)
1747    }
1748
1749    /// Receive over LN with a new invoice
1750    pub async fn create_bolt11_invoice<M: Serialize + Send + Sync>(
1751        &self,
1752        amount: Amount,
1753        description: lightning_invoice::Bolt11InvoiceDescription,
1754        expiry_time: Option<u64>,
1755        extra_meta: M,
1756        gateway: Option<LightningGateway>,
1757    ) -> anyhow::Result<(OperationId, Bolt11Invoice, [u8; 32])> {
1758        let receiving_key =
1759            ReceivingKey::Personal(Keypair::new(&self.secp, &mut rand::rngs::OsRng));
1760        self.create_bolt11_invoice_internal(
1761            amount,
1762            description,
1763            expiry_time,
1764            receiving_key,
1765            extra_meta,
1766            gateway,
1767        )
1768        .await
1769    }
1770
1771    /// Receive over LN with a new invoice for another user, tweaking their key
1772    /// by the given index
1773    #[allow(clippy::too_many_arguments)]
1774    pub async fn create_bolt11_invoice_for_user_tweaked<M: Serialize + Send + Sync>(
1775        &self,
1776        amount: Amount,
1777        description: lightning_invoice::Bolt11InvoiceDescription,
1778        expiry_time: Option<u64>,
1779        user_key: PublicKey,
1780        index: u64,
1781        extra_meta: M,
1782        gateway: Option<LightningGateway>,
1783    ) -> anyhow::Result<(OperationId, Bolt11Invoice, [u8; 32])> {
1784        let tweaked_key = tweak_user_key(&self.secp, user_key, index);
1785        self.create_bolt11_invoice_for_user(
1786            amount,
1787            description,
1788            expiry_time,
1789            tweaked_key,
1790            extra_meta,
1791            gateway,
1792        )
1793        .await
1794    }
1795
1796    /// Receive over LN with a new invoice for another user
1797    pub async fn create_bolt11_invoice_for_user<M: Serialize + Send + Sync>(
1798        &self,
1799        amount: Amount,
1800        description: lightning_invoice::Bolt11InvoiceDescription,
1801        expiry_time: Option<u64>,
1802        user_key: PublicKey,
1803        extra_meta: M,
1804        gateway: Option<LightningGateway>,
1805    ) -> anyhow::Result<(OperationId, Bolt11Invoice, [u8; 32])> {
1806        let receiving_key = ReceivingKey::External(user_key);
1807        self.create_bolt11_invoice_internal(
1808            amount,
1809            description,
1810            expiry_time,
1811            receiving_key,
1812            extra_meta,
1813            gateway,
1814        )
1815        .await
1816    }
1817
1818    /// Receive over LN with a new invoice
1819    async fn create_bolt11_invoice_internal<M: Serialize + Send + Sync>(
1820        &self,
1821        amount: Amount,
1822        description: lightning_invoice::Bolt11InvoiceDescription,
1823        expiry_time: Option<u64>,
1824        receiving_key: ReceivingKey,
1825        extra_meta: M,
1826        gateway: Option<LightningGateway>,
1827    ) -> anyhow::Result<(OperationId, Bolt11Invoice, [u8; 32])> {
1828        let gateway_id = gateway.as_ref().map(|g| g.gateway_id);
1829        let (src_node_id, short_channel_id, route_hints) = if let Some(current_gateway) = gateway {
1830            (
1831                current_gateway.node_pub_key,
1832                current_gateway.federation_index,
1833                current_gateway.route_hints,
1834            )
1835        } else {
1836            // If no gateway is provided, this is assumed to be an internal payment.
1837            let markers = self.client_ctx.get_internal_payment_markers()?;
1838            (markers.0, markers.1, vec![])
1839        };
1840
1841        debug!(target: LOG_CLIENT_MODULE_LN, ?gateway_id, %amount, "Selected LN gateway for invoice generation");
1842
1843        let (operation_id, invoice, output, preimage) = self.create_lightning_receive_output(
1844            amount,
1845            description,
1846            receiving_key,
1847            rand::rngs::OsRng,
1848            expiry_time,
1849            src_node_id,
1850            short_channel_id,
1851            &route_hints,
1852            self.cfg.network.0,
1853        )?;
1854
1855        let tx =
1856            TransactionBuilder::new().with_outputs(self.client_ctx.make_client_outputs(output));
1857        let extra_meta = serde_json::to_value(extra_meta).expect("extra_meta is serializable");
1858        let operation_meta_gen = {
1859            let invoice = invoice.clone();
1860            move |change_range: OutPointRange| LightningOperationMeta {
1861                variant: LightningOperationMetaVariant::Receive {
1862                    out_point: OutPoint {
1863                        txid: change_range.txid(),
1864                        out_idx: 0,
1865                    },
1866                    invoice: invoice.clone(),
1867                    gateway_id,
1868                },
1869                extra_meta: extra_meta.clone(),
1870            }
1871        };
1872        let change_range = self
1873            .client_ctx
1874            .finalize_and_submit_transaction(
1875                operation_id,
1876                LightningCommonInit::KIND.as_str(),
1877                operation_meta_gen,
1878                tx,
1879            )
1880            .await?;
1881
1882        debug!(target: LOG_CLIENT_MODULE_LN, txid = ?change_range.txid(), ?operation_id, "Waiting for LN invoice to be confirmed");
1883
1884        // Wait for the transaction to be accepted by the federation, otherwise the
1885        // invoice will not be able to be paid
1886        self.client_ctx
1887            .transaction_updates(operation_id)
1888            .await
1889            .await_tx_accepted(change_range.txid())
1890            .await
1891            .map_err(|e| anyhow!("Offer transaction was not accepted: {e:?}"))?;
1892
1893        debug!(target: LOG_CLIENT_MODULE_LN, %invoice, "Invoice confirmed");
1894
1895        Ok((operation_id, invoice, preimage))
1896    }
1897
1898    #[deprecated(since = "0.7.0", note = "Use recurring payment functionality instead")]
1899    #[allow(deprecated)]
1900    pub async fn subscribe_ln_claim(
1901        &self,
1902        operation_id: OperationId,
1903    ) -> anyhow::Result<UpdateStreamOrOutcome<LnReceiveState>> {
1904        let operation = self.client_ctx.get_operation(operation_id).await?;
1905        let LightningOperationMetaVariant::Claim { out_points } =
1906            operation.meta::<LightningOperationMeta>().variant
1907        else {
1908            bail!("Operation is not a lightning claim")
1909        };
1910
1911        let client_ctx = self.client_ctx.clone();
1912
1913        Ok(self.client_ctx.outcome_or_updates(operation, operation_id, move || {
1914            stream! {
1915                yield LnReceiveState::AwaitingFunds;
1916
1917                if client_ctx.await_primary_module_outputs(operation_id, out_points).await.is_ok() {
1918                    yield LnReceiveState::Claimed;
1919                } else {
1920                    yield LnReceiveState::Canceled { reason: LightningReceiveError::ClaimRejected }
1921                }
1922            }
1923        }))
1924    }
1925
1926    pub async fn subscribe_ln_receive(
1927        &self,
1928        operation_id: OperationId,
1929    ) -> anyhow::Result<UpdateStreamOrOutcome<LnReceiveState>> {
1930        let operation = self.client_ctx.get_operation(operation_id).await?;
1931        let LightningOperationMetaVariant::Receive {
1932            out_point, invoice, ..
1933        } = operation.meta::<LightningOperationMeta>().variant
1934        else {
1935            bail!("Operation is not a lightning payment")
1936        };
1937
1938        let tx_accepted_future = self
1939            .client_ctx
1940            .transaction_updates(operation_id)
1941            .await
1942            .await_tx_accepted(out_point.txid);
1943
1944        let client_ctx = self.client_ctx.clone();
1945
1946        Ok(self.client_ctx.outcome_or_updates(operation, operation_id, move || {
1947            stream! {
1948
1949                let self_ref = client_ctx.self_ref();
1950
1951                yield LnReceiveState::Created;
1952
1953                if tx_accepted_future.await.is_err() {
1954                    yield LnReceiveState::Canceled { reason: LightningReceiveError::Rejected };
1955                    return;
1956                }
1957                yield LnReceiveState::WaitingForPayment { invoice: invoice.to_string(), timeout: invoice.expiry_time() };
1958
1959                match self_ref.await_receive_success(operation_id).await {
1960                    Ok(()) => {
1961
1962                        yield LnReceiveState::Funded;
1963
1964                        if let Ok(out_points) = self_ref.await_claim_acceptance(operation_id).await {
1965                            yield LnReceiveState::AwaitingFunds;
1966
1967                            if client_ctx.await_primary_module_outputs(operation_id, out_points).await.is_ok() {
1968                                yield LnReceiveState::Claimed;
1969                                return;
1970                            }
1971                        }
1972
1973                        yield LnReceiveState::Canceled { reason: LightningReceiveError::Rejected };
1974                    }
1975                    Err(e) => {
1976                        yield LnReceiveState::Canceled { reason: e };
1977                    }
1978                }
1979            }
1980        }))
1981    }
1982
1983    /// Returns a gateway to be used for a lightning operation. If
1984    /// `force_internal` is true and no `gateway_id` is specified, no
1985    /// gateway will be selected.
1986    pub async fn get_gateway(
1987        &self,
1988        gateway_id: Option<secp256k1::PublicKey>,
1989        force_internal: bool,
1990    ) -> anyhow::Result<Option<LightningGateway>> {
1991        match gateway_id {
1992            Some(gateway_id) => {
1993                if let Some(gw) = self.select_gateway(&gateway_id).await {
1994                    Ok(Some(gw))
1995                } else {
1996                    // Refresh the gateway cache in case the target gateway was registered since the
1997                    // last update.
1998                    self.update_gateway_cache().await?;
1999                    Ok(self.select_gateway(&gateway_id).await)
2000                }
2001            }
2002            None if !force_internal => {
2003                // Refresh the gateway cache to find a random gateway to select from.
2004                self.update_gateway_cache().await?;
2005                let gateways = self.list_gateways().await;
2006                let gw = gateways.into_iter().choose(&mut OsRng).map(|gw| gw.info);
2007                if let Some(gw) = gw {
2008                    let gw_id = gw.gateway_id;
2009                    info!(%gw_id, "Using random gateway");
2010                    Ok(Some(gw))
2011                } else {
2012                    Err(anyhow!(
2013                        "No gateways exist in gateway cache and `force_internal` is false"
2014                    ))
2015                }
2016            }
2017            None => Ok(None),
2018        }
2019    }
2020
2021    /// Subscribes to either a internal or external lightning payment and
2022    /// returns `LightningPaymentOutcome` that indicates if the payment was
2023    /// successful or not.
2024    pub async fn await_outgoing_payment(
2025        &self,
2026        operation_id: OperationId,
2027    ) -> anyhow::Result<LightningPaymentOutcome> {
2028        let operation = self.client_ctx.get_operation(operation_id).await?;
2029        let variant = operation.meta::<LightningOperationMeta>().variant;
2030        let LightningOperationMetaVariant::Pay(LightningOperationMetaPay {
2031            is_internal_payment,
2032            ..
2033        }) = variant
2034        else {
2035            bail!("Operation is not a lightning payment")
2036        };
2037
2038        let mut final_state = None;
2039
2040        // First check if the outgoing payment is an internal payment
2041        if is_internal_payment {
2042            let updates = self.subscribe_internal_pay(operation_id).await?;
2043            let mut stream = updates.into_stream();
2044            while let Some(update) = stream.next().await {
2045                match update {
2046                    InternalPayState::Preimage(preimage) => {
2047                        final_state = Some(LightningPaymentOutcome::Success {
2048                            preimage: preimage.0.consensus_encode_to_hex(),
2049                        });
2050                    }
2051                    InternalPayState::RefundSuccess {
2052                        out_points: _,
2053                        error,
2054                    } => {
2055                        final_state = Some(LightningPaymentOutcome::Failure {
2056                            error_message: format!("LNv1 internal payment was refunded: {error:?}"),
2057                        });
2058                    }
2059                    InternalPayState::FundingFailed { error } => {
2060                        final_state = Some(LightningPaymentOutcome::Failure {
2061                            error_message: format!(
2062                                "LNv1 internal payment funding failed: {error:?}"
2063                            ),
2064                        });
2065                    }
2066                    InternalPayState::RefundError {
2067                        error_message,
2068                        error,
2069                    } => {
2070                        final_state = Some(LightningPaymentOutcome::Failure {
2071                            error_message: format!(
2072                                "LNv1 refund failed: {error_message}: {error:?}"
2073                            ),
2074                        });
2075                    }
2076                    InternalPayState::UnexpectedError(error) => {
2077                        final_state = Some(LightningPaymentOutcome::Failure {
2078                            error_message: error,
2079                        });
2080                    }
2081                    InternalPayState::Funding => {}
2082                }
2083            }
2084        } else {
2085            let updates = self.subscribe_ln_pay(operation_id).await?;
2086            let mut stream = updates.into_stream();
2087            while let Some(update) = stream.next().await {
2088                match update {
2089                    LnPayState::Success { preimage } => {
2090                        final_state = Some(LightningPaymentOutcome::Success { preimage });
2091                    }
2092                    LnPayState::Refunded { gateway_error } => {
2093                        final_state = Some(LightningPaymentOutcome::Failure {
2094                            error_message: format!(
2095                                "LNv1 external payment was refunded: {gateway_error:?}"
2096                            ),
2097                        });
2098                    }
2099                    LnPayState::UnexpectedError { error_message } => {
2100                        final_state = Some(LightningPaymentOutcome::Failure { error_message });
2101                    }
2102                    _ => {}
2103                }
2104            }
2105        }
2106
2107        final_state.ok_or(anyhow!(
2108            "Internal or external outgoing lightning payment did not reach a final state"
2109        ))
2110    }
2111}
2112
2113// TODO: move to appropriate module (cli?)
2114// some refactoring here needed
2115#[derive(Debug, Clone, Serialize, Deserialize)]
2116#[serde(rename_all = "snake_case")]
2117pub struct PayInvoiceResponse {
2118    operation_id: OperationId,
2119    contract_id: ContractId,
2120    preimage: String,
2121}
2122
2123#[allow(clippy::large_enum_variant)]
2124#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
2125pub enum LightningClientStateMachines {
2126    InternalPay(IncomingStateMachine),
2127    LightningPay(LightningPayStateMachine),
2128    Receive(LightningReceiveStateMachine),
2129}
2130
2131impl IntoDynInstance for LightningClientStateMachines {
2132    type DynType = DynState;
2133
2134    fn into_dyn(self, instance_id: ModuleInstanceId) -> Self::DynType {
2135        DynState::from_typed(instance_id, self)
2136    }
2137}
2138
2139impl State for LightningClientStateMachines {
2140    type ModuleContext = LightningClientContext;
2141
2142    fn transitions(
2143        &self,
2144        context: &Self::ModuleContext,
2145        global_context: &DynGlobalClientContext,
2146    ) -> Vec<StateTransition<Self>> {
2147        match self {
2148            LightningClientStateMachines::InternalPay(internal_pay_state) => {
2149                sm_enum_variant_translation!(
2150                    internal_pay_state.transitions(context, global_context),
2151                    LightningClientStateMachines::InternalPay
2152                )
2153            }
2154            LightningClientStateMachines::LightningPay(lightning_pay_state) => {
2155                sm_enum_variant_translation!(
2156                    lightning_pay_state.transitions(context, global_context),
2157                    LightningClientStateMachines::LightningPay
2158                )
2159            }
2160            LightningClientStateMachines::Receive(receive_state) => {
2161                sm_enum_variant_translation!(
2162                    receive_state.transitions(context, global_context),
2163                    LightningClientStateMachines::Receive
2164                )
2165            }
2166        }
2167    }
2168
2169    fn operation_id(&self) -> OperationId {
2170        match self {
2171            LightningClientStateMachines::InternalPay(internal_pay_state) => {
2172                internal_pay_state.operation_id()
2173            }
2174            LightningClientStateMachines::LightningPay(lightning_pay_state) => {
2175                lightning_pay_state.operation_id()
2176            }
2177            LightningClientStateMachines::Receive(receive_state) => receive_state.operation_id(),
2178        }
2179    }
2180}
2181
2182async fn fetch_and_validate_offer(
2183    module_api: &DynModuleApi,
2184    payment_hash: sha256::Hash,
2185    amount_msat: Amount,
2186) -> anyhow::Result<IncomingContractOffer, IncomingSmError> {
2187    let offer = timeout(Duration::from_secs(5), module_api.fetch_offer(payment_hash))
2188        .await
2189        .map_err(|_| IncomingSmError::TimeoutFetchingOffer { payment_hash })?
2190        .map_err(|e| IncomingSmError::FetchContractError {
2191            payment_hash,
2192            error_message: e.to_string(),
2193        })?;
2194
2195    if offer.amount > amount_msat {
2196        return Err(IncomingSmError::ViolatedFeePolicy {
2197            offer_amount: offer.amount,
2198            payment_amount: amount_msat,
2199        });
2200    }
2201    if offer.hash != payment_hash {
2202        return Err(IncomingSmError::InvalidOffer {
2203            offer_hash: offer.hash,
2204            payment_hash,
2205        });
2206    }
2207    Ok(offer)
2208}
2209
2210pub async fn create_incoming_contract_output(
2211    module_api: &DynModuleApi,
2212    payment_hash: sha256::Hash,
2213    amount_msat: Amount,
2214    redeem_key: &Keypair,
2215) -> Result<(LightningOutputV0, Amount, ContractId), IncomingSmError> {
2216    let offer = fetch_and_validate_offer(module_api, payment_hash, amount_msat).await?;
2217    let our_pub_key = secp256k1::PublicKey::from_keypair(redeem_key);
2218    let contract = IncomingContract {
2219        hash: offer.hash,
2220        encrypted_preimage: offer.encrypted_preimage.clone(),
2221        decrypted_preimage: DecryptedPreimage::Pending,
2222        gateway_key: our_pub_key,
2223    };
2224    let contract_id = contract.contract_id();
2225    let incoming_output = LightningOutputV0::Contract(ContractOutput {
2226        amount: offer.amount,
2227        contract: Contract::Incoming(contract),
2228    });
2229
2230    Ok((incoming_output, offer.amount, contract_id))
2231}
2232
2233#[derive(Debug, Encodable, Decodable, Serialize)]
2234pub struct OutgoingLightningPayment {
2235    pub payment_type: PayType,
2236    pub contract_id: ContractId,
2237    pub fee: Amount,
2238}
2239
2240async fn set_payment_result(
2241    dbtx: &mut DatabaseTransaction<'_>,
2242    payment_hash: sha256::Hash,
2243    payment_type: PayType,
2244    contract_id: ContractId,
2245    fee: Amount,
2246) {
2247    if let Some(mut payment_result) = dbtx.get_value(&PaymentResultKey { payment_hash }).await {
2248        payment_result.completed_payment = Some(OutgoingLightningPayment {
2249            payment_type,
2250            contract_id,
2251            fee,
2252        });
2253        dbtx.insert_entry(&PaymentResultKey { payment_hash }, &payment_result)
2254            .await;
2255    }
2256}
2257
2258/// Tweak a user key with an index, this is used to generate a new key for each
2259/// invoice. This is done to not be able to link invoices to the same user.
2260pub fn tweak_user_key<Ctx: Verification + Signing>(
2261    secp: &Secp256k1<Ctx>,
2262    user_key: PublicKey,
2263    index: u64,
2264) -> PublicKey {
2265    let mut hasher = HmacEngine::<sha256::Hash>::new(&user_key.serialize()[..]);
2266    hasher.input(&index.to_be_bytes());
2267    let tweak = Hmac::from_engine(hasher).to_byte_array();
2268
2269    user_key
2270        .add_exp_tweak(secp, &Scalar::from_be_bytes(tweak).expect("can't fail"))
2271        .expect("tweak is always 32 bytes, other failure modes are negligible")
2272}
2273
2274/// Tweak a secret key with an index, this is used to claim an unspent incoming
2275/// contract.
2276fn tweak_user_secret_key<Ctx: Verification + Signing>(
2277    secp: &Secp256k1<Ctx>,
2278    key_pair: Keypair,
2279    index: u64,
2280) -> Keypair {
2281    let public_key = key_pair.public_key();
2282    let mut hasher = HmacEngine::<sha256::Hash>::new(&public_key.serialize()[..]);
2283    hasher.input(&index.to_be_bytes());
2284    let tweak = Hmac::from_engine(hasher).to_byte_array();
2285
2286    let secret_key = key_pair.secret_key();
2287    let sk_tweaked = secret_key
2288        .add_tweak(&Scalar::from_be_bytes(tweak).expect("Cant fail"))
2289        .expect("Cant fail");
2290    Keypair::from_secret_key(secp, &sk_tweaked)
2291}
2292
2293/// Get LN invoice with given settings
2294pub async fn get_invoice(
2295    info: &str,
2296    amount: Option<Amount>,
2297    lnurl_comment: Option<String>,
2298) -> anyhow::Result<Bolt11Invoice> {
2299    let info = info.trim();
2300    match lightning_invoice::Bolt11Invoice::from_str(info) {
2301        Ok(invoice) => {
2302            debug!("Parsed parameter as bolt11 invoice: {invoice}");
2303            match (invoice.amount_milli_satoshis(), amount) {
2304                (Some(_), Some(_)) => {
2305                    bail!("Amount specified in both invoice and command line")
2306                }
2307                (None, _) => {
2308                    bail!("We don't support invoices without an amount")
2309                }
2310                _ => {}
2311            }
2312            Ok(invoice)
2313        }
2314        Err(e) => {
2315            let lnurl = if info.to_lowercase().starts_with("lnurl") {
2316                lnurl::lnurl::LnUrl::from_str(info)?
2317            } else if info.contains('@') {
2318                lnurl::lightning_address::LightningAddress::from_str(info)?.lnurl()
2319            } else {
2320                bail!("Invalid invoice or lnurl: {e:?}");
2321            };
2322            debug!("Parsed parameter as lnurl: {lnurl:?}");
2323            let amount = amount.context("When using a lnurl, an amount must be specified")?;
2324            let async_client = lnurl::AsyncClient::from_client(reqwest::Client::new());
2325            let response = async_client.make_request(&lnurl.url).await?;
2326            match response {
2327                lnurl::LnUrlResponse::LnUrlPayResponse(response) => {
2328                    let invoice = async_client
2329                        .get_invoice(&response, amount.msats, None, lnurl_comment.as_deref())
2330                        .await?;
2331                    let invoice = Bolt11Invoice::from_str(invoice.invoice())?;
2332                    let invoice_amount = invoice.amount_milli_satoshis();
2333                    ensure!(
2334                        invoice_amount == Some(amount.msats),
2335                        "the amount generated by the lnurl ({invoice_amount:?}) is different from the requested amount ({amount}), try again using a different amount"
2336                    );
2337                    Ok(invoice)
2338                }
2339                other => {
2340                    bail!("Unexpected response from lnurl: {other:?}");
2341                }
2342            }
2343        }
2344    }
2345}
2346
2347#[derive(Debug, Clone)]
2348pub struct LightningClientContext {
2349    pub ln_decoder: Decoder,
2350    pub redeem_key: Keypair,
2351    pub gateway_conn: Arc<dyn GatewayConnection + Send + Sync>,
2352    /// Set to `None` for the gateway since it does not emit the client events.
2353    pub client_ctx: Option<ClientContext<LightningClientModule>>,
2354}
2355
2356impl fedimint_client_module::sm::Context for LightningClientContext {
2357    const KIND: Option<ModuleKind> = Some(KIND);
2358}
2359
2360#[apply(async_trait_maybe_send!)]
2361pub trait GatewayConnection: std::fmt::Debug {
2362    // Ping gateway endpoint to verify that it is available before locking funds in
2363    // OutgoingContract
2364    async fn verify_gateway_availability(
2365        &self,
2366        gateway: &LightningGateway,
2367    ) -> Result<(), ServerError>;
2368
2369    // Request the gateway to pay a BOLT11 invoice
2370    async fn pay_invoice(
2371        &self,
2372        gateway: LightningGateway,
2373        payload: PayInvoicePayload,
2374    ) -> Result<String, GatewayPayError>;
2375}
2376
2377#[derive(Debug)]
2378pub struct RealGatewayConnection {
2379    pub api: GatewayApi,
2380}
2381
2382#[apply(async_trait_maybe_send!)]
2383impl GatewayConnection for RealGatewayConnection {
2384    async fn verify_gateway_availability(
2385        &self,
2386        gateway: &LightningGateway,
2387    ) -> Result<(), ServerError> {
2388        self.api
2389            .request::<PublicKey, serde_json::Value>(
2390                &gateway.api,
2391                Method::GET,
2392                GET_GATEWAY_ID_ENDPOINT,
2393                None,
2394            )
2395            .await?;
2396        Ok(())
2397    }
2398
2399    async fn pay_invoice(
2400        &self,
2401        gateway: LightningGateway,
2402        payload: PayInvoicePayload,
2403    ) -> Result<String, GatewayPayError> {
2404        let preimage: String = self
2405            .api
2406            .request(
2407                &gateway.api,
2408                Method::POST,
2409                PAY_INVOICE_ENDPOINT,
2410                Some(payload),
2411            )
2412            .await
2413            .map_err(|e| GatewayPayError::GatewayInternalError {
2414                error_code: None,
2415                error_message: e.to_string(),
2416            })?;
2417        let length = preimage.len();
2418        Ok(preimage[1..length - 1].to_string())
2419    }
2420}
2421
2422#[derive(Debug)]
2423pub struct MockGatewayConnection;
2424
2425#[apply(async_trait_maybe_send!)]
2426impl GatewayConnection for MockGatewayConnection {
2427    async fn verify_gateway_availability(
2428        &self,
2429        _gateway: &LightningGateway,
2430    ) -> Result<(), ServerError> {
2431        Ok(())
2432    }
2433
2434    async fn pay_invoice(
2435        &self,
2436        _gateway: LightningGateway,
2437        _payload: PayInvoicePayload,
2438    ) -> Result<String, GatewayPayError> {
2439        // Just return a fake preimage to indicate success
2440        Ok("00000000".to_string())
2441    }
2442}