Skip to main content

fedimint_gw_client/
lib.rs

1mod complete;
2pub mod events;
3pub mod pay;
4
5use std::collections::BTreeMap;
6use std::fmt;
7use std::fmt::Debug;
8use std::sync::Arc;
9use std::time::Duration;
10
11use async_stream::stream;
12use async_trait::async_trait;
13use bitcoin::hashes::{Hash, sha256};
14use bitcoin::key::Secp256k1;
15use bitcoin::secp256k1::{All, PublicKey};
16use complete::{GatewayCompleteCommon, GatewayCompleteStates, WaitForPreimageState};
17use events::{IncomingPaymentStarted, OutgoingPaymentStarted};
18use fedimint_api_client::api::DynModuleApi;
19use fedimint_client::ClientHandleArc;
20use fedimint_client_module::module::init::{ClientModuleInit, ClientModuleInitArgs};
21use fedimint_client_module::module::recovery::NoModuleBackup;
22use fedimint_client_module::module::{ClientContext, ClientModule, IClientModule, OutPointRange};
23use fedimint_client_module::oplog::UpdateStreamOrOutcome;
24use fedimint_client_module::sm::{Context, DynState, ModuleNotifier, State, StateTransition};
25use fedimint_client_module::transaction::{
26    ClientOutput, ClientOutputBundle, ClientOutputSM, TransactionBuilder,
27};
28use fedimint_client_module::{
29    AddStateMachinesError, DynGlobalClientContext, sm_enum_variant_translation,
30};
31use fedimint_connectors::ConnectorRegistry;
32use fedimint_core::config::FederationId;
33use fedimint_core::core::{Decoder, IntoDynInstance, ModuleInstanceId, ModuleKind, OperationId};
34use fedimint_core::db::{AutocommitError, DatabaseTransaction};
35use fedimint_core::encoding::{Decodable, Encodable};
36use fedimint_core::module::{Amounts, ApiVersion, ModuleInit, MultiApiVersion};
37use fedimint_core::util::{FmtCompact, SafeUrl, Spanned};
38use fedimint_core::{Amount, OutPoint, apply, async_trait_maybe_send, secp256k1};
39use fedimint_derive_secret::ChildId;
40use fedimint_lightning::{
41    InterceptPaymentRequest, InterceptPaymentResponse, LightningContext, LightningRpcError,
42    PayInvoiceResponse,
43};
44use fedimint_ln_client::api::LnFederationApi;
45use fedimint_ln_client::incoming::{
46    FundingOfferState, IncomingSmCommon, IncomingSmError, IncomingSmStates, IncomingStateMachine,
47};
48use fedimint_ln_client::pay::{PayInvoicePayload, PaymentData};
49use fedimint_ln_client::{
50    LightningClientContext, LightningClientInit, RealGatewayConnection,
51    create_incoming_contract_output,
52};
53use fedimint_ln_common::config::LightningClientConfig;
54use fedimint_ln_common::contracts::outgoing::OutgoingContractAccount;
55use fedimint_ln_common::contracts::{ContractId, Preimage};
56use fedimint_ln_common::route_hints::RouteHint;
57use fedimint_ln_common::{
58    KIND, LightningCommonInit, LightningGateway, LightningGatewayAnnouncement,
59    LightningModuleTypes, LightningOutput, LightningOutputV0, RemoveGatewayRequest,
60    create_gateway_remove_message,
61};
62use fedimint_lnv2_common::GatewayApi;
63use futures::StreamExt;
64use lightning_invoice::RoutingFees;
65use secp256k1::Keypair;
66use serde::{Deserialize, Serialize};
67use tracing::{debug, error, info, warn};
68
69use self::complete::GatewayCompleteStateMachine;
70use self::pay::{
71    GatewayPayCommon, GatewayPayInvoice, GatewayPayStateMachine, GatewayPayStates,
72    OutgoingPaymentError,
73};
74
75/// The high-level state of a reissue operation started with
76/// [`GatewayClientModule::gateway_pay_bolt11_invoice`].
77#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
78pub enum GatewayExtPayStates {
79    Created,
80    Preimage {
81        preimage: Preimage,
82    },
83    Success {
84        preimage: Preimage,
85        out_points: Vec<OutPoint>,
86    },
87    Canceled {
88        error: OutgoingPaymentError,
89    },
90    Fail {
91        error: OutgoingPaymentError,
92        error_message: String,
93    },
94    OfferDoesNotExist {
95        contract_id: ContractId,
96    },
97}
98
99/// The high-level state of an intercepted HTLC operation started with
100/// [`GatewayClientModule::gateway_handle_intercepted_htlc`].
101#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
102pub enum GatewayExtReceiveStates {
103    Funding,
104    Preimage(Preimage),
105    RefundSuccess {
106        out_points: Vec<OutPoint>,
107        error: IncomingSmError,
108    },
109    RefundError {
110        error_message: String,
111        error: IncomingSmError,
112    },
113    FundingFailed {
114        error: IncomingSmError,
115    },
116}
117
118#[derive(Debug, Clone, Serialize, Deserialize)]
119pub enum GatewayMeta {
120    Pay,
121    Receive,
122}
123
124#[derive(Debug, Clone)]
125pub struct GatewayClientInit {
126    pub federation_index: u64,
127    pub lightning_manager: Arc<dyn IGatewayClientV1>,
128}
129
130impl ModuleInit for GatewayClientInit {
131    type Common = LightningCommonInit;
132
133    async fn dump_database(
134        &self,
135        _dbtx: &mut DatabaseTransaction<'_>,
136        _prefix_names: Vec<String>,
137    ) -> Box<dyn Iterator<Item = (String, Box<dyn erased_serde::Serialize + Send>)> + '_> {
138        Box::new(vec![].into_iter())
139    }
140}
141
142#[apply(async_trait_maybe_send!)]
143impl ClientModuleInit for GatewayClientInit {
144    type Module = GatewayClientModule;
145
146    fn supported_api_versions(&self) -> MultiApiVersion {
147        MultiApiVersion::try_from_iter([ApiVersion { major: 0, minor: 0 }])
148            .expect("no version conflicts")
149    }
150
151    async fn init(&self, args: &ClientModuleInitArgs<Self>) -> anyhow::Result<Self::Module> {
152        Ok(GatewayClientModule {
153            cfg: args.cfg().clone(),
154            notifier: args.notifier().clone(),
155            redeem_key: args
156                .module_root_secret()
157                .child_key(ChildId(0))
158                .to_secp_key(&fedimint_core::secp256k1::Secp256k1::new()),
159            module_api: args.module_api().clone(),
160            federation_index: self.federation_index,
161            client_ctx: args.context(),
162            lightning_manager: self.lightning_manager.clone(),
163            connector_registry: args.connector_registry.clone(),
164        })
165    }
166}
167
168#[derive(Debug, Clone)]
169pub struct GatewayClientContext {
170    redeem_key: Keypair,
171    secp: Secp256k1<All>,
172    pub ln_decoder: Decoder,
173    notifier: ModuleNotifier<GatewayClientStateMachines>,
174    pub client_ctx: ClientContext<GatewayClientModule>,
175    pub lightning_manager: Arc<dyn IGatewayClientV1>,
176    pub connector_registry: ConnectorRegistry,
177}
178
179impl Context for GatewayClientContext {
180    const KIND: Option<ModuleKind> = Some(fedimint_ln_common::KIND);
181}
182
183impl From<&GatewayClientContext> for LightningClientContext {
184    fn from(ctx: &GatewayClientContext) -> Self {
185        let gateway_conn = RealGatewayConnection {
186            api: GatewayApi::new(None, ctx.connector_registry.clone()),
187        };
188        LightningClientContext {
189            ln_decoder: ctx.ln_decoder.clone(),
190            redeem_key: ctx.redeem_key,
191            gateway_conn: Arc::new(gateway_conn),
192            client_ctx: None,
193        }
194    }
195}
196
197/// Client side Lightning module **for the gateway**.
198///
199/// For the client side Lightning module for normal clients,
200/// see [`fedimint_ln_client::LightningClientModule`]
201#[derive(Debug)]
202pub struct GatewayClientModule {
203    cfg: LightningClientConfig,
204    pub notifier: ModuleNotifier<GatewayClientStateMachines>,
205    pub redeem_key: Keypair,
206    federation_index: u64,
207    module_api: DynModuleApi,
208    client_ctx: ClientContext<Self>,
209    pub lightning_manager: Arc<dyn IGatewayClientV1>,
210    connector_registry: ConnectorRegistry,
211}
212
213impl ClientModule for GatewayClientModule {
214    type Init = LightningClientInit;
215    type Common = LightningModuleTypes;
216    type Backup = NoModuleBackup;
217    type ModuleStateMachineContext = GatewayClientContext;
218    type States = GatewayClientStateMachines;
219
220    fn context(&self) -> Self::ModuleStateMachineContext {
221        Self::ModuleStateMachineContext {
222            redeem_key: self.redeem_key,
223            secp: Secp256k1::new(),
224            ln_decoder: self.decoder(),
225            notifier: self.notifier.clone(),
226            client_ctx: self.client_ctx.clone(),
227            lightning_manager: self.lightning_manager.clone(),
228            connector_registry: self.connector_registry.clone(),
229        }
230    }
231
232    fn input_fee(
233        &self,
234        _amount: &Amounts,
235        _input: &<Self::Common as fedimint_core::module::ModuleCommon>::Input,
236    ) -> Option<Amounts> {
237        Some(Amounts::new_bitcoin(self.cfg.fee_consensus.contract_input))
238    }
239
240    fn output_fee(
241        &self,
242        _amount: &Amounts,
243        output: &<Self::Common as fedimint_core::module::ModuleCommon>::Output,
244    ) -> Option<Amounts> {
245        match output.maybe_v0_ref()? {
246            LightningOutputV0::Contract(_) => {
247                Some(Amounts::new_bitcoin(self.cfg.fee_consensus.contract_output))
248            }
249            LightningOutputV0::Offer(_) | LightningOutputV0::CancelOutgoing { .. } => {
250                Some(Amounts::ZERO)
251            }
252        }
253    }
254}
255
256impl GatewayClientModule {
257    fn to_gateway_registration_info(
258        &self,
259        route_hints: Vec<RouteHint>,
260        ttl: Duration,
261        fees: RoutingFees,
262        lightning_context: LightningContext,
263        api: SafeUrl,
264        gateway_id: PublicKey,
265    ) -> LightningGatewayAnnouncement {
266        LightningGatewayAnnouncement {
267            info: LightningGateway {
268                federation_index: self.federation_index,
269                gateway_redeem_key: self.redeem_key.public_key(),
270                node_pub_key: lightning_context.lightning_public_key,
271                lightning_alias: lightning_context.lightning_alias,
272                api,
273                route_hints,
274                fees,
275                gateway_id,
276                supports_private_payments: lightning_context.lnrpc.supports_private_payments(),
277            },
278            ttl,
279            vetted: false,
280        }
281    }
282
283    async fn create_funding_incoming_contract_output_from_htlc(
284        &self,
285        htlc: Htlc,
286    ) -> Result<
287        (
288            OperationId,
289            Amount,
290            ClientOutput<LightningOutputV0>,
291            ClientOutputSM<GatewayClientStateMachines>,
292            ContractId,
293        ),
294        IncomingSmError,
295    > {
296        let operation_id = OperationId(htlc.payment_hash.to_byte_array());
297        let (incoming_output, amount, contract_id) = create_incoming_contract_output(
298            &self.module_api,
299            htlc.payment_hash,
300            htlc.outgoing_amount_msat,
301            &self.redeem_key,
302        )
303        .await?;
304
305        let client_output = ClientOutput::<LightningOutputV0> {
306            output: incoming_output,
307            amounts: Amounts::new_bitcoin(amount),
308        };
309        let client_output_sm = ClientOutputSM::<GatewayClientStateMachines> {
310            state_machines: Arc::new(move |out_point_range: OutPointRange| {
311                assert_eq!(out_point_range.count(), 1);
312                vec![
313                    GatewayClientStateMachines::Receive(IncomingStateMachine {
314                        common: IncomingSmCommon {
315                            operation_id,
316                            contract_id,
317                            payment_hash: htlc.payment_hash,
318                        },
319                        state: IncomingSmStates::FundingOffer(FundingOfferState {
320                            txid: out_point_range.txid(),
321                        }),
322                    }),
323                    GatewayClientStateMachines::Complete(GatewayCompleteStateMachine {
324                        common: GatewayCompleteCommon {
325                            operation_id,
326                            payment_hash: htlc.payment_hash,
327                            incoming_chan_id: htlc.incoming_chan_id,
328                            htlc_id: htlc.htlc_id,
329                        },
330                        state: GatewayCompleteStates::WaitForPreimage(WaitForPreimageState),
331                    }),
332                ]
333            }),
334        };
335        Ok((
336            operation_id,
337            amount,
338            client_output,
339            client_output_sm,
340            contract_id,
341        ))
342    }
343
344    async fn create_funding_incoming_contract_output_from_swap(
345        &self,
346        swap: SwapParameters,
347    ) -> Result<
348        (
349            OperationId,
350            ClientOutput<LightningOutputV0>,
351            ClientOutputSM<GatewayClientStateMachines>,
352        ),
353        IncomingSmError,
354    > {
355        let payment_hash = swap.payment_hash;
356        let operation_id = OperationId(payment_hash.to_byte_array());
357        let (incoming_output, amount, contract_id) = create_incoming_contract_output(
358            &self.module_api,
359            payment_hash,
360            swap.amount_msat,
361            &self.redeem_key,
362        )
363        .await?;
364
365        let client_output = ClientOutput::<LightningOutputV0> {
366            output: incoming_output,
367            amounts: Amounts::new_bitcoin(amount),
368        };
369        let client_output_sm = ClientOutputSM::<GatewayClientStateMachines> {
370            state_machines: Arc::new(move |out_point_range| {
371                assert_eq!(out_point_range.count(), 1);
372                vec![GatewayClientStateMachines::Receive(IncomingStateMachine {
373                    common: IncomingSmCommon {
374                        operation_id,
375                        contract_id,
376                        payment_hash,
377                    },
378                    state: IncomingSmStates::FundingOffer(FundingOfferState {
379                        txid: out_point_range.txid(),
380                    }),
381                })]
382            }),
383        };
384        Ok((operation_id, client_output, client_output_sm))
385    }
386
387    /// Register gateway with federation
388    pub async fn try_register_with_federation(
389        &self,
390        route_hints: Vec<RouteHint>,
391        time_to_live: Duration,
392        fees: RoutingFees,
393        lightning_context: LightningContext,
394        api: SafeUrl,
395        gateway_id: PublicKey,
396    ) {
397        let registration_info = self.to_gateway_registration_info(
398            route_hints,
399            time_to_live,
400            fees,
401            lightning_context,
402            api,
403            gateway_id,
404        );
405        let gateway_id = registration_info.info.gateway_id;
406
407        let federation_id = self
408            .client_ctx
409            .get_config()
410            .await
411            .global
412            .calculate_federation_id();
413        match self.module_api.register_gateway(&registration_info).await {
414            Err(e) => {
415                warn!(
416                    e = %e.fmt_compact(),
417                    "Failed to register gateway {gateway_id} with federation {federation_id}"
418                );
419            }
420            _ => {
421                info!(
422                    "Successfully registered gateway {gateway_id} with federation {federation_id}"
423                );
424            }
425        }
426    }
427
428    /// Attempts to remove a gateway's registration from the federation. Since
429    /// removing gateway registrations is best effort, this does not return
430    /// an error and simply emits a warning when the registration cannot be
431    /// removed.
432    pub async fn remove_from_federation(&self, gateway_keypair: Keypair) {
433        // Removing gateway registrations is best effort, so just emit a warning if it
434        // fails
435        if let Err(e) = self.remove_from_federation_inner(gateway_keypair).await {
436            let gateway_id = gateway_keypair.public_key();
437            let federation_id = self
438                .client_ctx
439                .get_config()
440                .await
441                .global
442                .calculate_federation_id();
443            warn!("Failed to remove gateway {gateway_id} from federation {federation_id}: {e:?}");
444        }
445    }
446
447    /// Retrieves the signing challenge from each federation peer. Since each
448    /// peer maintains their own list of registered gateways, the gateway
449    /// needs to provide a signature that is signed by the private key of the
450    /// gateway id to remove the registration.
451    async fn remove_from_federation_inner(&self, gateway_keypair: Keypair) -> anyhow::Result<()> {
452        let gateway_id = gateway_keypair.public_key();
453        let challenges = self
454            .module_api
455            .get_remove_gateway_challenge(gateway_id)
456            .await;
457
458        let fed_public_key = self.cfg.threshold_pub_key;
459        let signatures = challenges
460            .into_iter()
461            .filter_map(|(peer_id, challenge)| {
462                let msg = create_gateway_remove_message(fed_public_key, peer_id, challenge?);
463                let signature = gateway_keypair.sign_schnorr(msg);
464                Some((peer_id, signature))
465            })
466            .collect::<BTreeMap<_, _>>();
467
468        let remove_gateway_request = RemoveGatewayRequest {
469            gateway_id,
470            signatures,
471        };
472
473        self.module_api.remove_gateway(remove_gateway_request).await;
474
475        Ok(())
476    }
477
478    /// Attempt fulfill HTLC by buying preimage from the federation
479    pub async fn gateway_handle_intercepted_htlc(&self, htlc: Htlc) -> anyhow::Result<OperationId> {
480        debug!("Handling intercepted HTLC {htlc:?}");
481        let (operation_id, amount, client_output, client_output_sm, contract_id) = self
482            .create_funding_incoming_contract_output_from_htlc(htlc.clone())
483            .await?;
484
485        let output = ClientOutput {
486            output: LightningOutput::V0(client_output.output),
487            amounts: Amounts::new_bitcoin(amount),
488        };
489
490        let tx = TransactionBuilder::new().with_outputs(self.client_ctx.make_client_outputs(
491            ClientOutputBundle::new(vec![output], vec![client_output_sm]),
492        ));
493        let operation_meta_gen = |_: OutPointRange| GatewayMeta::Receive;
494        self.client_ctx
495            .finalize_and_submit_transaction(operation_id, KIND.as_str(), operation_meta_gen, tx)
496            .await?;
497        debug!(?operation_id, "Submitted transaction for HTLC {htlc:?}");
498        let mut dbtx = self.client_ctx.module_db().begin_transaction().await;
499        self.client_ctx
500            .log_event(
501                &mut dbtx,
502                IncomingPaymentStarted {
503                    contract_id,
504                    payment_hash: htlc.payment_hash,
505                    invoice_amount: htlc.outgoing_amount_msat,
506                    contract_amount: amount,
507                    operation_id,
508                },
509            )
510            .await;
511        dbtx.commit_tx().await;
512        Ok(operation_id)
513    }
514
515    /// Attempt buying preimage from this federation in order to fulfill a pay
516    /// request in another federation served by this gateway. In direct swap
517    /// scenario, the gateway DOES NOT send payment over the lightning network
518    pub async fn gateway_handle_direct_swap(
519        &self,
520        swap_params: SwapParameters,
521    ) -> anyhow::Result<OperationId> {
522        debug!("Handling direct swap {swap_params:?}");
523        let (operation_id, client_output, client_output_sm) = self
524            .create_funding_incoming_contract_output_from_swap(swap_params.clone())
525            .await?;
526
527        let output = ClientOutput {
528            output: LightningOutput::V0(client_output.output),
529            amounts: client_output.amounts,
530        };
531        let tx = TransactionBuilder::new().with_outputs(self.client_ctx.make_client_outputs(
532            ClientOutputBundle::new(vec![output], vec![client_output_sm]),
533        ));
534        let operation_meta_gen = |_: OutPointRange| GatewayMeta::Receive;
535        self.client_ctx
536            .finalize_and_submit_transaction(operation_id, KIND.as_str(), operation_meta_gen, tx)
537            .await?;
538        debug!(
539            ?operation_id,
540            "Submitted transaction for direct swap {swap_params:?}"
541        );
542        Ok(operation_id)
543    }
544
545    /// Subscribe to updates when the gateway is handling an intercepted HTLC,
546    /// or direct swap between federations
547    pub async fn gateway_subscribe_ln_receive(
548        &self,
549        operation_id: OperationId,
550    ) -> anyhow::Result<UpdateStreamOrOutcome<GatewayExtReceiveStates>> {
551        let operation = self.client_ctx.get_operation(operation_id).await?;
552        let mut stream = self.notifier.subscribe(operation_id).await;
553        let client_ctx = self.client_ctx.clone();
554
555        Ok(self.client_ctx.outcome_or_updates(operation, operation_id, move || {
556            stream! {
557
558                yield GatewayExtReceiveStates::Funding;
559
560                let state = loop {
561                    debug!("Getting next ln receive state for {}", operation_id.fmt_short());
562                    if let Some(GatewayClientStateMachines::Receive(state)) = stream.next().await {
563                        match state.state {
564                            IncomingSmStates::Preimage(preimage) =>{
565                                debug!(?operation_id, "Received preimage");
566                                break GatewayExtReceiveStates::Preimage(preimage)
567                            },
568                            IncomingSmStates::RefundSubmitted { out_points, error } => {
569                                debug!(?operation_id, "Refund submitted for {out_points:?} {error}");
570                                match client_ctx.await_primary_module_outputs(operation_id, out_points.clone()).await {
571                                    Ok(()) => {
572                                        debug!(?operation_id, "Refund success");
573                                        break GatewayExtReceiveStates::RefundSuccess { out_points, error }
574                                    },
575                                    Err(e) => {
576                                        warn!(?operation_id, "Got failure {e:?} while awaiting for refund outputs {out_points:?}");
577                                        break GatewayExtReceiveStates::RefundError{ error_message: e.to_string(), error }
578                                    },
579                                }
580                            },
581                            IncomingSmStates::FundingFailed { error } => {
582                                warn!(?operation_id, "Funding failed: {error:?}");
583                                break GatewayExtReceiveStates::FundingFailed{ error }
584                            },
585                            other => {
586                                debug!("Got state {other:?} while awaiting for output of {}", operation_id.fmt_short());
587                            }
588                        }
589                    }
590                };
591                yield state;
592            }
593        }))
594    }
595
596    /// For the given `OperationId`, this function will wait until the Complete
597    /// state machine has finished or failed.
598    pub async fn await_completion(&self, operation_id: OperationId) {
599        let mut stream = self.notifier.subscribe(operation_id).await;
600        loop {
601            match stream.next().await {
602                Some(GatewayClientStateMachines::Complete(state)) => match state.state {
603                    GatewayCompleteStates::HtlcFinished => {
604                        info!(%state, "LNv1 completion state machine finished");
605                        return;
606                    }
607                    GatewayCompleteStates::Failure => {
608                        error!(%state, "LNv1 completion state machine failed");
609                        return;
610                    }
611                    _ => {
612                        info!(%state, "Waiting for LNv1 completion state machine");
613                        continue;
614                    }
615                },
616                Some(GatewayClientStateMachines::Receive(state)) => {
617                    info!(%state, "Waiting for LNv1 completion state machine");
618                    continue;
619                }
620                Some(state) => {
621                    warn!(%state, "Operation is not an LNv1 completion state machine");
622                    return;
623                }
624                None => return,
625            }
626        }
627    }
628
629    /// Pay lightning invoice on behalf of federation user
630    pub async fn gateway_pay_bolt11_invoice(
631        &self,
632        pay_invoice_payload: PayInvoicePayload,
633    ) -> anyhow::Result<OperationId> {
634        let payload = pay_invoice_payload.clone();
635        self.lightning_manager
636            .verify_pruned_invoice(pay_invoice_payload.payment_data)
637            .await?;
638
639        self.client_ctx.module_db()
640            .autocommit(
641                |dbtx, _| {
642                    Box::pin(async {
643                        let operation_id = OperationId(payload.contract_id.to_byte_array());
644
645                        self.client_ctx.log_event(dbtx, OutgoingPaymentStarted {
646                            contract_id: payload.contract_id,
647                            invoice_amount: payload.payment_data.amount().expect("LNv1 invoices should have an amount"),
648                            operation_id,
649                        }).await;
650
651                        let state_machines =
652                            vec![GatewayClientStateMachines::Pay(GatewayPayStateMachine {
653                                common: GatewayPayCommon { operation_id },
654                                state: GatewayPayStates::PayInvoice(GatewayPayInvoice {
655                                    pay_invoice_payload: payload.clone(),
656                                }),
657                            })];
658
659                        let dyn_states = state_machines
660                            .into_iter()
661                            .map(|s| self.client_ctx.make_dyn(s))
662                            .collect();
663
664                            match self.client_ctx.add_state_machines_dbtx(dbtx, dyn_states).await {
665                                Ok(()) => {
666                                    self.client_ctx
667                                        .add_operation_log_entry_dbtx(
668                                            dbtx,
669                                            operation_id,
670                                            KIND.as_str(),
671                                            GatewayMeta::Pay,
672                                        )
673                                        .await;
674                                }
675                                Err(AddStateMachinesError::StateAlreadyExists) => {
676                                    info!("State machine for operation {} already exists, will not add a new one", operation_id.fmt_short());
677                                }
678                                Err(other) => {
679                                    anyhow::bail!("Failed to add state machines: {other:?}")
680                                }
681                            }
682                            Ok(operation_id)
683                    })
684                },
685                Some(100),
686            )
687            .await
688            .map_err(|e| match e {
689                AutocommitError::ClosureError { error, .. } => error,
690                AutocommitError::CommitFailed { last_error, .. } => {
691                    anyhow::anyhow!("Commit to DB failed: {last_error}")
692                }
693            })
694    }
695
696    pub async fn gateway_subscribe_ln_pay(
697        &self,
698        operation_id: OperationId,
699    ) -> anyhow::Result<UpdateStreamOrOutcome<GatewayExtPayStates>> {
700        let mut stream = self.notifier.subscribe(operation_id).await;
701        let operation = self.client_ctx.get_operation(operation_id).await?;
702        let client_ctx = self.client_ctx.clone();
703
704        Ok(self.client_ctx.outcome_or_updates(operation, operation_id, move || {
705            stream! {
706                yield GatewayExtPayStates::Created;
707
708                loop {
709                    debug!("Getting next ln pay state for {}", operation_id.fmt_short());
710                    match stream.next().await { Some(GatewayClientStateMachines::Pay(state)) => {
711                        match state.state {
712                            GatewayPayStates::Preimage(out_points, preimage) => {
713                                yield GatewayExtPayStates::Preimage{ preimage: preimage.clone() };
714
715                                match client_ctx.await_primary_module_outputs(operation_id, out_points.clone()).await {
716                                    Ok(()) => {
717                                        debug!(?operation_id, "Success");
718                                        yield GatewayExtPayStates::Success{ preimage: preimage.clone(), out_points };
719                                        return;
720
721                                    }
722                                    Err(e) => {
723                                        warn!(?operation_id, "Got failure {e:?} while awaiting for outputs {out_points:?}");
724                                        // TODO: yield something here?
725                                    }
726                                }
727                            }
728                            GatewayPayStates::Canceled { txid, contract_id, error } => {
729                                debug!(?operation_id, "Trying to cancel contract {contract_id:?} due to {error:?}");
730                                match client_ctx.transaction_updates(operation_id).await.await_tx_accepted(txid).await {
731                                    Ok(()) => {
732                                        debug!(?operation_id, "Canceled contract {contract_id:?} due to {error:?}");
733                                        yield GatewayExtPayStates::Canceled{ error };
734                                        return;
735                                    }
736                                    Err(e) => {
737                                        warn!(?operation_id, "Got failure {e:?} while awaiting for transaction {txid} to be accepted for");
738                                        yield GatewayExtPayStates::Fail { error, error_message: format!("Refund transaction {txid} was not accepted by the federation. OperationId: {} Error: {e:?}", operation_id.fmt_short()) };
739                                    }
740                                }
741                            }
742                            GatewayPayStates::OfferDoesNotExist(contract_id) => {
743                                warn!("Yielding OfferDoesNotExist state for {} and contract {contract_id}", operation_id.fmt_short());
744                                yield GatewayExtPayStates::OfferDoesNotExist { contract_id };
745                            }
746                            GatewayPayStates::Failed{ error, error_message } => {
747                                warn!("Yielding Fail state for {} due to {error:?} {error_message:?}", operation_id.fmt_short());
748                                yield GatewayExtPayStates::Fail{ error, error_message };
749                            },
750                            GatewayPayStates::PayInvoice(_) => {
751                                debug!("Got initial state PayInvoice while awaiting for output of {}", operation_id.fmt_short());
752                            }
753                            other => {
754                                info!("Got state {other:?} while awaiting for output of {}", operation_id.fmt_short());
755                            }
756                        }
757                    } _ => {
758                        warn!("Got None while getting next ln pay state for {}", operation_id.fmt_short());
759                    }}
760                }
761            }
762        }))
763    }
764}
765
766#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
767pub enum GatewayClientStateMachines {
768    Pay(GatewayPayStateMachine),
769    Receive(IncomingStateMachine),
770    Complete(GatewayCompleteStateMachine),
771}
772
773impl fmt::Display for GatewayClientStateMachines {
774    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
775        match self {
776            GatewayClientStateMachines::Pay(pay) => {
777                write!(f, "{pay}")
778            }
779            GatewayClientStateMachines::Receive(receive) => {
780                write!(f, "{receive}")
781            }
782            GatewayClientStateMachines::Complete(complete) => {
783                write!(f, "{complete}")
784            }
785        }
786    }
787}
788
789impl IntoDynInstance for GatewayClientStateMachines {
790    type DynType = DynState;
791
792    fn into_dyn(self, instance_id: ModuleInstanceId) -> Self::DynType {
793        DynState::from_typed(instance_id, self)
794    }
795}
796
797impl State for GatewayClientStateMachines {
798    type ModuleContext = GatewayClientContext;
799
800    fn transitions(
801        &self,
802        context: &Self::ModuleContext,
803        global_context: &DynGlobalClientContext,
804    ) -> Vec<StateTransition<Self>> {
805        match self {
806            GatewayClientStateMachines::Pay(pay_state) => {
807                sm_enum_variant_translation!(
808                    pay_state.transitions(context, global_context),
809                    GatewayClientStateMachines::Pay
810                )
811            }
812            GatewayClientStateMachines::Receive(receive_state) => {
813                sm_enum_variant_translation!(
814                    receive_state.transitions(&context.into(), global_context),
815                    GatewayClientStateMachines::Receive
816                )
817            }
818            GatewayClientStateMachines::Complete(complete_state) => {
819                sm_enum_variant_translation!(
820                    complete_state.transitions(context, global_context),
821                    GatewayClientStateMachines::Complete
822                )
823            }
824        }
825    }
826
827    fn operation_id(&self) -> fedimint_core::core::OperationId {
828        match self {
829            GatewayClientStateMachines::Pay(pay_state) => pay_state.operation_id(),
830            GatewayClientStateMachines::Receive(receive_state) => receive_state.operation_id(),
831            GatewayClientStateMachines::Complete(complete_state) => complete_state.operation_id(),
832        }
833    }
834}
835
836#[derive(Debug, Clone, Eq, PartialEq)]
837pub struct Htlc {
838    /// The HTLC payment hash.
839    pub payment_hash: sha256::Hash,
840    /// The incoming HTLC amount in millisatoshi.
841    pub incoming_amount_msat: Amount,
842    /// The outgoing HTLC amount in millisatoshi
843    pub outgoing_amount_msat: Amount,
844    /// The incoming HTLC expiry
845    pub incoming_expiry: u32,
846    /// The short channel id of the HTLC.
847    pub short_channel_id: Option<u64>,
848    /// The id of the incoming channel
849    pub incoming_chan_id: u64,
850    /// The index of the incoming htlc in the incoming channel
851    pub htlc_id: u64,
852}
853
854impl TryFrom<InterceptPaymentRequest> for Htlc {
855    type Error = anyhow::Error;
856
857    fn try_from(s: InterceptPaymentRequest) -> Result<Self, Self::Error> {
858        Ok(Self {
859            payment_hash: s.payment_hash,
860            incoming_amount_msat: Amount::from_msats(s.amount_msat),
861            outgoing_amount_msat: Amount::from_msats(s.amount_msat),
862            incoming_expiry: s.expiry,
863            short_channel_id: s.short_channel_id,
864            incoming_chan_id: s.incoming_chan_id,
865            htlc_id: s.htlc_id,
866        })
867    }
868}
869
870#[derive(Debug, Clone)]
871pub struct SwapParameters {
872    pub payment_hash: sha256::Hash,
873    pub amount_msat: Amount,
874}
875
876impl TryFrom<PaymentData> for SwapParameters {
877    type Error = anyhow::Error;
878
879    fn try_from(s: PaymentData) -> Result<Self, Self::Error> {
880        let payment_hash = s.payment_hash();
881        let amount_msat = s
882            .amount()
883            .ok_or_else(|| anyhow::anyhow!("Amountless invoice cannot be used in direct swap"))?;
884        Ok(Self {
885            payment_hash,
886            amount_msat,
887        })
888    }
889}
890
891/// An interface between module implementation and the general `Gateway`
892///
893/// To abstract away and decouple the core gateway from the modules, the
894/// interface between them is expressed as a trait. The gateway handles
895/// operations that require Lightning node access or database access.
896#[async_trait]
897pub trait IGatewayClientV1: Debug + Send + Sync {
898    /// Verifies that the supplied `preimage_auth` is the same as the
899    /// `preimage_auth` that initiated the payment.
900    ///
901    /// If it is not, then this will return an error because this client is not
902    /// authorized to receive the preimage.
903    async fn verify_preimage_authentication(
904        &self,
905        payment_hash: sha256::Hash,
906        preimage_auth: sha256::Hash,
907        contract: OutgoingContractAccount,
908    ) -> Result<(), OutgoingPaymentError>;
909
910    /// Verify that the lightning node supports private payments if a pruned
911    /// invoice is supplied.
912    async fn verify_pruned_invoice(&self, payment_data: PaymentData) -> anyhow::Result<()>;
913
914    /// Retrieves the federation's routing fees from the federation's config.
915    async fn get_routing_fees(&self, federation_id: FederationId) -> Option<RoutingFees>;
916
917    /// Retrieve a client given a federation ID, used for swapping ecash between
918    /// federations.
919    async fn get_client(&self, federation_id: &FederationId) -> Option<Spanned<ClientHandleArc>>;
920
921    // Retrieve a client given an invoice.
922    //
923    // Checks if the invoice route hint last hop has source node id matching this
924    // gateways node pubkey and if the short channel id matches one assigned by
925    // this gateway to a connected federation. In this case, the gateway can
926    // avoid paying the invoice over the lightning network and instead perform a
927    // direct swap between the two federations.
928    async fn get_client_for_invoice(
929        &self,
930        payment_data: PaymentData,
931    ) -> Option<Spanned<ClientHandleArc>>;
932
933    /// Pay a Lightning invoice using the gateway's lightning node.
934    async fn pay(
935        &self,
936        payment_data: PaymentData,
937        max_delay: u64,
938        max_fee: Amount,
939    ) -> Result<PayInvoiceResponse, LightningRpcError>;
940
941    /// Use the gateway's lightning node to send a complete HTLC response.
942    async fn complete_htlc(
943        &self,
944        htlc_response: InterceptPaymentResponse,
945    ) -> Result<(), LightningRpcError>;
946
947    /// Check if the gateway satisfy the LNv1 payment by funding an LNv2
948    /// `IncomingContract`
949    async fn is_lnv2_direct_swap(
950        &self,
951        payment_hash: sha256::Hash,
952        amount: Amount,
953    ) -> anyhow::Result<
954        Option<(
955            fedimint_lnv2_common::contracts::IncomingContract,
956            ClientHandleArc,
957        )>,
958    >;
959}