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
90pub const LNV1_HTLC_EXPIRY_SAFETY_MARGIN: u32 = LNV1_INCOMING_HTLC_EXPIRY_SAFETY_MARGIN as u32;
99
100#[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#[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 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
235pub 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 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 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 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(®istration_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 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 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 let _circuit_lock_guard = self
579 .intercepted_htlc_lock_pool
580 .async_lock(circuit_key)
581 .await;
582
583 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 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 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 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 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 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 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 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 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 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 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 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 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 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 if let Some(entry) =
1030 self.client_ctx.get_operation_dbtx(dbtx, operation_id).await
1031 {
1032 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 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 }
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 pub payment_hash: sha256::Hash,
1276 pub incoming_amount_msat: Amount,
1278 pub outgoing_amount_msat: Amount,
1280 pub incoming_expiry: u32,
1285 pub short_channel_id: Option<u64>,
1287 pub incoming_chan_id: u64,
1289 pub htlc_id: u64,
1291}
1292
1293#[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 pub incoming_expiry: u32,
1301 pub current_block_height: u32,
1303 pub expiry_safety_margin: u32,
1305}
1306
1307impl Htlc {
1308 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 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#[async_trait]
1367pub trait IGatewayClientV1: Debug + Send + Sync {
1368 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 async fn verify_pruned_invoice(
1388 &self,
1389 payment_data: PaymentData,
1390 ) -> Result<(), GatewayClientV1Error>;
1391
1392 async fn get_routing_fees(&self, federation_id: FederationId) -> Option<RoutingFees>;
1394
1395 async fn begin_fresh_receive(
1404 &self,
1405 federation_id: FederationId,
1406 ) -> Option<fedimint_gateway_common::PaymentPolicyGuard>;
1407
1408 async fn get_client(&self, federation_id: &FederationId) -> Option<Spanned<ClientHandleArc>>;
1411
1412 async fn get_client_for_invoice(
1420 &self,
1421 payment_data: PaymentData,
1422 ) -> Option<Spanned<ClientHandleArc>>;
1423
1424 async fn pay(
1426 &self,
1427 payment_data: PaymentData,
1428 max_delay: u64,
1429 max_fee: Amount,
1430 ) -> Result<PayInvoiceResponse, LightningRpcError>;
1431
1432 async fn outbound_payment_exists(&self, payment_hash: sha256::Hash) -> bool;
1443
1444 async fn complete_htlc(
1456 &self,
1457 htlc_response: InterceptPaymentResponse,
1458 ) -> Result<(), LightningRpcError>;
1459
1460 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 async fn claim_payment_image(
1483 &self,
1484 payment_image: &fedimint_lnv2_common::contracts::PaymentImage,
1485 operation_id: OperationId,
1486 ) -> bool;
1487}