Skip to main content

fedimint_gw_client/
lib.rs

1mod complete;
2pub mod error;
3pub mod events;
4pub mod pay;
5#[cfg(test)]
6mod tests;
7
8use std::collections::BTreeMap;
9use std::fmt;
10use std::fmt::Debug;
11use std::future::Future;
12use std::sync::Arc;
13use std::time::Duration;
14
15use async_stream::stream;
16use async_trait::async_trait;
17use bitcoin::hashes::{Hash, sha256};
18use bitcoin::key::Secp256k1;
19use bitcoin::secp256k1::All;
20use complete::{GatewayCompleteCommon, GatewayCompleteStates, WaitForPreimageState};
21use events::{IncomingPaymentStarted, OutgoingPaymentStarted};
22use fedimint_api_client::api::DynModuleApi;
23use fedimint_client::ClientHandleArc;
24use fedimint_client_module::error::ClientModuleError;
25use fedimint_client_module::module::init::{ClientModuleInit, ClientModuleInitArgs};
26use fedimint_client_module::module::recovery::NoModuleBackup;
27use fedimint_client_module::module::{ClientContext, ClientModule, IClientModule, OutPointRange};
28use fedimint_client_module::oplog::UpdateStreamOrOutcome;
29use fedimint_client_module::sm::{Context, DynState, ModuleNotifier, State, StateTransition};
30use fedimint_client_module::transaction::{
31    ClientOutput, ClientOutputBundle, ClientOutputSM, TransactionBuilder,
32};
33use fedimint_client_module::{
34    AddStateMachinesError, DynGlobalClientContext, OperationLookupError,
35    sm_enum_variant_translation,
36};
37use fedimint_connectors::ConnectorRegistry;
38use fedimint_core::config::FederationId;
39use fedimint_core::core::{
40    Account, Decoder, IntoDynInstance, ModuleInstanceId, ModuleKind, OperationId,
41};
42use fedimint_core::db::DatabaseTransaction;
43use fedimint_core::encoding::{Decodable, Encodable};
44use fedimint_core::module::{Amounts, ApiVersion, ModuleInit, MultiApiVersion};
45use fedimint_core::time::duration_since_epoch;
46use fedimint_core::util::{FmtCompact, SafeUrl, Spanned};
47use fedimint_core::{Amount, OutPoint, apply, async_trait_maybe_send, secp256k1};
48use fedimint_derive_secret::ChildId;
49use fedimint_lightning::{
50    InterceptPaymentRequest, InterceptPaymentResponse, LightningContext, LightningRpcError,
51    PayInvoiceResponse,
52};
53use fedimint_ln_client::api::LnFederationApi;
54use fedimint_ln_client::incoming::{
55    FundingOfferState, IncomingSmCommon, IncomingSmError, IncomingSmStates, IncomingStateMachine,
56};
57use fedimint_ln_client::pay::{PayInvoicePayload, PaymentData};
58use fedimint_ln_client::{
59    LightningClientContext, LightningClientInit, RealGatewayConnection,
60    create_incoming_contract_output,
61};
62use fedimint_ln_common::config::LightningClientConfig;
63use fedimint_ln_common::contracts::outgoing::OutgoingContractAccount;
64use fedimint_ln_common::contracts::{ContractId, FundedContract, Preimage};
65use fedimint_ln_common::route_hints::RouteHint;
66use fedimint_ln_common::{
67    GatewayRegistrationAuth, KIND, LNV1_INCOMING_HTLC_ADVERTISED_EXPIRY_DELTA,
68    LNV1_INCOMING_HTLC_EXPIRY_SAFETY_MARGIN, LightningCommonInit, LightningGateway,
69    LightningGatewayAnnouncement, LightningModuleTypes, LightningOutput, LightningOutputV0,
70    MissingInvoiceAmountError, PreimageAuth, RemoveGatewayRequest,
71    create_gateway_registration_message, create_gateway_remove_message,
72};
73use fedimint_lnv2_common::GatewayApi;
74use futures::StreamExt;
75use lightning_invoice::RoutingFees;
76use secp256k1::Keypair;
77use serde::{Deserialize, Serialize};
78use thiserror::Error;
79use tracing::{debug, error, info, warn};
80
81use self::complete::GatewayCompleteStateMachine;
82use self::pay::{
83    GatewayPayCancelContract, GatewayPayCommon, GatewayPayInvoice, GatewayPayStateMachine,
84    GatewayPayStates, OutgoingPaymentError,
85};
86pub use crate::error::{
87    GatewayClientV1Error, GatewayPayInvoiceError, HandleDirectSwapError, HandleInterceptedHtlcError,
88};
89
90/// Exclusive remaining-CLTV safety margin for an intercepted LNv1 HTLC.
91///
92/// This reserves the worst-case time to claim the HTLC on-chain after
93/// federation funding and threshold decryption. Exactly the margin is
94/// rejected; fresh funding requires at least one additional block. The value
95/// deliberately matches the route-hint delta advertised by pre-upgrade
96/// clients so their invoices remain payable; see
97/// [`LNV1_INCOMING_HTLC_EXPIRY_SAFETY_MARGIN`] for the plan to raise it.
98pub const LNV1_HTLC_EXPIRY_SAFETY_MARGIN: u32 = LNV1_INCOMING_HTLC_EXPIRY_SAFETY_MARGIN as u32;
99
100/// The high-level state of a reissue operation started with
101/// [`GatewayClientModule::gateway_pay_bolt11_invoice`].
102#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
103pub enum GatewayExtPayStates {
104    Created,
105    Preimage {
106        preimage: Preimage,
107    },
108    Success {
109        preimage: Preimage,
110        out_points: Vec<OutPoint>,
111    },
112    Canceled {
113        error: OutgoingPaymentError,
114    },
115    Fail {
116        error: OutgoingPaymentError,
117        error_message: String,
118    },
119    OfferDoesNotExist {
120        contract_id: ContractId,
121    },
122}
123
124/// The high-level state of an intercepted HTLC operation started with
125/// [`GatewayClientModule::gateway_handle_intercepted_htlc`].
126#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
127pub enum GatewayExtReceiveStates {
128    Funding,
129    Preimage(Preimage),
130    RefundSuccess {
131        out_points: Vec<OutPoint>,
132        error: IncomingSmError,
133    },
134    RefundError {
135        error_message: String,
136        error: IncomingSmError,
137    },
138    FundingFailed {
139        error: IncomingSmError,
140    },
141}
142
143#[derive(Debug, Clone, Serialize, Deserialize)]
144pub enum GatewayMeta {
145    /// Carries the `preimage_auth` of the request that started the payment.
146    ///
147    /// The operation id of a payment is its contract id, which is public in the
148    /// funding transaction, and joining the operation yields the preimage. So
149    /// the operation has to record who is allowed to join it. Entries written
150    /// before this field existed decode as an error and are treated as
151    /// unauthorized, which only affects payments in flight across an upgrade.
152    Pay {
153        preimage_auth: sha256::Hash,
154    },
155    Receive,
156}
157
158#[derive(Debug, Clone)]
159pub struct GatewayClientInit {
160    pub federation_index: u64,
161    pub lightning_manager: Arc<dyn IGatewayClientV1>,
162}
163
164impl ModuleInit for GatewayClientInit {
165    type Common = LightningCommonInit;
166
167    async fn dump_database(
168        &self,
169        _dbtx: &mut DatabaseTransaction<'_>,
170        _prefix_names: Vec<String>,
171    ) -> Box<dyn Iterator<Item = (String, Box<dyn erased_serde::Serialize + Send>)> + '_> {
172        Box::new(vec![].into_iter())
173    }
174}
175
176#[apply(async_trait_maybe_send!)]
177impl ClientModuleInit for GatewayClientInit {
178    type Module = GatewayClientModule;
179
180    fn supported_api_versions(&self) -> MultiApiVersion {
181        MultiApiVersion::try_from_iter([ApiVersion { major: 0, minor: 0 }])
182            .expect("no version conflicts")
183    }
184
185    async fn init(
186        &self,
187        args: &ClientModuleInitArgs<Self>,
188    ) -> Result<Self::Module, ClientModuleError> {
189        Ok(GatewayClientModule {
190            cfg: args.cfg().clone(),
191            notifier: args.notifier().clone(),
192            redeem_key: args
193                .module_root_secret()
194                .child_key(ChildId(0))
195                .to_secp_key(&fedimint_core::secp256k1::Secp256k1::new()),
196            module_api: args.module_api().clone(),
197            federation_index: self.federation_index,
198            client_ctx: args.context(),
199            lightning_manager: self.lightning_manager.clone(),
200            connector_registry: args.connector_registry.clone(),
201            intercepted_htlc_lock_pool: lockable::LockPool::new(),
202        })
203    }
204}
205
206#[derive(Debug, Clone)]
207pub struct GatewayClientContext {
208    redeem_key: Keypair,
209    secp: Secp256k1<All>,
210    pub ln_decoder: Decoder,
211    notifier: ModuleNotifier<GatewayClientStateMachines>,
212    pub client_ctx: ClientContext<GatewayClientModule>,
213    pub lightning_manager: Arc<dyn IGatewayClientV1>,
214    pub connector_registry: ConnectorRegistry,
215}
216
217impl Context for GatewayClientContext {
218    const KIND: Option<ModuleKind> = Some(fedimint_ln_common::KIND);
219}
220
221impl From<&GatewayClientContext> for LightningClientContext {
222    fn from(ctx: &GatewayClientContext) -> Self {
223        let gateway_conn = RealGatewayConnection {
224            api: GatewayApi::new(None, ctx.connector_registry.clone()),
225        };
226        LightningClientContext {
227            ln_decoder: ctx.ln_decoder.clone(),
228            redeem_key: ctx.redeem_key,
229            gateway_conn: Arc::new(gateway_conn),
230            client_ctx: None,
231        }
232    }
233}
234
235/// Client side Lightning module **for the gateway**.
236///
237/// For the client side Lightning module for normal clients,
238/// see [`fedimint_ln_client::LightningClientModule`]
239pub struct GatewayClientModule {
240    cfg: LightningClientConfig,
241    pub notifier: ModuleNotifier<GatewayClientStateMachines>,
242    pub redeem_key: Keypair,
243    federation_index: u64,
244    module_api: DynModuleApi,
245    client_ctx: ClientContext<Self>,
246    pub lightning_manager: Arc<dyn IGatewayClientV1>,
247    connector_registry: ConnectorRegistry,
248    intercepted_htlc_lock_pool: lockable::LockPool<HtlcCircuitKey>,
249}
250
251impl fmt::Debug for GatewayClientModule {
252    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
253        f.debug_struct("GatewayClientModule")
254            .finish_non_exhaustive()
255    }
256}
257
258impl ClientModule for GatewayClientModule {
259    type Init = LightningClientInit;
260    type Common = LightningModuleTypes;
261    type Backup = NoModuleBackup;
262    type ModuleStateMachineContext = GatewayClientContext;
263    type States = GatewayClientStateMachines;
264
265    fn context(&self) -> Self::ModuleStateMachineContext {
266        Self::ModuleStateMachineContext {
267            redeem_key: self.redeem_key,
268            secp: Secp256k1::new(),
269            ln_decoder: self.decoder(),
270            notifier: self.notifier.clone(),
271            client_ctx: self.client_ctx.clone(),
272            lightning_manager: self.lightning_manager.clone(),
273            connector_registry: self.connector_registry.clone(),
274        }
275    }
276
277    fn input_fee(
278        &self,
279        _amount: &Amounts,
280        _input: &<Self::Common as fedimint_core::module::ModuleCommon>::Input,
281    ) -> Option<Amounts> {
282        Some(Amounts::new_bitcoin(self.cfg.fee_consensus.contract_input))
283    }
284
285    fn output_fee(
286        &self,
287        _amount: &Amounts,
288        output: &<Self::Common as fedimint_core::module::ModuleCommon>::Output,
289    ) -> Option<Amounts> {
290        match output.maybe_v0_ref()? {
291            LightningOutputV0::Contract(_) => {
292                Some(Amounts::new_bitcoin(self.cfg.fee_consensus.contract_output))
293            }
294            LightningOutputV0::Offer(_) | LightningOutputV0::CancelOutgoing { .. } => {
295                Some(Amounts::ZERO)
296            }
297        }
298    }
299}
300
301impl GatewayClientModule {
302    fn to_gateway_registration_info(
303        &self,
304        route_hints: Vec<RouteHint>,
305        ttl: Duration,
306        fees: RoutingFees,
307        lightning_context: LightningContext,
308        api: SafeUrl,
309        gateway_keypair: Keypair,
310    ) -> LightningGatewayAnnouncement {
311        let info = LightningGateway {
312            federation_index: self.federation_index,
313            gateway_redeem_key: self.redeem_key.public_key(),
314            node_pub_key: lightning_context.lightning_public_key,
315            lightning_alias: lightning_context.lightning_alias,
316            api,
317            route_hints,
318            fees,
319            gateway_id: gateway_keypair.public_key(),
320            supports_private_payments: lightning_context.lnrpc.supports_private_payments(),
321        };
322
323        // Proves to the guardians that we hold the key behind `gateway_id`, so
324        // nobody else can replace our registration. Wall-clock milliseconds give
325        // a nonce that keeps increasing across restarts without persisting
326        // state; guardians only compare it to the nonce they already hold for
327        // us, so our clock need not agree with theirs.
328        let nonce = u64::try_from(duration_since_epoch().as_millis())
329            .expect("milliseconds since the epoch do not exceed u64 for another 500m years");
330        let signature = gateway_keypair.sign_schnorr(create_gateway_registration_message(
331            self.cfg.threshold_pub_key,
332            nonce,
333            &info,
334        ));
335
336        LightningGatewayAnnouncement {
337            info,
338            ttl,
339            vetted: false,
340            auth: Some(GatewayRegistrationAuth { nonce, signature }),
341        }
342    }
343
344    async fn create_funding_incoming_contract_output_from_htlc(
345        &self,
346        htlc: Htlc,
347    ) -> Result<
348        (
349            OperationId,
350            Amount,
351            ClientOutput<LightningOutputV0>,
352            ClientOutputSM<GatewayClientStateMachines>,
353            ContractId,
354        ),
355        IncomingSmError,
356    > {
357        let operation_id = OperationId(htlc.payment_hash.to_byte_array());
358        // The amount passed here only guards solvency: the contract is always
359        // funded at the offer amount, and `create_incoming_contract_output`
360        // rejects the HTLC if this value falls short of it. It must therefore
361        // be the amount actually locked in the incoming HTLC, never the
362        // sender-controlled onion forward amount -- otherwise a sender could
363        // lock a token amount while declaring a large `amt_to_forward`, pass
364        // the check, and have the gateway fund the full offer amount from its
365        // own ecash against a near-worthless HTLC.
366        let (incoming_output, amount, contract_id) = create_incoming_contract_output(
367            &self.module_api,
368            htlc.payment_hash,
369            htlc.incoming_amount_msat,
370            &self.redeem_key,
371        )
372        .await?;
373
374        let client_output = ClientOutput::<LightningOutputV0> {
375            output: incoming_output,
376            amounts: Amounts::new_bitcoin(amount),
377        };
378        let client_output_sm = ClientOutputSM::<GatewayClientStateMachines> {
379            state_machines: Arc::new(move |out_point_range: OutPointRange| {
380                assert_eq!(out_point_range.count(), 1);
381                vec![
382                    GatewayClientStateMachines::Receive(IncomingStateMachine {
383                        common: IncomingSmCommon {
384                            operation_id,
385                            contract_id,
386                            payment_hash: htlc.payment_hash,
387                        },
388                        state: IncomingSmStates::FundingOffer(FundingOfferState {
389                            txid: out_point_range.txid(),
390                        }),
391                    }),
392                    GatewayClientStateMachines::Complete(GatewayCompleteStateMachine {
393                        common: GatewayCompleteCommon {
394                            operation_id,
395                            payment_hash: htlc.payment_hash,
396                            incoming_chan_id: htlc.incoming_chan_id,
397                            htlc_id: htlc.htlc_id,
398                        },
399                        state: GatewayCompleteStates::WaitForPreimage(WaitForPreimageState),
400                    }),
401                ]
402            }),
403        };
404        Ok((
405            operation_id,
406            amount,
407            client_output,
408            client_output_sm,
409            contract_id,
410        ))
411    }
412
413    async fn create_funding_incoming_contract_output_from_swap(
414        &self,
415        swap: SwapParameters,
416    ) -> Result<
417        (
418            OperationId,
419            ClientOutput<LightningOutputV0>,
420            ClientOutputSM<GatewayClientStateMachines>,
421        ),
422        IncomingSmError,
423    > {
424        let payment_hash = swap.payment_hash;
425        let operation_id = OperationId(payment_hash.to_byte_array());
426        let (incoming_output, amount, contract_id) = create_incoming_contract_output(
427            &self.module_api,
428            payment_hash,
429            swap.amount_msat,
430            &self.redeem_key,
431        )
432        .await?;
433
434        let client_output = ClientOutput::<LightningOutputV0> {
435            output: incoming_output,
436            amounts: Amounts::new_bitcoin(amount),
437        };
438        let client_output_sm = ClientOutputSM::<GatewayClientStateMachines> {
439            state_machines: Arc::new(move |out_point_range| {
440                assert_eq!(out_point_range.count(), 1);
441                vec![GatewayClientStateMachines::Receive(IncomingStateMachine {
442                    common: IncomingSmCommon {
443                        operation_id,
444                        contract_id,
445                        payment_hash,
446                    },
447                    state: IncomingSmStates::FundingOffer(FundingOfferState {
448                        txid: out_point_range.txid(),
449                    }),
450                })]
451            }),
452        };
453        Ok((operation_id, client_output, client_output_sm))
454    }
455
456    /// Registers the gateway with a federation and reports whether it
457    /// succeeded.
458    ///
459    /// Detailed errors remain in gateway logs; callers can retain the boolean
460    /// result without exposing federation internals.
461    pub async fn try_register_with_federation(
462        &self,
463        route_hints: Vec<RouteHint>,
464        time_to_live: Duration,
465        fees: RoutingFees,
466        lightning_context: LightningContext,
467        api: SafeUrl,
468        gateway_keypair: Keypair,
469    ) -> bool {
470        let registration_info = self.to_gateway_registration_info(
471            route_hints,
472            time_to_live,
473            fees,
474            lightning_context,
475            api,
476            gateway_keypair,
477        );
478        let gateway_id = registration_info.info.gateway_id;
479
480        let federation_id = self
481            .client_ctx
482            .get_config()
483            .await
484            .global
485            .calculate_federation_id();
486        match self.module_api.register_gateway(&registration_info).await {
487            Err(e) => {
488                warn!(
489                    e = %e.fmt_compact(),
490                    "Failed to register gateway {gateway_id} with federation {federation_id}"
491                );
492                false
493            }
494            _ => {
495                info!(
496                    "Successfully registered gateway {gateway_id} with federation {federation_id}"
497                );
498                true
499            }
500        }
501    }
502
503    /// Attempts to remove a gateway's registration from the federation.
504    ///
505    /// Each peer keeps its own list of registered gateways, so the gateway
506    /// signs every peer's removal challenge with the private key of its
507    /// gateway id. Removal is best effort and reports nothing: a peer that
508    /// fails or does not answer within a second is skipped, and one that
509    /// declines the removal is logged.
510    pub async fn remove_from_federation(&self, gateway_keypair: Keypair) {
511        let gateway_id = gateway_keypair.public_key();
512        let challenges = self
513            .module_api
514            .get_remove_gateway_challenge(gateway_id)
515            .await;
516
517        let fed_public_key = self.cfg.threshold_pub_key;
518        let signatures = challenges
519            .into_iter()
520            .filter_map(|(peer_id, challenge)| {
521                let msg = create_gateway_remove_message(fed_public_key, peer_id, challenge?);
522                let signature = gateway_keypair.sign_schnorr(msg);
523                Some((peer_id, signature))
524            })
525            .collect::<BTreeMap<_, _>>();
526
527        let remove_gateway_request = RemoveGatewayRequest {
528            gateway_id,
529            signatures,
530        };
531
532        self.module_api.remove_gateway(remove_gateway_request).await;
533    }
534
535    /// Attempt to fulfill an HTLC by buying its preimage from the federation.
536    ///
537    /// LND can replay a still-pending HTLC after interceptor reconnect or
538    /// gatewayd restart. Since the operation id is deterministic from the
539    /// payment hash, the replay must not re-fetch the consumed federation offer
540    /// or submit the same funding transaction again.
541    ///
542    /// We only short-circuit if a `GatewayCompleteStateMachine` is or was
543    /// handling the exact same LND circuit. Direct swaps with the same payment
544    /// hash and different circuits fall through to the normal failure/cancel
545    /// path. Exact-circuit replays bypass fresh-funding expiry validation so an
546    /// already-funded operation can still settle after reconnect or restart.
547    ///
548    /// `current_block_height` resolves to the Lightning backend's absolute best
549    /// Bitcoin block height. It is awaited only after replay detection, before
550    /// any fresh funding.
551    ///
552    /// # Errors
553    ///
554    /// Fails with [`HandleInterceptedHtlcError::BlockHeight`] if
555    /// `current_block_height` fails,
556    /// [`HandleInterceptedHtlcError::UnsafeExpiry`] if the HTLC expires too
557    /// soon, [`HandleInterceptedHtlcError::IncomingContract`]
558    /// if the federation's offer cannot be funded, and
559    /// [`HandleInterceptedHtlcError::Transaction`] if the funding transaction
560    /// cannot be submitted. A replay of a circuit already handled does not
561    /// fail.
562    pub async fn gateway_handle_intercepted_htlc(
563        &self,
564        htlc: Htlc,
565        current_block_height: impl Future<Output = Result<u32, LightningRpcError>>,
566    ) -> Result<OperationId, HandleInterceptedHtlcError> {
567        debug!("Handling intercepted HTLC {htlc:?}");
568
569        let operation_id = OperationId(htlc.payment_hash.to_byte_array());
570        let circuit_key = HtlcCircuitKey {
571            operation_id,
572            incoming_chan_id: htlc.incoming_chan_id,
573            htlc_id: htlc.htlc_id,
574        };
575
576        // Serialize same-circuit handling so the active-state replay scan and
577        // operation creation are atomic for LND stream-reconnect replays.
578        let _circuit_lock_guard = self
579            .intercepted_htlc_lock_pool
580            .async_lock(circuit_key)
581            .await;
582
583        // Check before the funding helper: the first handling consumes the
584        // federation offer. Match the full circuit key, not just `operation_id`.
585        let replay_of_active_circuit = self
586            .client_ctx
587            .get_own_operation_active_states(operation_id)
588            .await
589            .into_iter()
590            .any(|(state, _)| circuit_key.matches_state(&state));
591        if replay_of_active_circuit {
592            debug!(
593                ?operation_id,
594                incoming_chan_id = htlc.incoming_chan_id,
595                htlc_id = htlc.htlc_id,
596                "HTLC circuit already being handled by an active completion state machine, treating as in-flight (likely an LND stream-reconnect replay)"
597            );
598            return Ok(operation_id);
599        }
600        let replay_of_inactive_circuit = self
601            .client_ctx
602            .get_own_operation_inactive_states(operation_id)
603            .await
604            .into_iter()
605            .any(|(state, _)| circuit_key.matches_state(&state));
606        if replay_of_inactive_circuit {
607            debug!(
608                ?operation_id,
609                incoming_chan_id = htlc.incoming_chan_id,
610                htlc_id = htlc.htlc_id,
611                "HTLC circuit was already handled by a completion state machine, treating as idempotent replay"
612            );
613            return Ok(operation_id);
614        }
615
616        let current_block_height = current_block_height
617            .await
618            .map_err(HandleInterceptedHtlcError::BlockHeight)?;
619        htlc.ensure_safe_expiry(current_block_height)?;
620        let remaining_blocks = htlc.incoming_expiry.saturating_sub(current_block_height);
621        if remaining_blocks <= u32::from(LNV1_INCOMING_HTLC_ADVERTISED_EXPIRY_DELTA) {
622            // Tracks how much traffic still arrives via pre-upgrade invoices;
623            // enforcement can be raised to the advertised delta once this stops
624            // firing in the wild.
625            warn!(
626                payment_hash = %htlc.payment_hash,
627                remaining_blocks,
628                advertised_delta = LNV1_INCOMING_HTLC_ADVERTISED_EXPIRY_DELTA,
629                "Accepting LNv1 HTLC with less remaining expiry than newly created invoices advertise, likely paid to a pre-upgrade invoice"
630            );
631        }
632
633        let (op_id_from_funding, amount, client_output, client_output_sm, contract_id) = self
634            .create_funding_incoming_contract_output_from_htlc(htlc.clone())
635            .await?;
636        // Keep the direct derivation above in sync with the funding helper. Return
637        // an error instead of panicking so the caller can fail back the HTLC cleanly.
638        if op_id_from_funding != operation_id {
639            return Err(HandleInterceptedHtlcError::OperationIdMismatch {
640                expected: operation_id,
641                derived: op_id_from_funding,
642            });
643        }
644
645        let output = ClientOutput {
646            output: LightningOutput::V0(client_output.output),
647            amounts: Amounts::new_bitcoin(amount),
648        };
649
650        let tx = TransactionBuilder::new(Account::Primary).with_outputs(
651            self.client_ctx.make_client_outputs(ClientOutputBundle::new(
652                vec![output],
653                vec![client_output_sm],
654            )),
655        );
656        let operation_meta_gen = |_: OutPointRange| GatewayMeta::Receive;
657
658        // The receive policy admits a fresh payment only here, below the replay
659        // checks above: a circuit this gateway already funded must still be
660        // settled, or the gateway is out of pocket for a contract it paid for.
661        // The guard is held across the funding write, so a payment cannot slip
662        // in after disabling has returned.
663        let federation_id = self
664            .client_ctx
665            .get_config()
666            .await
667            .global
668            .calculate_federation_id();
669        let _policy_guard = self
670            .lightning_manager
671            .begin_fresh_receive(federation_id)
672            .await
673            .ok_or(HandleInterceptedHtlcError::ReceiveDisabled { federation_id })?;
674
675        self.client_ctx
676            .finalize_and_submit_transaction_with_events(
677                operation_id,
678                KIND.as_str(),
679                operation_meta_gen,
680                tx,
681                vec![self.client_ctx.make_event(IncomingPaymentStarted {
682                    contract_id,
683                    payment_hash: htlc.payment_hash,
684                    invoice_amount: htlc.incoming_amount_msat,
685                    contract_amount: amount,
686                    operation_id,
687                })],
688            )
689            .await?;
690        debug!(?operation_id, "Submitted transaction for HTLC {htlc:?}");
691        Ok(operation_id)
692    }
693
694    /// Attempt buying preimage from this federation in order to fulfill a pay
695    /// request in another federation served by this gateway. In direct swap
696    /// scenario, the gateway DOES NOT send payment over the lightning network
697    ///
698    /// The operation is keyed on the payment hash, so an existing one means the
699    /// incoming contract for this swap is already funded and only ever pays out
700    /// one preimage. A second call therefore has nothing to fund; it wants the
701    /// preimage the first call is buying, and gets it by being handed the
702    /// operation already in progress for
703    /// [`pay::GatewayPayWaitForSwapPreimage`] to follow. Reporting a failure
704    /// instead would cancel the outgoing contract that this swap is the other
705    /// half of, refunding the sender while the recipient still gets paid out of
706    /// the gateway's own funds.
707    ///
708    /// `allow_fresh_dispatch` is consulted only when no such operation exists:
709    /// callers pass `false` when a wall-clock gate such as invoice expiry
710    /// forbids starting a new swap, and receive `Ok(None)` to signal that
711    /// nothing was started.
712    ///
713    /// # Errors
714    ///
715    /// Fails with [`HandleDirectSwapError::IncomingContract`] if the
716    /// federation's offer cannot be funded,
717    /// [`HandleDirectSwapError::Transaction`] if the funding transaction
718    /// cannot be submitted, and [`HandleDirectSwapError::Database`] if it
719    /// cannot be recorded.
720    pub async fn gateway_handle_direct_swap(
721        &self,
722        swap_params: SwapParameters,
723        allow_fresh_dispatch: bool,
724    ) -> Result<Option<OperationId>, HandleDirectSwapError> {
725        debug!("Handling direct swap {swap_params:?}");
726
727        let payment_hash = swap_params.payment_hash;
728        let operation_id = OperationId(payment_hash.to_byte_array());
729
730        // Check before the funding helper: funding the incoming contract consumes
731        // the federation's offer, and the await-offer endpoint waits for one to
732        // appear rather than reporting that it is gone, so a re-entrant call gets
733        // no further than that helper's timeout.
734        if self.client_ctx.operation_exists(operation_id).await {
735            debug!(
736                operation_id = %operation_id.fmt_short(),
737                %payment_hash,
738                "Direct swap already in progress, returning the operation already funding it"
739            );
740
741            return Ok(Some(operation_id));
742        }
743
744        if !allow_fresh_dispatch {
745            return Ok(None);
746        }
747
748        let (op_id_from_funding, client_output, client_output_sm) = self
749            .create_funding_incoming_contract_output_from_swap(swap_params.clone())
750            .await?;
751        // Keep the direct derivation above in sync with the funding helper.
752        if op_id_from_funding != operation_id {
753            return Err(HandleDirectSwapError::OperationIdMismatch {
754                expected: operation_id,
755                derived: op_id_from_funding,
756            });
757        }
758
759        // A swap is how funds from another federation enter this one through
760        // the gateway, so it is admitted only while receives are on, and the
761        // guard holds that admission across the funding transaction below. A
762        // swap already funded resumes above regardless.
763        let federation_id = self
764            .client_ctx
765            .get_config()
766            .await
767            .global
768            .calculate_federation_id();
769        let _policy_guard = self
770            .lightning_manager
771            .begin_fresh_receive(federation_id)
772            .await
773            .ok_or(HandleDirectSwapError::ReceiveDisabled { federation_id })?;
774
775        self.client_ctx
776            .module_db()
777            .autocommit(
778                |dbtx, _| {
779                    let client_output = client_output.clone();
780                    let client_output_sm = client_output_sm.clone();
781                    Box::pin(async move {
782                        // The check above raced anyone who got here first; this one
783                        // shares a transaction with the write that would settle the
784                        // race, so exactly one of us funds the contract and the
785                        // other joins that operation.
786                        if self
787                            .client_ctx
788                            .get_operation_dbtx(dbtx, operation_id)
789                            .await
790                            .is_some()
791                        {
792                            debug!(
793                                operation_id = %operation_id.fmt_short(),
794                                %payment_hash,
795                                "Concurrent direct swap won the race, returning the operation already funding it"
796                            );
797
798                            return Ok(Some(operation_id));
799                        }
800
801                        let output = ClientOutput {
802                            output: LightningOutput::V0(client_output.output),
803                            amounts: client_output.amounts,
804                        };
805                        let tx = TransactionBuilder::new(Account::Primary).with_outputs(
806                            self.client_ctx.make_client_outputs(ClientOutputBundle::new(
807                                vec![output],
808                                vec![client_output_sm],
809                            )),
810                        );
811
812                        self.client_ctx
813                            .finalize_and_submit_transaction_dbtx(
814                                dbtx,
815                                operation_id,
816                                KIND.as_str(),
817                                |_: OutPointRange| GatewayMeta::Receive,
818                                tx,
819                            )
820                            .await?;
821
822                        debug!(
823                            ?operation_id,
824                            %payment_hash,
825                            "Submitted funding transaction for direct swap"
826                        );
827
828                        Ok::<_, HandleDirectSwapError>(Some(operation_id))
829                    })
830                },
831                Some(100),
832            )
833            .await
834            .map_err(HandleDirectSwapError::from)
835    }
836
837    /// Subscribe to updates when the gateway is handling an intercepted HTLC,
838    /// or direct swap between federations
839    ///
840    /// # Errors
841    ///
842    /// Fails with an [`OperationLookupError`] if no operation with this id
843    /// exists, or if another module started it.
844    pub async fn gateway_subscribe_ln_receive(
845        &self,
846        operation_id: OperationId,
847    ) -> Result<UpdateStreamOrOutcome<GatewayExtReceiveStates>, OperationLookupError> {
848        let operation = self.client_ctx.get_operation(operation_id).await?;
849        let mut stream = self.notifier.subscribe(operation_id).await;
850        let client_ctx = self.client_ctx.clone();
851
852        Ok(self.client_ctx.outcome_or_updates(&operation, operation_id, |state| match state {
853                GatewayExtReceiveStates::Funding => false,
854                GatewayExtReceiveStates::Preimage(_)
855                | GatewayExtReceiveStates::RefundSuccess { .. }
856                | GatewayExtReceiveStates::RefundError { .. }
857                | GatewayExtReceiveStates::FundingFailed { .. } => true,
858            }, move || {
859            stream! {
860
861                yield GatewayExtReceiveStates::Funding;
862
863                let state = loop {
864                    debug!("Getting next ln receive state for {}", operation_id.fmt_short());
865                    if let Some(GatewayClientStateMachines::Receive(state)) = stream.next().await {
866                        match state.state {
867                            IncomingSmStates::Preimage(preimage) =>{
868                                debug!(?operation_id, "Received preimage");
869                                break GatewayExtReceiveStates::Preimage(preimage)
870                            },
871                            IncomingSmStates::RefundSubmitted { out_points, error } => {
872                                debug!(?operation_id, "Refund submitted for {out_points:?} {error}");
873                                match client_ctx.await_primary_module_outputs(operation_id, out_points.clone()).await {
874                                    Ok(()) => {
875                                        debug!(?operation_id, "Refund success");
876                                        break GatewayExtReceiveStates::RefundSuccess { out_points, error }
877                                    },
878                                    Err(e) => {
879                                        warn!(?operation_id, "Got failure {e:?} while awaiting for refund outputs {out_points:?}");
880                                        break GatewayExtReceiveStates::RefundError{ error_message: e.fmt_compact().to_string(), error }
881                                    },
882                                }
883                            },
884                            IncomingSmStates::FundingFailed { error } => {
885                                warn!(?operation_id, "Funding failed: {error:?}");
886                                break GatewayExtReceiveStates::FundingFailed{ error }
887                            },
888                            other => {
889                                debug!("Got state {other:?} while awaiting for output of {}", operation_id.fmt_short());
890                            }
891                        }
892                    }
893                };
894                yield state;
895            }
896        }))
897    }
898
899    /// For the given `OperationId`, this function will wait until the Complete
900    /// state machine has finished or failed.
901    pub async fn await_completion(&self, operation_id: OperationId) {
902        let mut stream = self.notifier.subscribe(operation_id).await;
903        loop {
904            match stream.next().await {
905                Some(GatewayClientStateMachines::Complete(state)) => match state.state {
906                    GatewayCompleteStates::HtlcFinished => {
907                        info!(%state, "LNv1 completion state machine finished");
908                        return;
909                    }
910                    GatewayCompleteStates::Failure => {
911                        error!(%state, "LNv1 completion state machine failed");
912                        return;
913                    }
914                    _ => {
915                        info!(%state, "Waiting for LNv1 completion state machine");
916                        continue;
917                    }
918                },
919                Some(GatewayClientStateMachines::Receive(state)) => {
920                    info!(%state, "Waiting for LNv1 completion state machine");
921                    continue;
922                }
923                Some(state) => {
924                    warn!(%state, "Operation is not an LNv1 completion state machine");
925                    return;
926                }
927                None => return,
928            }
929        }
930    }
931
932    /// Pay lightning invoice on behalf of federation user
933    ///
934    /// A funded contract whose invoice hash belongs to another operation is
935    /// cancelled without attempting a payment. The hash claim is retained.
936    ///
937    /// # Errors
938    ///
939    /// Fails with [`GatewayPayInvoiceError::MissingInvoiceAmount`] if the
940    /// invoice has no amount, [`GatewayPayInvoiceError::PrunedInvoiceRejected`]
941    /// if the gateway cannot pay a pruned invoice,
942    /// [`GatewayPayInvoiceError::PaymentHashAlreadyClaimed`] if another
943    /// operation already claimed the invoice's payment hash and this request
944    /// has no matching funded contract to refund,
945    /// [`GatewayPayInvoiceError::ContractLookup`] if the contract cannot be
946    /// fetched for a refund,
947    /// [`GatewayPayInvoiceError::Unauthorized`] if a payment of this contract
948    /// is already under way and the request does not carry the
949    /// authentication it was started with,
950    /// [`GatewayPayInvoiceError::StateMachines`] if the payment cannot be
951    /// started, and [`GatewayPayInvoiceError::Database`] if it cannot be
952    /// recorded.
953    pub async fn gateway_pay_bolt11_invoice(
954        &self,
955        pay_invoice_payload: PayInvoicePayload,
956    ) -> Result<OperationId, GatewayPayInvoiceError> {
957        let payload = pay_invoice_payload.clone();
958
959        // `payment_data` is caller-supplied on the unauthenticated `/pay_invoice`
960        // route, so an amountless BOLT11 reaches us here. The state machine
961        // rejects it in `validate_outgoing_account`, but that runs only after
962        // this function has already recorded the invoice amount, so the amount
963        // has to be resolved before any of that work starts.
964        let invoice_amount = pay_invoice_payload
965            .payment_data
966            .amount()
967            .ok_or(GatewayPayInvoiceError::MissingInvoiceAmount)?;
968
969        self.lightning_manager
970            .verify_pruned_invoice(pay_invoice_payload.payment_data)
971            .await
972            .map_err(GatewayPayInvoiceError::PrunedInvoiceRejected)?;
973
974        // Only the first operation to claim a payment image may ever pay it out,
975        // across LNv1, LNv2 and all federations; see the LNv2 `send_payment`.
976        // The claim is taken before the operation is created, and a retry of the
977        // same contract finds its own claim.
978        let initial_state = if self
979            .lightning_manager
980            .claim_payment_image(
981                &fedimint_lnv2_common::contracts::PaymentImage::Hash(
982                    payload.payment_data.payment_hash(),
983                ),
984                OperationId(payload.contract_id.to_byte_array()),
985            )
986            .await
987        {
988            GatewayPayStates::PayInvoice(GatewayPayInvoice {
989                pay_invoice_payload: payload.clone(),
990            })
991        } else {
992            let account = self
993                .module_api
994                .fetch_contract(payload.contract_id)
995                .await
996                .map_err(GatewayPayInvoiceError::ContractLookup)?
997                .ok_or(GatewayPayInvoiceError::PaymentHashAlreadyClaimed)?;
998            let FundedContract::Outgoing(contract) = account.contract else {
999                return Err(GatewayPayInvoiceError::PaymentHashAlreadyClaimed);
1000            };
1001
1002            if account.amount == Amount::ZERO
1003                || contract.gateway_key != self.redeem_key.public_key()
1004                || contract.hash != payload.payment_data.payment_hash()
1005            {
1006                return Err(GatewayPayInvoiceError::PaymentHashAlreadyClaimed);
1007            }
1008            GatewayPayStates::CancelContract(Box::new(GatewayPayCancelContract::for_claimed_hash(
1009                OutgoingContractAccount {
1010                    amount: account.amount,
1011                    contract,
1012                },
1013            )))
1014        };
1015
1016        self.client_ctx.module_db()
1017            .autocommit(
1018                |dbtx, _| {
1019                    Box::pin(async {
1020                        let operation_id = OperationId(payload.contract_id.to_byte_array());
1021
1022                        // The operation id is the contract id, so an existing entry means we
1023                        // already accepted a request to pay this very contract. The state
1024                        // machine's own dedupe key covers the whole payload, so a caller who
1025                        // varies any field of it -- `preimage_auth`, say -- slips past that
1026                        // and would have us buy the preimage a second time, spending the
1027                        // gateway's funds twice against a contract that only pays out once.
1028                        // Hand back the operation already under way instead.
1029                        if let Some(entry) =
1030                            self.client_ctx.get_operation_dbtx(dbtx, operation_id).await
1031                        {
1032                            // This operation id yields the preimage, so only the
1033                            // caller that started the payment may join it. The
1034                            // state machine's own check comes too late for a
1035                            // request that never reaches one, and it is keyed on
1036                            // `payment_data`, which the caller supplies
1037                            // independently of `contract_id` -- so it would answer
1038                            // for the wrong payment here.
1039                            if !matches!(
1040                                entry.try_meta::<GatewayMeta>(),
1041                                Ok(GatewayMeta::Pay { preimage_auth })
1042                                    if PreimageAuth::new(preimage_auth)
1043                                        .verifies(payload.preimage_auth)
1044                            ) {
1045                                return Err(GatewayPayInvoiceError::Unauthorized {
1046                                    contract_id: payload.contract_id,
1047                                });
1048                            }
1049
1050                            debug!(
1051                                operation_id = %operation_id.fmt_short(),
1052                                contract_id = %payload.contract_id,
1053                                "Duplicate request to pay an outgoing contract, returning the operation already in progress"
1054                            );
1055
1056                            return Ok(operation_id);
1057                        }
1058
1059                        self.client_ctx.log_event(dbtx, OutgoingPaymentStarted {
1060                            contract_id: payload.contract_id,
1061                            invoice_amount,
1062                            operation_id,
1063                        }).await;
1064
1065                        let state_machines =
1066                            vec![GatewayClientStateMachines::Pay(GatewayPayStateMachine {
1067                                common: GatewayPayCommon { operation_id },
1068                                state: initial_state.clone(),
1069                            })];
1070
1071                        let dyn_states = state_machines
1072                            .into_iter()
1073                            .map(|s| self.client_ctx.make_dyn(s))
1074                            .collect();
1075
1076                            match self.client_ctx.add_state_machines_dbtx(dbtx, dyn_states).await {
1077                                Ok(()) => {
1078                                    self.client_ctx
1079                                        .add_operation_log_entry_dbtx(dbtx, operation_id, Account::Primary, KIND.as_str(), GatewayMeta::Pay {
1080                                                preimage_auth: payload.preimage_auth,
1081                                            })
1082                                        .await;
1083                                }
1084                                Err(AddStateMachinesError::StateAlreadyExists) => {
1085                                    info!("State machine for operation {} already exists, will not add a new one", operation_id.fmt_short());
1086                                }
1087                                Err(other) => {
1088                                    return Err(GatewayPayInvoiceError::StateMachines(other));
1089                                }
1090                            }
1091                            Ok::<_, GatewayPayInvoiceError>(operation_id)
1092                    })
1093                },
1094                Some(100),
1095            )
1096            .await
1097            .map_err(GatewayPayInvoiceError::from)
1098    }
1099
1100    /// Subscribe to updates of a payment started with
1101    /// [`Self::gateway_pay_bolt11_invoice`].
1102    ///
1103    /// # Errors
1104    ///
1105    /// Fails with an [`OperationLookupError`] if no operation with this id
1106    /// exists, or if another module started it.
1107    pub async fn gateway_subscribe_ln_pay(
1108        &self,
1109        operation_id: OperationId,
1110    ) -> Result<UpdateStreamOrOutcome<GatewayExtPayStates>, OperationLookupError> {
1111        let mut stream = self.notifier.subscribe(operation_id).await;
1112        let operation = self.client_ctx.get_operation(operation_id).await?;
1113        let client_ctx = self.client_ctx.clone();
1114
1115        Ok(self.client_ctx.outcome_or_updates(&operation, operation_id, |state| match state {
1116                GatewayExtPayStates::Created | GatewayExtPayStates::Preimage { .. } => false,
1117                GatewayExtPayStates::Success { .. }
1118                | GatewayExtPayStates::Canceled { .. }
1119                | GatewayExtPayStates::Fail { .. }
1120                | GatewayExtPayStates::OfferDoesNotExist { .. } => true,
1121            }, move || {
1122            stream! {
1123                yield GatewayExtPayStates::Created;
1124
1125                loop {
1126                    debug!("Getting next ln pay state for {}", operation_id.fmt_short());
1127                    match stream.next().await { Some(GatewayClientStateMachines::Pay(state)) => {
1128                        match state.state {
1129                            GatewayPayStates::Preimage(out_points, preimage) => {
1130                                yield GatewayExtPayStates::Preimage{ preimage: preimage.clone() };
1131
1132                                match client_ctx.await_primary_module_outputs(operation_id, out_points.clone()).await {
1133                                    Ok(()) => {
1134                                        debug!(?operation_id, "Success");
1135                                        yield GatewayExtPayStates::Success{ preimage: preimage.clone(), out_points };
1136                                        return;
1137
1138                                    }
1139                                    Err(e) => {
1140                                        warn!(?operation_id, "Got failure {e:?} while awaiting for outputs {out_points:?}");
1141                                        // TODO: yield something here?
1142                                    }
1143                                }
1144                            }
1145                            GatewayPayStates::Canceled { txid, contract_id, error } => {
1146                                debug!(?operation_id, "Trying to cancel contract {contract_id:?} due to {error:?}");
1147                                match client_ctx.transaction_updates(operation_id).await.await_tx_accepted(txid).await {
1148                                    Ok(()) => {
1149                                        debug!(?operation_id, "Canceled contract {contract_id:?} due to {error:?}");
1150                                        yield GatewayExtPayStates::Canceled{ error };
1151                                        return;
1152                                    }
1153                                    Err(e) => {
1154                                        warn!(?operation_id, "Got failure {e:?} while awaiting for transaction {txid} to be accepted for");
1155                                        yield GatewayExtPayStates::Fail { error, error_message: format!("Refund transaction {txid} was not accepted by the federation. OperationId: {} Error: {e:?}", operation_id.fmt_short()) };
1156                                    }
1157                                }
1158                            }
1159                            GatewayPayStates::OfferDoesNotExist(contract_id) => {
1160                                warn!("Yielding OfferDoesNotExist state for {} and contract {contract_id}", operation_id.fmt_short());
1161                                yield GatewayExtPayStates::OfferDoesNotExist { contract_id };
1162                            }
1163                            GatewayPayStates::Failed{ error, error_message } => {
1164                                warn!("Yielding Fail state for {} due to {error:?} {error_message:?}", operation_id.fmt_short());
1165                                yield GatewayExtPayStates::Fail{ error, error_message };
1166                            },
1167                            GatewayPayStates::PayInvoice(_) => {
1168                                debug!("Got initial state PayInvoice while awaiting for output of {}", operation_id.fmt_short());
1169                            }
1170                            other => {
1171                                info!("Got state {other:?} while awaiting for output of {}", operation_id.fmt_short());
1172                            }
1173                        }
1174                    } _ => {
1175                        warn!("Got None while getting next ln pay state for {}", operation_id.fmt_short());
1176                    }}
1177                }
1178            }
1179        }))
1180    }
1181}
1182
1183#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
1184struct HtlcCircuitKey {
1185    operation_id: OperationId,
1186    incoming_chan_id: u64,
1187    htlc_id: u64,
1188}
1189
1190impl HtlcCircuitKey {
1191    fn matches_state(self, state: &GatewayClientStateMachines) -> bool {
1192        matches!(
1193            state,
1194            GatewayClientStateMachines::Complete(sm)
1195                if sm.common.operation_id == self.operation_id
1196                    && sm.common.incoming_chan_id == self.incoming_chan_id
1197                    && sm.common.htlc_id == self.htlc_id
1198        )
1199    }
1200}
1201
1202#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
1203pub enum GatewayClientStateMachines {
1204    Pay(GatewayPayStateMachine),
1205    Receive(IncomingStateMachine),
1206    Complete(GatewayCompleteStateMachine),
1207}
1208
1209impl fmt::Display for GatewayClientStateMachines {
1210    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1211        match self {
1212            GatewayClientStateMachines::Pay(pay) => {
1213                write!(f, "{pay}")
1214            }
1215            GatewayClientStateMachines::Receive(receive) => {
1216                write!(f, "{receive}")
1217            }
1218            GatewayClientStateMachines::Complete(complete) => {
1219                write!(f, "{complete}")
1220            }
1221        }
1222    }
1223}
1224
1225impl IntoDynInstance for GatewayClientStateMachines {
1226    type DynType = DynState;
1227
1228    fn into_dyn(self, instance_id: ModuleInstanceId) -> Self::DynType {
1229        DynState::from_typed(instance_id, self)
1230    }
1231}
1232
1233impl State for GatewayClientStateMachines {
1234    type ModuleContext = GatewayClientContext;
1235
1236    fn transitions(
1237        &self,
1238        context: &Self::ModuleContext,
1239        global_context: &DynGlobalClientContext,
1240    ) -> Vec<StateTransition<Self>> {
1241        match self {
1242            GatewayClientStateMachines::Pay(pay_state) => {
1243                sm_enum_variant_translation!(
1244                    pay_state.transitions(context, global_context),
1245                    GatewayClientStateMachines::Pay
1246                )
1247            }
1248            GatewayClientStateMachines::Receive(receive_state) => {
1249                sm_enum_variant_translation!(
1250                    receive_state.transitions(&context.into(), global_context),
1251                    GatewayClientStateMachines::Receive
1252                )
1253            }
1254            GatewayClientStateMachines::Complete(complete_state) => {
1255                sm_enum_variant_translation!(
1256                    complete_state.transitions(context, global_context),
1257                    GatewayClientStateMachines::Complete
1258                )
1259            }
1260        }
1261    }
1262
1263    fn operation_id(&self) -> fedimint_core::core::OperationId {
1264        match self {
1265            GatewayClientStateMachines::Pay(pay_state) => pay_state.operation_id(),
1266            GatewayClientStateMachines::Receive(receive_state) => receive_state.operation_id(),
1267            GatewayClientStateMachines::Complete(complete_state) => complete_state.operation_id(),
1268        }
1269    }
1270}
1271
1272#[derive(Debug, Clone, Eq, PartialEq)]
1273pub struct Htlc {
1274    /// The HTLC payment hash.
1275    pub payment_hash: sha256::Hash,
1276    /// The incoming HTLC amount in millisatoshi.
1277    pub incoming_amount_msat: Amount,
1278    /// The outgoing HTLC amount in millisatoshi
1279    pub outgoing_amount_msat: Amount,
1280    /// Absolute Bitcoin block height at which the incoming HTLC expires.
1281    ///
1282    /// This uses the same coordinate system as the Lightning backend's current
1283    /// best block height.
1284    pub incoming_expiry: u32,
1285    /// The short channel id of the HTLC.
1286    pub short_channel_id: Option<u64>,
1287    /// The id of the incoming channel
1288    pub incoming_chan_id: u64,
1289    /// The index of the incoming htlc in the incoming channel
1290    pub htlc_id: u64,
1291}
1292
1293/// An intercepted LNv1 HTLC does not leave enough time for safe settlement.
1294#[derive(Debug, Error, Clone, Eq, PartialEq)]
1295#[error(
1296    "incoming HTLC expiry is unsafe: expiry {incoming_expiry}, current height {current_block_height}, required remaining blocks greater than {expiry_safety_margin}"
1297)]
1298pub struct UnsafeHtlcExpiry {
1299    /// Absolute Bitcoin block height at which the HTLC expires.
1300    pub incoming_expiry: u32,
1301    /// Lightning backend's current best Bitcoin block height.
1302    pub current_block_height: u32,
1303    /// Reserved settlement and on-chain safety margin in blocks.
1304    pub expiry_safety_margin: u32,
1305}
1306
1307impl Htlc {
1308    /// Rejects an HTLC unless its remaining lifetime exceeds the LNv1 safety
1309    /// margin.
1310    pub fn ensure_safe_expiry(&self, current_block_height: u32) -> Result<(), UnsafeHtlcExpiry> {
1311        let remaining_blocks = self.incoming_expiry.saturating_sub(current_block_height);
1312        if LNV1_HTLC_EXPIRY_SAFETY_MARGIN < remaining_blocks {
1313            return Ok(());
1314        }
1315
1316        Err(UnsafeHtlcExpiry {
1317            incoming_expiry: self.incoming_expiry,
1318            current_block_height,
1319            expiry_safety_margin: LNV1_HTLC_EXPIRY_SAFETY_MARGIN,
1320        })
1321    }
1322}
1323
1324impl From<InterceptPaymentRequest> for Htlc {
1325    fn from(s: InterceptPaymentRequest) -> Self {
1326        Self {
1327            payment_hash: s.payment_hash,
1328            // Keep the two amounts distinct: `incoming_amount_msat` is the real
1329            // value locked in the HTLC, while `amount_msat` is the sender-written
1330            // onion forward amount. Collapsing them lets a sender forge the
1331            // amount the gateway funds against.
1332            incoming_amount_msat: Amount::from_msats(s.incoming_amount_msat),
1333            outgoing_amount_msat: Amount::from_msats(s.amount_msat),
1334            incoming_expiry: s.expiry,
1335            short_channel_id: s.short_channel_id,
1336            incoming_chan_id: s.incoming_chan_id,
1337            htlc_id: s.htlc_id,
1338        }
1339    }
1340}
1341
1342#[derive(Debug, Clone)]
1343pub struct SwapParameters {
1344    pub payment_hash: sha256::Hash,
1345    pub amount_msat: Amount,
1346}
1347
1348impl TryFrom<PaymentData> for SwapParameters {
1349    type Error = MissingInvoiceAmountError;
1350
1351    fn try_from(s: PaymentData) -> Result<Self, Self::Error> {
1352        let payment_hash = s.payment_hash();
1353        let amount_msat = s.amount().ok_or(MissingInvoiceAmountError)?;
1354        Ok(Self {
1355            payment_hash,
1356            amount_msat,
1357        })
1358    }
1359}
1360
1361/// An interface between module implementation and the general `Gateway`
1362///
1363/// To abstract away and decouple the core gateway from the modules, the
1364/// interface between them is expressed as a trait. The gateway handles
1365/// operations that require Lightning node access or database access.
1366#[async_trait]
1367pub trait IGatewayClientV1: Debug + Send + Sync {
1368    /// Verifies that the supplied `preimage_auth` is the same as the
1369    /// `preimage_auth` that initiated the payment.
1370    ///
1371    /// If it is not, then this will return an error because this client is not
1372    /// authorized to receive the preimage.
1373    async fn verify_preimage_authentication(
1374        &self,
1375        payment_hash: sha256::Hash,
1376        preimage_auth: sha256::Hash,
1377        contract: OutgoingContractAccount,
1378    ) -> Result<(), OutgoingPaymentError>;
1379
1380    /// Verify that the lightning node supports private payments if a pruned
1381    /// invoice is supplied.
1382    ///
1383    /// # Errors
1384    ///
1385    /// Fails with a [`GatewayClientV1Error`] if the invoice is pruned and the
1386    /// gateway cannot pay it.
1387    async fn verify_pruned_invoice(
1388        &self,
1389        payment_data: PaymentData,
1390    ) -> Result<(), GatewayClientV1Error>;
1391
1392    /// Retrieves the federation's routing fees from the federation's config.
1393    async fn get_routing_fees(&self, federation_id: FederationId) -> Option<RoutingFees>;
1394
1395    /// Admits a fresh incoming payment for the clients of `federation_id` when
1396    /// the operator's receive policy allows one, or answers `None` when
1397    /// receives are disabled.
1398    ///
1399    /// The returned guard must be held until the funding operation exists.
1400    /// That is what makes disabling atomic: a policy change waits for the
1401    /// guards outstanding when it runs, so a payment admitted here always
1402    /// funds, and none is admitted once the change has returned.
1403    async fn begin_fresh_receive(
1404        &self,
1405        federation_id: FederationId,
1406    ) -> Option<fedimint_gateway_common::PaymentPolicyGuard>;
1407
1408    /// Retrieve a client given a federation ID, used for swapping ecash between
1409    /// federations.
1410    async fn get_client(&self, federation_id: &FederationId) -> Option<Spanned<ClientHandleArc>>;
1411
1412    // Retrieve a client given an invoice.
1413    //
1414    // Checks if the invoice route hint last hop has source node id matching this
1415    // gateways node pubkey and if the short channel id matches one assigned by
1416    // this gateway to a connected federation. In this case, the gateway can
1417    // avoid paying the invoice over the lightning network and instead perform a
1418    // direct swap between the two federations.
1419    async fn get_client_for_invoice(
1420        &self,
1421        payment_data: PaymentData,
1422    ) -> Option<Spanned<ClientHandleArc>>;
1423
1424    /// Pay a Lightning invoice using the gateway's lightning node.
1425    async fn pay(
1426        &self,
1427        payment_data: PaymentData,
1428        max_delay: u64,
1429        max_fee: Amount,
1430    ) -> Result<PayInvoiceResponse, LightningRpcError>;
1431
1432    /// Returns whether the gateway's Lightning node has any record of an
1433    /// outbound payment for `payment_hash`, whatever its state.
1434    ///
1435    /// The pay state machine consults this when it resumes after a restart:
1436    /// a payment the node already knows was dispatched before the crash and
1437    /// must be resolved through [`IGatewayClientV1::pay`]'s idempotent resume
1438    /// path rather than cancelled by pre-dispatch checks. A wrong `false`
1439    /// cancels a contract whose payment may still settle, so implementations
1440    /// must absorb transient node failures and only answer once the node's
1441    /// payment store could actually be consulted.
1442    async fn outbound_payment_exists(&self, payment_hash: sha256::Hash) -> bool;
1443
1444    /// Uses the gateway's lightning node to complete (settle or cancel) a
1445    /// previously intercepted HTLC.
1446    ///
1447    /// By the time the gateway settles the upstream HTLC it has already funded
1448    /// the incoming contract, so a transient failure here must not strand it
1449    /// out of pocket. Implementations must absorb and retry every transient
1450    /// node or connectivity failure, returning `Err` only when Lightning has
1451    /// reached a permanent state that makes the requested outcome impossible.
1452    /// The future may block while retrying and must remain cancellation-safe.
1453    /// The completion state machine persists any returned error as a terminal
1454    /// failure.
1455    async fn complete_htlc(
1456        &self,
1457        htlc_response: InterceptPaymentResponse,
1458    ) -> Result<(), LightningRpcError>;
1459
1460    /// Check if the gateway satisfy the LNv1 payment by funding an LNv2
1461    /// `IncomingContract`
1462    ///
1463    /// # Errors
1464    ///
1465    /// Fails with a [`GatewayClientV1Error`] if the gateway holds no LNv2
1466    /// incoming contract it can use for this payment. The pay state machine
1467    /// treats a failure like `None` and pays the invoice some other way.
1468    async fn is_lnv2_direct_swap(
1469        &self,
1470        payment_hash: sha256::Hash,
1471        amount: Amount,
1472    ) -> Result<
1473        Option<(
1474            fedimint_lnv2_common::contracts::IncomingContract,
1475            ClientHandleArc,
1476        )>,
1477        GatewayClientV1Error,
1478    >;
1479
1480    /// Claims the payment image for `operation_id` in the claim table shared
1481    /// with LNv2, returning `false` if another operation already claimed it.
1482    async fn claim_payment_image(
1483        &self,
1484        payment_image: &fedimint_lnv2_common::contracts::PaymentImage,
1485        operation_id: OperationId,
1486    ) -> bool;
1487}