Skip to main content

fedimint_gwv2_client/
lib.rs

1mod api;
2mod complete_sm;
3pub mod events;
4mod receive_sm;
5mod send_sm;
6
7use std::collections::BTreeMap;
8use std::fmt;
9use std::fmt::Debug;
10use std::sync::Arc;
11
12use anyhow::{anyhow, ensure};
13use async_trait::async_trait;
14use bitcoin::hashes::sha256;
15use bitcoin::secp256k1::Message;
16use events::{IncomingPaymentStarted, OutgoingPaymentStarted};
17use fedimint_api_client::api::DynModuleApi;
18use fedimint_client::ClientHandleArc;
19use fedimint_client_module::module::init::{ClientModuleInit, ClientModuleInitArgs};
20use fedimint_client_module::module::recovery::NoModuleBackup;
21use fedimint_client_module::module::{ClientContext, ClientModule, IClientModule, OutPointRange};
22use fedimint_client_module::sm::{Context, DynState, ModuleNotifier, State, StateTransition};
23use fedimint_client_module::transaction::{
24    ClientOutput, ClientOutputBundle, ClientOutputSM, TransactionBuilder,
25};
26use fedimint_client_module::{DynGlobalClientContext, sm_enum_variant_translation};
27use fedimint_core::config::FederationId;
28use fedimint_core::core::{Decoder, IntoDynInstance, ModuleInstanceId, ModuleKind, OperationId};
29use fedimint_core::db::DatabaseTransaction;
30use fedimint_core::encoding::{Decodable, Encodable};
31use fedimint_core::module::{
32    Amounts, ApiVersion, CommonModuleInit, ModuleCommon, ModuleInit, MultiApiVersion,
33};
34use fedimint_core::secp256k1::Keypair;
35use fedimint_core::time::now;
36use fedimint_core::util::Spanned;
37use fedimint_core::{Amount, PeerId, apply, async_trait_maybe_send, secp256k1};
38use fedimint_lightning::{InterceptPaymentResponse, LightningRpcError};
39use fedimint_lnv2_common::config::LightningClientConfig;
40use fedimint_lnv2_common::contracts::{IncomingContract, PaymentImage};
41use fedimint_lnv2_common::gateway_api::SendPaymentPayload;
42use fedimint_lnv2_common::{
43    LightningCommonInit, LightningInvoice, LightningModuleTypes, LightningOutput, LightningOutputV0,
44};
45use futures::StreamExt;
46use lightning_invoice::Bolt11Invoice;
47use receive_sm::{ReceiveSMState, ReceiveStateMachine};
48use secp256k1::schnorr::Signature;
49use send_sm::{SendSMState, SendStateMachine};
50use serde::{Deserialize, Serialize};
51use tpe::{AggregatePublicKey, PublicKeyShare};
52use tracing::{info, warn};
53
54use crate::api::GatewayFederationApi;
55pub use crate::complete_sm::IncomingCircuitKey;
56use crate::complete_sm::{
57    CircuitCompleteSMCommon, CircuitCompleteStateMachine, CompleteSMState, CompleteStateMachine,
58};
59use crate::receive_sm::ReceiveSMCommon;
60use crate::send_sm::SendSMCommon;
61
62/// LNv2 CLTV Delta in blocks
63pub const EXPIRATION_DELTA_MINIMUM_V2: u64 = 144;
64
65fn incoming_circuit_operation_id(
66    receive_operation_id: OperationId,
67    circuit: IncomingCircuitKey,
68) -> OperationId {
69    OperationId::from_encodable(&(
70        "gateway-lnv2-incoming-circuit",
71        receive_operation_id,
72        circuit,
73    ))
74}
75
76fn is_legacy_completion_for_circuit(
77    state: &GatewayClientStateMachinesV2,
78    circuit: IncomingCircuitKey,
79) -> bool {
80    let IncomingCircuitKey {
81        incoming_chan_id,
82        htlc_id,
83    } = circuit;
84    matches!(
85        state,
86        GatewayClientStateMachinesV2::Complete(CompleteStateMachine {
87            common,
88            ..
89        }) if common.incoming_chan_id == incoming_chan_id && common.htlc_id == htlc_id
90    )
91}
92
93fn legacy_completion_in_states(
94    active: &[GatewayClientStateMachinesV2],
95    inactive: &[GatewayClientStateMachinesV2],
96    circuit: IncomingCircuitKey,
97) -> bool {
98    active
99        .iter()
100        .chain(inactive)
101        .any(|state| is_legacy_completion_for_circuit(state, circuit))
102}
103
104#[derive(Debug, Clone, Copy, Eq, PartialEq)]
105enum IncomingRelayPlan {
106    Replay,
107    AddCompletion,
108    CreateReceiveAndCompletion,
109}
110
111fn incoming_relay_plan(
112    receive_exists: bool,
113    completion_exists: bool,
114    legacy_completion_exists: bool,
115) -> IncomingRelayPlan {
116    if completion_exists || legacy_completion_exists {
117        IncomingRelayPlan::Replay
118    } else if receive_exists {
119        IncomingRelayPlan::AddCompletion
120    } else {
121        IncomingRelayPlan::CreateReceiveAndCompletion
122    }
123}
124
125fn operation_creation_failed_permanently(
126    creation_failed: bool,
127    operation_exists_after_failure: bool,
128) -> bool {
129    creation_failed && !operation_exists_after_failure
130}
131
132/// Identifies the role of an LNv2 gateway operation.
133#[derive(Debug, Clone, Serialize, Deserialize)]
134#[serde(untagged)]
135pub enum GatewayOperationMetaV2 {
136    /// Metadata written before operation roles were distinguished.
137    Legacy(()),
138    /// Metadata written for a role-specific operation.
139    Role {
140        /// Role used when recovering active operations.
141        role: GatewayOperationRoleV2,
142    },
143}
144
145/// Role of an LNv2 gateway operation.
146#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
147#[serde(rename_all = "snake_case")]
148pub enum GatewayOperationRoleV2 {
149    /// An outgoing payment operation.
150    Send,
151    /// A federation receive operation.
152    Receive,
153    /// An incoming Lightning circuit completion operation.
154    CircuitCompletion,
155}
156
157impl GatewayOperationMetaV2 {
158    /// Constructs metadata for `role`.
159    pub fn role(role: GatewayOperationRoleV2) -> Self {
160        Self::Role { role }
161    }
162
163    /// Returns whether shutdown must await Lightning circuit completion.
164    pub fn waits_for_completion(&self) -> bool {
165        matches!(
166            self,
167            Self::Legacy(())
168                | Self::Role {
169                    role: GatewayOperationRoleV2::CircuitCompletion
170                }
171        )
172    }
173}
174
175#[derive(Debug, Clone)]
176pub struct GatewayClientInitV2 {
177    pub gateway: Arc<dyn IGatewayClientV2>,
178}
179
180impl ModuleInit for GatewayClientInitV2 {
181    type Common = LightningCommonInit;
182
183    async fn dump_database(
184        &self,
185        _dbtx: &mut DatabaseTransaction<'_>,
186        _prefix_names: Vec<String>,
187    ) -> Box<dyn Iterator<Item = (String, Box<dyn erased_serde::Serialize + Send>)> + '_> {
188        Box::new(vec![].into_iter())
189    }
190}
191
192#[apply(async_trait_maybe_send!)]
193impl ClientModuleInit for GatewayClientInitV2 {
194    type Module = GatewayClientModuleV2;
195
196    fn supported_api_versions(&self) -> MultiApiVersion {
197        MultiApiVersion::try_from_iter([ApiVersion { major: 0, minor: 0 }])
198            .expect("no version conflicts")
199    }
200
201    async fn init(&self, args: &ClientModuleInitArgs<Self>) -> anyhow::Result<Self::Module> {
202        Ok(GatewayClientModuleV2 {
203            federation_id: *args.federation_id(),
204            cfg: args.cfg().clone(),
205            notifier: args.notifier().clone(),
206            client_ctx: args.context(),
207            module_api: args.module_api().clone(),
208            keypair: args
209                .module_root_secret()
210                .clone()
211                .to_secp_key(fedimint_core::secp256k1::SECP256K1),
212            gateway: self.gateway.clone(),
213        })
214    }
215}
216
217#[derive(Debug, Clone)]
218pub struct GatewayClientModuleV2 {
219    pub federation_id: FederationId,
220    pub cfg: LightningClientConfig,
221    pub notifier: ModuleNotifier<GatewayClientStateMachinesV2>,
222    pub client_ctx: ClientContext<Self>,
223    pub module_api: DynModuleApi,
224    pub keypair: Keypair,
225    pub gateway: Arc<dyn IGatewayClientV2>,
226}
227
228#[derive(Debug, Clone)]
229pub struct GatewayClientContextV2 {
230    pub module: GatewayClientModuleV2,
231    pub decoder: Decoder,
232    pub tpe_agg_pk: AggregatePublicKey,
233    pub tpe_pks: BTreeMap<PeerId, PublicKeyShare>,
234    pub gateway: Arc<dyn IGatewayClientV2>,
235}
236
237impl Context for GatewayClientContextV2 {
238    const KIND: Option<ModuleKind> = Some(fedimint_lnv2_common::KIND);
239}
240
241impl ClientModule for GatewayClientModuleV2 {
242    type Init = GatewayClientInitV2;
243    type Common = LightningModuleTypes;
244    type Backup = NoModuleBackup;
245    type ModuleStateMachineContext = GatewayClientContextV2;
246    type States = GatewayClientStateMachinesV2;
247
248    fn context(&self) -> Self::ModuleStateMachineContext {
249        GatewayClientContextV2 {
250            module: self.clone(),
251            decoder: self.decoder(),
252            tpe_agg_pk: self.cfg.tpe_agg_pk,
253            tpe_pks: self.cfg.tpe_pks.clone(),
254            gateway: self.gateway.clone(),
255        }
256    }
257    fn input_fee(
258        &self,
259        amount: &Amounts,
260        _input: &<Self::Common as ModuleCommon>::Input,
261    ) -> Option<Amounts> {
262        Some(Amounts::new_bitcoin(
263            self.cfg.fee_consensus.fee(amount.expect_only_bitcoin()),
264        ))
265    }
266
267    fn output_fee(
268        &self,
269        _amount: &Amounts,
270        output: &<Self::Common as ModuleCommon>::Output,
271    ) -> Option<Amounts> {
272        let amount = match output.ensure_v0_ref().ok()? {
273            LightningOutputV0::Outgoing(contract) => contract.amount,
274            LightningOutputV0::Incoming(contract) => contract.commitment.amount,
275        };
276
277        Some(Amounts::new_bitcoin(self.cfg.fee_consensus.fee(amount)))
278    }
279}
280
281#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
282pub enum GatewayClientStateMachinesV2 {
283    Send(SendStateMachine),
284    Receive(ReceiveStateMachine),
285    /// Legacy completion state retained to decode and resume combined receive
286    /// operations created by older clients.
287    Complete(CompleteStateMachine),
288    /// Completes one incoming circuit independently of other circuits carrying
289    /// the same payment hash and amount.
290    CircuitComplete(CircuitCompleteStateMachine),
291}
292
293impl fmt::Display for GatewayClientStateMachinesV2 {
294    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
295        match self {
296            GatewayClientStateMachinesV2::Send(send) => {
297                write!(f, "{send}")
298            }
299            GatewayClientStateMachinesV2::Receive(receive) => {
300                write!(f, "{receive}")
301            }
302            GatewayClientStateMachinesV2::Complete(complete) => {
303                write!(f, "{complete}")
304            }
305            GatewayClientStateMachinesV2::CircuitComplete(complete) => {
306                write!(f, "{complete}")
307            }
308        }
309    }
310}
311
312impl IntoDynInstance for GatewayClientStateMachinesV2 {
313    type DynType = DynState;
314
315    fn into_dyn(self, instance_id: ModuleInstanceId) -> Self::DynType {
316        DynState::from_typed(instance_id, self)
317    }
318}
319
320impl State for GatewayClientStateMachinesV2 {
321    type ModuleContext = GatewayClientContextV2;
322
323    fn transitions(
324        &self,
325        context: &Self::ModuleContext,
326        global_context: &DynGlobalClientContext,
327    ) -> Vec<StateTransition<Self>> {
328        match self {
329            GatewayClientStateMachinesV2::Send(state) => {
330                sm_enum_variant_translation!(
331                    state.transitions(context, global_context),
332                    GatewayClientStateMachinesV2::Send
333                )
334            }
335            GatewayClientStateMachinesV2::Receive(state) => {
336                sm_enum_variant_translation!(
337                    state.transitions(context, global_context),
338                    GatewayClientStateMachinesV2::Receive
339                )
340            }
341            GatewayClientStateMachinesV2::Complete(state) => {
342                sm_enum_variant_translation!(
343                    state.transitions(context, global_context),
344                    GatewayClientStateMachinesV2::Complete
345                )
346            }
347            GatewayClientStateMachinesV2::CircuitComplete(state) => {
348                sm_enum_variant_translation!(
349                    state.transitions(context, global_context),
350                    GatewayClientStateMachinesV2::CircuitComplete
351                )
352            }
353        }
354    }
355
356    fn operation_id(&self) -> OperationId {
357        match self {
358            GatewayClientStateMachinesV2::Send(state) => state.operation_id(),
359            GatewayClientStateMachinesV2::Receive(state) => state.operation_id(),
360            GatewayClientStateMachinesV2::Complete(state) => state.operation_id(),
361            GatewayClientStateMachinesV2::CircuitComplete(state) => state.operation_id(),
362        }
363    }
364}
365
366#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize, Decodable, Encodable)]
367pub enum FinalReceiveState {
368    Rejected,
369    Success([u8; 32]),
370    Refunded,
371    Failure,
372}
373
374impl GatewayClientModuleV2 {
375    pub async fn send_payment(
376        &self,
377        payload: SendPaymentPayload,
378    ) -> anyhow::Result<Result<[u8; 32], Signature>> {
379        let operation_start = now();
380
381        // The operation id is equal to the contract id which also doubles as the
382        // message signed by the gateway via the forfeit signature to forfeit
383        // the gateways claim to a contract in case of cancellation. We only create a
384        // forfeit signature after we have started the send state machine to
385        // prevent replay attacks with a previously cancelled outgoing contract
386        let operation_id = OperationId::from_encodable(&payload.contract.clone());
387
388        if self.client_ctx.operation_exists(operation_id).await {
389            return Ok(self.subscribe_send(operation_id).await);
390        }
391
392        // Since the following four checks may only fail due to client side
393        // programming error we do not have to enable cancellation and can check
394        // them before we start the state machine.
395        ensure!(
396            payload.contract.claim_pk == self.keypair.public_key(),
397            "The outgoing contract is keyed to another gateway"
398        );
399
400        // This prevents DOS attacks where an attacker submits a different invoice.
401        ensure!(
402            secp256k1::SECP256K1
403                .verify_schnorr(
404                    &payload.auth,
405                    &Message::from_digest(
406                        *payload.invoice.consensus_hash::<sha256::Hash>().as_ref()
407                    ),
408                    &payload.contract.refund_pk.x_only_public_key().0,
409                )
410                .is_ok(),
411            "Invalid auth signature for the invoice data"
412        );
413
414        // We need to check that the contract has been confirmed by the federation
415        // before we start the state machine to prevent DOS attacks.
416        let (contract_id, expiration) = self
417            .module_api
418            .outgoing_contract_expiration(payload.outpoint)
419            .await
420            .map_err(|_| anyhow!("The gateway can not reach the federation"))?
421            .ok_or(anyhow!("The outgoing contract has not yet been confirmed"))?;
422
423        ensure!(
424            contract_id == payload.contract.contract_id(),
425            "Contract Id returned by the federation does not match contract in request"
426        );
427
428        let (payment_hash, amount) = match &payload.invoice {
429            LightningInvoice::Bolt11(invoice) => (
430                invoice.payment_hash(),
431                invoice
432                    .amount_milli_satoshis()
433                    .ok_or(anyhow!("Invoice is missing amount"))?,
434            ),
435        };
436
437        ensure!(
438            PaymentImage::Hash(*payment_hash) == payload.contract.payment_image,
439            "The invoices payment hash does not match the contracts payment hash"
440        );
441
442        let min_contract_amount = self
443            .gateway
444            .min_contract_amount(&payload.federation_id, amount)
445            .await?;
446
447        let send_sm = GatewayClientStateMachinesV2::Send(SendStateMachine {
448            common: SendSMCommon {
449                operation_id,
450                outpoint: payload.outpoint,
451                contract: payload.contract.clone(),
452                max_delay: expiration.saturating_sub(EXPIRATION_DELTA_MINIMUM_V2),
453                min_contract_amount,
454                invoice: payload.invoice,
455                claim_keypair: self.keypair,
456            },
457            state: SendSMState::Sending,
458        });
459
460        let mut dbtx = self.client_ctx.module_db().begin_transaction().await;
461        self.client_ctx
462            .manual_operation_start_dbtx(
463                &mut dbtx.to_ref_nc(),
464                operation_id,
465                LightningCommonInit::KIND.as_str(),
466                GatewayOperationMetaV2::role(GatewayOperationRoleV2::Send),
467                vec![self.client_ctx.make_dyn_state(send_sm)],
468            )
469            .await
470            .ok();
471
472        self.client_ctx
473            .log_event(
474                &mut dbtx,
475                OutgoingPaymentStarted {
476                    operation_start,
477                    outgoing_contract: payload.contract.clone(),
478                    min_contract_amount,
479                    invoice_amount: Amount::from_msats(amount),
480                    max_delay: expiration.saturating_sub(EXPIRATION_DELTA_MINIMUM_V2),
481                },
482            )
483            .await;
484        dbtx.commit_tx().await;
485
486        Ok(self.subscribe_send(operation_id).await)
487    }
488
489    pub async fn subscribe_send(&self, operation_id: OperationId) -> Result<[u8; 32], Signature> {
490        let mut stream = self.notifier.subscribe(operation_id).await;
491
492        loop {
493            if let Some(GatewayClientStateMachinesV2::Send(state)) = stream.next().await {
494                match state.state {
495                    SendSMState::Sending => {}
496                    SendSMState::Claiming(claiming) => {
497                        // The preimage is proof the payment succeeded, so return it to
498                        // the sender as soon as it is available rather than waiting for
499                        // an additional ordering. The gateway's claim of the outgoing
500                        // contract has already been submitted by the send state machine
501                        // and finalizes in the background.
502                        return Ok(claiming.preimage);
503                    }
504                    SendSMState::Cancelled(cancelled) => {
505                        warn!("Outgoing lightning payment is cancelled {:?}", cancelled);
506
507                        let signature = self
508                            .keypair
509                            .sign_schnorr(state.common.contract.forfeit_message());
510
511                        assert!(state.common.contract.verify_forfeit_signature(&signature));
512
513                        return Err(signature);
514                    }
515                }
516            }
517        }
518    }
519
520    async fn legacy_completion_exists(
521        &self,
522        operation_id: OperationId,
523        circuit: IncomingCircuitKey,
524    ) -> bool {
525        let active = self
526            .client_ctx
527            .get_own_operation_active_states(operation_id)
528            .await
529            .into_iter()
530            .map(|(state, _)| state)
531            .collect::<Vec<_>>();
532        let inactive = self
533            .client_ctx
534            .get_own_operation_inactive_states(operation_id)
535            .await
536            .into_iter()
537            .map(|(state, _)| state)
538            .collect::<Vec<_>>();
539
540        legacy_completion_in_states(&active, &inactive, circuit)
541    }
542
543    pub async fn relay_incoming_htlc(
544        &self,
545        payment_hash: sha256::Hash,
546        incoming_chan_id: u64,
547        htlc_id: u64,
548        contract: IncomingContract,
549        amount_msat: u64,
550    ) -> anyhow::Result<()> {
551        let operation_start = now();
552        let receive_operation_id = OperationId::from_encodable(&contract);
553        let circuit = IncomingCircuitKey {
554            incoming_chan_id,
555            htlc_id,
556        };
557        let completion_operation_id = incoming_circuit_operation_id(receive_operation_id, circuit);
558        let receive_exists = self.client_ctx.operation_exists(receive_operation_id).await;
559        let completion_exists = self
560            .client_ctx
561            .operation_exists(completion_operation_id)
562            .await;
563        let legacy_completion_exists = self
564            .legacy_completion_exists(receive_operation_id, circuit)
565            .await;
566        let plan = incoming_relay_plan(receive_exists, completion_exists, legacy_completion_exists);
567        if plan == IncomingRelayPlan::Replay {
568            return Ok(());
569        }
570
571        let commitment = contract.commitment.clone();
572        if plan == IncomingRelayPlan::CreateReceiveAndCompletion {
573            let refund_keypair = self.keypair;
574            let client_output = ClientOutput::<LightningOutput> {
575                output: LightningOutput::V0(LightningOutputV0::Incoming(contract.clone())),
576                amounts: Amounts::new_bitcoin(contract.commitment.amount),
577            };
578            let client_output_sm = ClientOutputSM::<GatewayClientStateMachinesV2> {
579                state_machines: Arc::new(move |range: OutPointRange| {
580                    assert_eq!(range.count(), 1);
581
582                    vec![GatewayClientStateMachinesV2::Receive(ReceiveStateMachine {
583                        common: ReceiveSMCommon {
584                            operation_id: receive_operation_id,
585                            contract: contract.clone(),
586                            outpoint: range.into_iter().next().unwrap(),
587                            refund_keypair,
588                        },
589                        state: ReceiveSMState::Funding,
590                    })]
591                }),
592            };
593
594            let client_output = self.client_ctx.make_client_outputs(ClientOutputBundle::new(
595                vec![client_output],
596                vec![client_output_sm],
597            ));
598            let transaction = TransactionBuilder::new().with_outputs(client_output);
599
600            let creation_result = self
601                .client_ctx
602                .finalize_and_submit_transaction(
603                    receive_operation_id,
604                    LightningCommonInit::KIND.as_str(),
605                    |_| GatewayOperationMetaV2::role(GatewayOperationRoleV2::Receive),
606                    transaction,
607                )
608                .await;
609            if let Err(error) = creation_result {
610                let operation_exists = self.client_ctx.operation_exists(receive_operation_id).await;
611                if operation_creation_failed_permanently(true, operation_exists) {
612                    return Err(error);
613                }
614            } else {
615                let mut dbtx = self.client_ctx.module_db().begin_transaction().await;
616                self.client_ctx
617                    .log_event(
618                        &mut dbtx,
619                        IncomingPaymentStarted {
620                            operation_start,
621                            incoming_contract_commitment: commitment,
622                            invoice_amount: Amount::from_msats(amount_msat),
623                        },
624                    )
625                    .await;
626                dbtx.commit_tx().await;
627            }
628        }
629
630        let completion =
631            GatewayClientStateMachinesV2::CircuitComplete(CircuitCompleteStateMachine {
632                common: CircuitCompleteSMCommon {
633                    operation_id: completion_operation_id,
634                    receive_operation_id,
635                    payment_hash,
636                    circuit,
637                },
638                state: CompleteSMState::Pending,
639            });
640        let creation_result = self
641            .client_ctx
642            .manual_operation_start(
643                completion_operation_id,
644                LightningCommonInit::KIND.as_str(),
645                GatewayOperationMetaV2::role(GatewayOperationRoleV2::CircuitCompletion),
646                vec![self.client_ctx.make_dyn_state(completion)],
647            )
648            .await;
649        if let Err(error) = creation_result {
650            let operation_exists = self
651                .client_ctx
652                .operation_exists(completion_operation_id)
653                .await;
654            if operation_creation_failed_permanently(true, operation_exists) {
655                return Err(error);
656            }
657        }
658
659        Ok(())
660    }
661
662    pub async fn relay_direct_swap(
663        &self,
664        contract: IncomingContract,
665        amount_msat: u64,
666    ) -> anyhow::Result<FinalReceiveState> {
667        let operation_start = now();
668
669        let operation_id = OperationId::from_encodable(&contract);
670
671        if self.client_ctx.operation_exists(operation_id).await {
672            return Ok(self.await_receive(operation_id).await);
673        }
674
675        let refund_keypair = self.keypair;
676
677        let client_output = ClientOutput::<LightningOutput> {
678            output: LightningOutput::V0(LightningOutputV0::Incoming(contract.clone())),
679            amounts: Amounts::new_bitcoin(contract.commitment.amount),
680        };
681        let commitment = contract.commitment.clone();
682        let client_output_sm = ClientOutputSM::<GatewayClientStateMachinesV2> {
683            state_machines: Arc::new(move |range| {
684                assert_eq!(range.count(), 1);
685
686                vec![GatewayClientStateMachinesV2::Receive(ReceiveStateMachine {
687                    common: ReceiveSMCommon {
688                        operation_id,
689                        contract: contract.clone(),
690                        outpoint: range.into_iter().next().unwrap(),
691                        refund_keypair,
692                    },
693                    state: ReceiveSMState::Funding,
694                })]
695            }),
696        };
697
698        let client_output = self.client_ctx.make_client_outputs(ClientOutputBundle::new(
699            vec![client_output],
700            vec![client_output_sm],
701        ));
702
703        let transaction = TransactionBuilder::new().with_outputs(client_output);
704
705        self.client_ctx
706            .finalize_and_submit_transaction(
707                operation_id,
708                LightningCommonInit::KIND.as_str(),
709                |_| GatewayOperationMetaV2::role(GatewayOperationRoleV2::Receive),
710                transaction,
711            )
712            .await?;
713
714        let mut dbtx = self.client_ctx.module_db().begin_transaction().await;
715        self.client_ctx
716            .log_event(
717                &mut dbtx,
718                IncomingPaymentStarted {
719                    operation_start,
720                    incoming_contract_commitment: commitment,
721                    invoice_amount: Amount::from_msats(amount_msat),
722                },
723            )
724            .await;
725        dbtx.commit_tx().await;
726
727        Ok(self.await_receive(operation_id).await)
728    }
729
730    pub async fn await_receive(&self, operation_id: OperationId) -> FinalReceiveState {
731        let mut stream = self.notifier.subscribe(operation_id).await;
732
733        loop {
734            if let Some(GatewayClientStateMachinesV2::Receive(state)) = stream.next().await {
735                match state.state {
736                    ReceiveSMState::Funding => {}
737                    ReceiveSMState::Rejected(..) => return FinalReceiveState::Rejected,
738                    ReceiveSMState::Success(preimage) => {
739                        return FinalReceiveState::Success(preimage);
740                    }
741                    ReceiveSMState::Refunding(out_points) => {
742                        if self
743                            .client_ctx
744                            .await_primary_module_outputs(operation_id, out_points)
745                            .await
746                            .is_err()
747                        {
748                            return FinalReceiveState::Failure;
749                        }
750
751                        return FinalReceiveState::Refunded;
752                    }
753                    ReceiveSMState::Failure => return FinalReceiveState::Failure,
754                }
755            }
756        }
757    }
758
759    /// Waits for a legacy combined receive operation or a circuit-completion
760    /// operation to finish.
761    ///
762    /// `operation_id` must identify either a legacy operation containing
763    /// [`GatewayClientStateMachinesV2::Complete`] or a role-specific operation
764    /// containing [`GatewayClientStateMachinesV2::CircuitComplete`]. Both
765    /// successful completion and a durable permanent outcome conflict terminate
766    /// the wait.
767    pub async fn await_completion(&self, operation_id: OperationId) {
768        let mut stream = self.notifier.subscribe(operation_id).await;
769
770        loop {
771            match stream.next().await {
772                Some(GatewayClientStateMachinesV2::Complete(state)) => {
773                    if matches!(
774                        state.state,
775                        CompleteSMState::Completed | CompleteSMState::CompletionFailed(_)
776                    ) {
777                        info!(%state, "LNv2 completion state machine finished");
778                        return;
779                    }
780
781                    info!(%state, "Waiting for LNv2 completion state machine");
782                }
783                Some(GatewayClientStateMachinesV2::Receive(state)) => {
784                    info!(%state, "Waiting for LNv2 completion state machine");
785                    continue;
786                }
787                Some(GatewayClientStateMachinesV2::CircuitComplete(state)) => {
788                    if matches!(
789                        state.state,
790                        CompleteSMState::Completed | CompleteSMState::CompletionFailed(_)
791                    ) {
792                        info!(%state, "LNv2 circuit completion state machine finished");
793                        return;
794                    }
795
796                    info!(%state, "Waiting for LNv2 circuit completion state machine");
797                }
798                Some(state) => {
799                    warn!(%state, "Operation is not an LNv2 completion state machine");
800                    return;
801                }
802                None => return,
803            }
804        }
805    }
806}
807
808/// An interface between module implementation and the general `Gateway`
809///
810/// To abstract away and decouple the core gateway from the modules, the
811/// interface between the is expressed as a trait. The core gateway handles
812/// LNv2 operations that require access to the database or lightning node.
813#[async_trait]
814pub trait IGatewayClientV2: Debug + Send + Sync {
815    /// Uses the gateway's Lightning node to complete a payment.
816    ///
817    /// Implementations must absorb and retry every transient node or
818    /// connectivity failure. They return `Err` only when Lightning has reached
819    /// a permanent state that makes the requested outcome impossible. The
820    /// future may block while retrying and must remain cancellation-safe.
821    /// Completion state machines persist any returned error as terminal
822    /// `CompletionFailed`.
823    async fn complete_htlc(
824        &self,
825        htlc_response: InterceptPaymentResponse,
826    ) -> Result<(), LightningRpcError>;
827
828    /// Determines if the payment can be completed using a direct swap to
829    /// another federation.
830    ///
831    /// A direct swap is determined by checking the gateway's connected
832    /// lightning node against the invoice's payee lightning node. If they
833    /// are the same, then the gateway can use another client to complete
834    /// the payment be swapping ecash instead of a payment over the
835    /// Lightning network.
836    async fn is_direct_swap(
837        &self,
838        invoice: &Bolt11Invoice,
839    ) -> anyhow::Result<Option<(IncomingContract, ClientHandleArc)>>;
840
841    /// Initiates a payment over the Lightning network.
842    async fn pay(
843        &self,
844        invoice: Bolt11Invoice,
845        max_delay: u64,
846        max_fee: Amount,
847    ) -> Result<[u8; 32], LightningRpcError>;
848
849    /// Computes the minimum contract amount necessary for making an outgoing
850    /// payment.
851    ///
852    /// The minimum contract amount must contain transaction fees to cover the
853    /// gateway's transaction fee and optionally additional fee to cover the
854    /// gateway's Lightning fee if the payment goes over the Lightning
855    /// network.
856    async fn min_contract_amount(
857        &self,
858        federation_id: &FederationId,
859        amount: u64,
860    ) -> anyhow::Result<Amount>;
861
862    /// Check if this invoice was created using LNv1 and if the gateway is
863    /// connected to the target federation.
864    async fn is_lnv1_invoice(&self, invoice: &Bolt11Invoice) -> Option<Spanned<ClientHandleArc>>;
865
866    /// Perform a swap from an LNv2 `OutgoingContract` to an LNv1
867    /// `IncomingContract`
868    async fn relay_lnv1_swap(
869        &self,
870        client: &ClientHandleArc,
871        invoice: &Bolt11Invoice,
872    ) -> anyhow::Result<FinalReceiveState>;
873
874    /// Claims the given payment image for `operation_id` in the gateway's
875    /// global database, returning `true` if this operation may claim the
876    /// outgoing contract (the image was unclaimed, or already claimed by
877    /// this same operation) and `false` if another operation already
878    /// claimed it.
879    ///
880    /// A single Lightning payment yields a single preimage, so the gateway may
881    /// claim at most one outgoing contract per payment image. Unlike the
882    /// per-federation module database, this spans all of the gateway's
883    /// federations, so two clients in different federations paying the same
884    /// invoice cannot both be claimed.
885    async fn claim_payment_image(
886        &self,
887        payment_image: &PaymentImage,
888        operation_id: OperationId,
889    ) -> bool;
890}
891
892#[cfg(test)]
893mod tests;