1#![deny(clippy::pedantic)]
2#![allow(clippy::missing_errors_doc)]
3#![allow(clippy::missing_panics_doc)]
4#![allow(clippy::module_name_repetitions)]
5#![allow(clippy::must_use_candidate)]
6
7pub use fedimint_lnv2_common as common;
8
9mod api;
10#[cfg(feature = "cli")]
11mod cli;
12pub mod db;
13pub mod events;
14pub mod htlc;
15mod receive_sm;
16mod send_sm;
17
18use std::collections::{BTreeMap, BTreeSet};
19use std::sync::Arc;
20use std::time::Duration;
21
22use async_stream::stream;
23use bitcoin::hashes::{Hash, sha256};
24use bitcoin::secp256k1;
25use db::{DbKeyPrefix, GatewayKey, IncomingContractStreamIndexKey};
26use fedimint_api_client::api::{DynModuleApi, ServerError};
27use fedimint_client_module::error::{
28 ClientModuleError, InsufficientBalanceError, OperationLookupError, TransactionSubmitError,
29};
30use fedimint_client_module::module::init::{ClientModuleInit, ClientModuleInitArgs};
31use fedimint_client_module::module::recovery::NoModuleBackup;
32use fedimint_client_module::module::{ClientContext, ClientModule, OutPointRange};
33use fedimint_client_module::oplog::UpdateStreamOrOutcome;
34use fedimint_client_module::secret::DeriveableSecretClientExt;
35use fedimint_client_module::sm::{Context, DynState, ModuleNotifier, State, StateTransition};
36use fedimint_client_module::transaction::{
37 ClientOutput, ClientOutputBundle, ClientOutputSM, FeeQuote, FeeQuoteRequest,
38 TransactionBuilder, max_affordable_send_amount,
39};
40use fedimint_client_module::{DynGlobalClientContext, sm_enum_variant_translation};
41use fedimint_core::bolt11::{currency_for_network, currency_matches_network};
42use fedimint_core::config::FederationId;
43use fedimint_core::core::{Account, IntoDynInstance, ModuleInstanceId, ModuleKind, OperationId};
44use fedimint_core::db::{DatabaseTransaction, IDatabaseTransactionOpsCoreTyped};
45use fedimint_core::encoding::{Decodable, Encodable};
46use fedimint_core::module::{
47 AmountUnit, Amounts, ApiAuth, ApiVersion, CommonModuleInit, ModuleCommon, ModuleInit,
48 MultiApiVersion,
49};
50use fedimint_core::secp256k1::SECP256K1;
51use fedimint_core::task::TaskGroup;
52use fedimint_core::time::duration_since_epoch;
53use fedimint_core::util::backoff_util::{self, custom_backoff};
54use fedimint_core::util::{self as util, FmtCompact as _, SafeUrl};
55use fedimint_core::{Amount, PeerId, apply, async_trait_maybe_send, runtime};
56use fedimint_derive_secret::{ChildId, DerivableSecret};
57use fedimint_lnv2_common::config::LightningClientConfig;
58use fedimint_lnv2_common::contracts::{IncomingContract, OutgoingContract, PaymentImage};
59use fedimint_lnv2_common::gateway_api::{
60 GatewayConnection, MAX_INVOICE_EXPIRY_SECS, PaymentFee, RealGatewayConnection, RoutingInfo,
61};
62use fedimint_lnv2_common::{
63 Bolt11InvoiceDescription, GatewayApi, KIND, LightningCommonInit, LightningInvoice,
64 LightningModuleTypes, LightningOutput, LightningOutputV0, lnurl, tweak,
65};
66use fedimint_logging::LOG_CLIENT_MODULE_LNV2;
67use futures::StreamExt;
68use lightning_invoice::{Bolt11Invoice, Currency};
69use secp256k1::{Keypair, Scalar, SecretKey, ecdh};
70use serde::{Deserialize, Serialize};
71use serde_json::Value;
72use strum::IntoEnumIterator as _;
73use thiserror::Error;
74use tpe::{AggregateDecryptionKey, AggregatePublicKey, derive_agg_dk};
75use tracing::warn;
76
77use crate::api::LightningFederationApi;
78use crate::events::SendPaymentEvent;
79use crate::htlc::{CreateHtlcOperationMeta, SpendHtlcOperationMeta};
80use crate::receive_sm::{ReceiveSMCommon, ReceiveSMState, ReceiveStateMachine};
81use crate::send_sm::{SendSMCommon, SendSMState, SendStateMachine};
82
83const EXPIRATION_DELTA_LIMIT: u64 = 1440;
86
87const CONTRACT_CONFIRMATION_BUFFER: u64 = 12;
89
90fn gateway_request_backoff() -> backoff_util::FibonacciBackoff {
94 custom_backoff(Duration::from_millis(250), Duration::from_secs(1), Some(3))
95}
96
97#[allow(clippy::large_enum_variant)]
98#[derive(Debug, Clone, Serialize, Deserialize)]
99pub enum LightningOperationMeta {
100 Send(SendOperationMeta),
101 Receive(ReceiveOperationMeta),
102 LnurlReceive(LnurlReceiveOperationMeta),
103 CreateHtlc(CreateHtlcOperationMeta),
104 ClaimHtlc(SpendHtlcOperationMeta),
105 RefundHtlc(SpendHtlcOperationMeta),
106 CancelHtlc(SpendHtlcOperationMeta),
107}
108
109#[derive(Debug, Clone, Serialize, Deserialize)]
110pub struct SendOperationMeta {
111 pub change_outpoint_range: OutPointRange,
112 pub gateway: SafeUrl,
113 pub contract: OutgoingContract,
114 pub invoice: LightningInvoice,
115 pub custom_meta: Value,
116}
117
118impl SendOperationMeta {
119 pub fn gateway_fee(&self) -> Amount {
121 match &self.invoice {
122 LightningInvoice::Bolt11(invoice) => self.contract.amount.saturating_sub(
123 Amount::from_msats(invoice.amount_milli_satoshis().expect("Invoice has amount")),
124 ),
125 }
126 }
127}
128
129#[derive(Debug, Clone, Serialize, Deserialize)]
130pub struct ReceiveOperationMeta {
131 pub gateway: SafeUrl,
132 pub contract: IncomingContract,
133 pub invoice: LightningInvoice,
134 pub custom_meta: Value,
135}
136
137impl ReceiveOperationMeta {
138 pub fn gateway_fee(&self) -> Amount {
140 match &self.invoice {
141 LightningInvoice::Bolt11(invoice) => {
142 Amount::from_msats(invoice.amount_milli_satoshis().expect("Invoice has amount"))
143 .saturating_sub(self.contract.commitment.amount)
144 }
145 }
146 }
147}
148
149#[derive(Debug, Clone, Serialize, Deserialize)]
150pub struct LnurlReceiveOperationMeta {
151 pub contract: IncomingContract,
152 pub custom_meta: Value,
153}
154
155#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
173pub enum SendOperationState {
174 Funding,
176 Funded,
178 Success([u8; 32]),
180 Refunding,
182 Refunded,
184 Failure,
186}
187
188#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
190pub enum FinalSendOperationState {
191 Success(#[serde(with = "fedimint_core::hex::serde")] [u8; 32]),
194 Refunded,
196 Failure,
198}
199
200pub type SendResult = Result<OperationId, SendPaymentError>;
201
202#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
214pub enum ReceiveOperationState {
215 Pending,
217 Expired,
219 Claiming,
221 Claimed,
223 Failure,
225 Uneconomical,
229}
230
231#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
233pub enum FinalReceiveOperationState {
234 Expired,
236 Claimed,
238 Failure,
240 Uneconomical,
243}
244
245pub type ReceiveResult = Result<(Bolt11Invoice, OperationId), ReceiveError>;
246
247#[derive(Clone)]
248pub struct LightningClientInit {
249 pub gateway_conn: Option<Arc<dyn GatewayConnection + Send + Sync>>,
250 pub custom_meta_fn: Arc<dyn Fn() -> Value + Send + Sync>,
251}
252
253impl std::fmt::Debug for LightningClientInit {
254 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
255 f.debug_struct("LightningClientInit")
256 .field("gateway_conn", &self.gateway_conn)
257 .field("custom_meta_fn", &"<function>")
258 .finish()
259 }
260}
261
262impl Default for LightningClientInit {
263 fn default() -> Self {
264 LightningClientInit {
265 gateway_conn: None,
266 custom_meta_fn: Arc::new(|| Value::Null),
267 }
268 }
269}
270
271impl ModuleInit for LightningClientInit {
272 type Common = LightningCommonInit;
273
274 async fn dump_database(
275 &self,
276 _dbtx: &mut DatabaseTransaction<'_>,
277 _prefix_names: Vec<String>,
278 ) -> Box<dyn Iterator<Item = (String, Box<dyn erased_serde::Serialize + Send>)> + '_> {
279 Box::new(BTreeMap::new().into_iter())
280 }
281}
282
283#[apply(async_trait_maybe_send!)]
284impl ClientModuleInit for LightningClientInit {
285 type Module = LightningClientModule;
286
287 fn supported_api_versions(&self) -> MultiApiVersion {
288 MultiApiVersion::try_from_iter([ApiVersion { major: 0, minor: 0 }])
289 .expect("no version conflicts")
290 }
291
292 async fn init(
293 &self,
294 args: &ClientModuleInitArgs<Self>,
295 ) -> Result<Self::Module, ClientModuleError> {
296 let gateway_conn = if let Some(gateway_conn) = self.gateway_conn.clone() {
297 gateway_conn
298 } else {
299 let api = GatewayApi::new(None, args.connector_registry.clone());
300 Arc::new(RealGatewayConnection { api })
301 };
302 Ok(LightningClientModule::new(
303 *args.federation_id(),
304 args.cfg().clone(),
305 args.notifier().clone(),
306 args.context(),
307 args.module_api().clone(),
308 args.module_root_secret(),
309 gateway_conn,
310 self.custom_meta_fn.clone(),
311 args.admin_auth().cloned(),
312 args.task_group(),
313 args.client_span(),
314 ))
315 }
316
317 fn used_db_prefixes(&self) -> Option<BTreeSet<u8>> {
318 Some(
319 DbKeyPrefix::iter()
320 .map(|p| p as u8)
321 .chain(
322 DbKeyPrefix::ExternalReservedStart as u8
323 ..=DbKeyPrefix::CoreInternalReservedEnd as u8,
324 )
325 .collect(),
326 )
327 }
328}
329
330#[derive(Debug, Clone)]
331pub struct LightningClientContext {
332 federation_id: FederationId,
333 gateway_conn: Arc<dyn GatewayConnection + Send + Sync>,
334 pub(crate) client_ctx: ClientContext<LightningClientModule>,
335}
336
337impl Context for LightningClientContext {
338 const KIND: Option<ModuleKind> = Some(KIND);
339}
340
341#[derive(Debug, Clone)]
342pub struct LightningClientModule {
343 federation_id: FederationId,
344 cfg: LightningClientConfig,
345 notifier: ModuleNotifier<LightningClientStateMachines>,
346 client_ctx: ClientContext<Self>,
347 module_api: DynModuleApi,
348 keys: [AccountKeys; Account::ALL.len()],
353 gateway_conn: Arc<dyn GatewayConnection + Send + Sync>,
354 #[allow(unused)] admin_auth: Option<ApiAuth>,
356}
357
358#[apply(async_trait_maybe_send!)]
359impl ClientModule for LightningClientModule {
360 type Init = LightningClientInit;
361 type Common = LightningModuleTypes;
362 type Backup = NoModuleBackup;
363 type ModuleStateMachineContext = LightningClientContext;
364 type States = LightningClientStateMachines;
365
366 fn context(&self) -> Self::ModuleStateMachineContext {
367 LightningClientContext {
368 federation_id: self.federation_id,
369 gateway_conn: self.gateway_conn.clone(),
370 client_ctx: self.client_ctx.clone(),
371 }
372 }
373
374 fn input_fee(
375 &self,
376 amounts: &Amounts,
377 _input: &<Self::Common as ModuleCommon>::Input,
378 ) -> Option<Amounts> {
379 Some(Amounts::new_bitcoin(
380 self.cfg.fee_consensus.fee(amounts.expect_only_bitcoin()),
381 ))
382 }
383
384 fn output_fee(
385 &self,
386 amounts: &Amounts,
387 _output: &<Self::Common as ModuleCommon>::Output,
388 ) -> Option<Amounts> {
389 Some(Amounts::new_bitcoin(
390 self.cfg.fee_consensus.fee(amounts.expect_only_bitcoin()),
391 ))
392 }
393
394 #[cfg(feature = "cli")]
395 async fn handle_cli_command(
396 &self,
397 args: &[std::ffi::OsString],
398 ) -> Result<serde_json::Value, ClientModuleError> {
399 cli::handle_cli_command(self, args)
400 .await
401 .map_err(ClientModuleError::other)
402 }
403}
404
405#[derive(Debug, Clone, Copy)]
407struct AccountKeys {
408 keypair: Keypair,
411 lnurl_keypair: Keypair,
414}
415
416impl LightningClientModule {
417 fn keys(&self, account: Account) -> AccountKeys {
418 self.keys[usize::from(account.index())]
419 }
420
421 #[allow(clippy::too_many_arguments)]
422 fn new(
423 federation_id: FederationId,
424 cfg: LightningClientConfig,
425 notifier: ModuleNotifier<LightningClientStateMachines>,
426 client_ctx: ClientContext<Self>,
427 module_api: DynModuleApi,
428 module_root_secret: &DerivableSecret,
429 gateway_conn: Arc<dyn GatewayConnection + Send + Sync>,
430 custom_meta_fn: Arc<dyn Fn() -> Value + Send + Sync>,
431 admin_auth: Option<ApiAuth>,
432 task_group: &TaskGroup,
433 client_span: &tracing::Span,
434 ) -> Self {
435 let module = Self {
436 federation_id,
437 cfg,
438 notifier,
439 client_ctx,
440 module_api,
441 keys: Account::ALL.map(|account| {
442 let account_secret = module_root_secret.derive_account_secret(account);
443
444 AccountKeys {
445 keypair: account_secret.child_key(ChildId(0)).to_secp_key(SECP256K1),
446 lnurl_keypair: account_secret.child_key(ChildId(1)).to_secp_key(SECP256K1),
447 }
448 }),
449 gateway_conn,
450 admin_auth,
451 };
452
453 module.spawn_receive_lnurl_task(custom_meta_fn, task_group, client_span);
454
455 module.spawn_gateway_map_update_task(task_group, client_span);
456
457 module
458 }
459
460 fn spawn_gateway_map_update_task(&self, task_group: &TaskGroup, client_span: &tracing::Span) {
461 let module = self.clone();
462 let api = self.module_api.clone();
463
464 task_group.spawn_cancellable_with_span(
465 client_span.clone(),
466 "gateway_map_update_task",
467 async move {
468 api.wait_for_initialized_connections().await;
469 module.update_gateway_map().await;
470 },
471 );
472 }
473
474 async fn update_gateway_map(&self) {
475 if let Ok(gateways) = self.module_api.gateways().await {
482 let mut dbtx = self.client_ctx.module_db().begin_transaction().await;
483
484 for gateway in gateways {
485 if let Ok(Some(routing_info)) = self
486 .gateway_conn
487 .routing_info(gateway.clone(), &self.federation_id)
488 .await
489 {
490 dbtx.insert_entry(&GatewayKey(routing_info.lightning_public_key), &gateway)
491 .await;
492 }
493 }
494
495 if let Err(e) = dbtx.commit_tx_result().await {
496 warn!("Failed to commit the updated gateway mapping to the database: {e}");
497 }
498 }
499 }
500
501 pub async fn select_gateway(
506 &self,
507 invoice: Option<Bolt11Invoice>,
508 ) -> Result<(SafeUrl, RoutingInfo), SelectGatewayError> {
509 let gateways = self
510 .module_api
511 .gateways()
512 .await
513 .map_err(|e| SelectGatewayError::FailedToRequestGateways(e.to_string()))?;
514
515 if gateways.is_empty() {
516 return Err(SelectGatewayError::NoGatewaysAvailable);
517 }
518
519 if let Some(invoice) = invoice
520 && let Some(gateway) = self
521 .client_ctx
522 .module_db()
523 .begin_transaction_nc()
524 .await
525 .get_value(&GatewayKey(invoice.recover_payee_pub_key()))
526 .await
527 .filter(|gateway| gateways.contains(gateway))
528 && let Ok(Some(routing_info)) = self.routing_info(&gateway).await
529 {
530 return Ok((gateway, routing_info));
531 }
532
533 for gateway in gateways {
534 if let Ok(Some(routing_info)) = self.routing_info(&gateway).await {
535 return Ok((gateway, routing_info));
536 }
537 }
538
539 Err(SelectGatewayError::GatewaysUnresponsive)
540 }
541
542 pub async fn list_gateways(
545 &self,
546 peer: Option<PeerId>,
547 ) -> Result<Vec<SafeUrl>, ListGatewaysError> {
548 if let Some(peer) = peer {
549 self.module_api
550 .gateways_from_peer(peer)
551 .await
552 .map_err(|_| ListGatewaysError::FailedToListGateways)
553 } else {
554 self.module_api
555 .gateways()
556 .await
557 .map_err(|_| ListGatewaysError::FailedToListGateways)
558 }
559 }
560
561 pub async fn routing_info(
568 &self,
569 gateway: &SafeUrl,
570 ) -> Result<Option<RoutingInfo>, RoutingInfoError> {
571 util::retry("gateway-routing-info", gateway_request_backoff(), || {
572 self.gateway_conn
573 .routing_info(gateway.clone(), &self.federation_id)
574 })
575 .await
576 .map_err(|_| RoutingInfoError::FailedToRequestRoutingInfo)
577 }
578
579 pub async fn send(
596 &self,
597 account: Account,
598 invoice: Bolt11Invoice,
599 gateway: Option<SafeUrl>,
600 custom_meta: Value,
601 ) -> Result<OperationId, SendPaymentError> {
602 let (amount, operation_id) = self.validate_send_invoice(account, &invoice).await?;
603
604 let (gateway_api, routing_info) = self.resolve_send_gateway(&invoice, gateway).await?;
605
606 self.fund_outgoing_contract(
607 account,
608 invoice,
609 amount,
610 operation_id,
611 gateway_api,
612 routing_info,
613 custom_meta,
614 )
615 .await
616 }
617
618 pub async fn send_with_terms(
634 &self,
635 account: Account,
636 invoice: Bolt11Invoice,
637 gateway: SafeUrl,
638 send_fee: PaymentFee,
639 expiration_delta: u64,
640 custom_meta: Value,
641 ) -> Result<OperationId, SendWithTermsError> {
642 let (amount, operation_id) = self.validate_send_invoice(account, &invoice).await?;
643
644 let (gateway_api, routing_info) =
645 self.resolve_send_gateway(&invoice, Some(gateway)).await?;
646
647 let current = routing_info.send_parameters(&invoice);
648
649 if current != (send_fee, expiration_delta) {
650 return Err(SendWithTermsError::TermsChanged {
651 send_fee: current.0,
652 expiration_delta: current.1,
653 });
654 }
655
656 let operation_id = self
657 .fund_outgoing_contract(
658 account,
659 invoice,
660 amount,
661 operation_id,
662 gateway_api,
663 routing_info,
664 custom_meta,
665 )
666 .await?;
667
668 Ok(operation_id)
669 }
670
671 async fn validate_send_invoice(
675 &self,
676 account: Account,
677 invoice: &Bolt11Invoice,
678 ) -> Result<(u64, OperationId), SendPaymentError> {
679 let amount = invoice
680 .amount_milli_satoshis()
681 .ok_or(SendPaymentError::InvoiceMissingAmount)?;
682
683 if invoice.would_expire(duration_since_epoch()) {
684 return Err(SendPaymentError::InvoiceExpired);
685 }
686
687 if !currency_matches_network(&invoice.currency(), self.cfg.network) {
688 return Err(SendPaymentError::WrongCurrency {
689 invoice_currency: invoice.currency(),
690 federation_currency: currency_for_network(self.cfg.network),
691 });
692 }
693
694 if !self
695 .client_ctx
696 .supports_account(AmountUnit::BITCOIN, account)
697 {
698 return Err(SendPaymentError::AccountNotSupported);
699 }
700
701 let operation_id = OperationId::from_encodable(&(invoice.clone(), 0u64));
705
706 if self.client_ctx.operation_exists(operation_id).await {
707 return Err(SendPaymentError::DuplicatePaymentAttempt(operation_id));
708 }
709
710 Ok((amount, operation_id))
711 }
712
713 async fn resolve_send_gateway(
716 &self,
717 invoice: &Bolt11Invoice,
718 gateway: Option<SafeUrl>,
719 ) -> Result<(SafeUrl, RoutingInfo), SendPaymentError> {
720 match gateway {
721 Some(gateway_api) => Ok((
722 gateway_api.clone(),
723 self.routing_info(&gateway_api)
724 .await
725 .map_err(|e| SendPaymentError::FailedToConnectToGateway(e.to_string()))?
726 .ok_or(SendPaymentError::FederationNotSupported)?,
727 )),
728 None => self
729 .select_gateway(Some(invoice.clone()))
730 .await
731 .map_err(SendPaymentError::SelectGateway),
732 }
733 }
734
735 #[allow(clippy::too_many_lines)]
738 #[allow(clippy::too_many_arguments)]
739 async fn fund_outgoing_contract(
740 &self,
741 account: Account,
742 invoice: Bolt11Invoice,
743 amount: u64,
744 operation_id: OperationId,
745 gateway_api: SafeUrl,
746 routing_info: RoutingInfo,
747 custom_meta: Value,
748 ) -> Result<OperationId, SendPaymentError> {
749 let (ephemeral_tweak, ephemeral_pk) =
750 tweak::generate(self.keys(account).keypair.public_key());
751
752 let refund_keypair = SecretKey::from_slice(&ephemeral_tweak)
753 .expect("32 bytes, within curve order")
754 .keypair(secp256k1::SECP256K1);
755
756 let (send_fee, expiration_delta) = routing_info.send_parameters(&invoice);
757
758 if !send_fee.is_within(&PaymentFee::SEND_FEE_LIMIT) {
759 return Err(SendPaymentError::GatewayFeeExceedsLimit);
760 }
761
762 if EXPIRATION_DELTA_LIMIT < expiration_delta {
763 return Err(SendPaymentError::GatewayExpirationExceedsLimit);
764 }
765
766 let consensus_block_count = self
767 .module_api
768 .consensus_block_count()
769 .await
770 .map_err(|e| SendPaymentError::FailedToRequestBlockCount(e.to_string()))?;
771
772 let contract = OutgoingContract {
773 payment_image: PaymentImage::Hash(*invoice.payment_hash()),
774 amount: send_fee.add_to(amount),
775 expiration: consensus_block_count + expiration_delta + CONTRACT_CONFIRMATION_BUFFER,
776 claim_pk: routing_info.module_public_key,
777 refund_pk: refund_keypair.public_key(),
778 ephemeral_pk,
779 };
780
781 let contract_clone = contract.clone();
782 let gateway_api_clone = gateway_api.clone();
783 let invoice_clone = invoice.clone();
784
785 let client_output = ClientOutput::<LightningOutput> {
786 output: LightningOutput::V0(LightningOutputV0::Outgoing(contract.clone())),
787 amounts: Amounts::new_bitcoin(contract.amount),
788 };
789
790 let client_output_sm = ClientOutputSM::<LightningClientStateMachines> {
791 state_machines: Arc::new(move |range: OutPointRange| {
792 vec![LightningClientStateMachines::Send(SendStateMachine {
793 common: SendSMCommon {
794 operation_id,
795 outpoint: range.into_iter().next().unwrap(),
796 contract: contract_clone.clone(),
797 gateway_api: Some(gateway_api_clone.clone()),
798 invoice: Some(LightningInvoice::Bolt11(invoice_clone.clone())),
799 refund_keypair,
800 },
801 state: SendSMState::Funding,
802 })]
803 }),
804 };
805
806 let client_output = self.client_ctx.make_client_outputs(ClientOutputBundle::new(
807 vec![client_output],
808 vec![client_output_sm],
809 ));
810
811 let transaction = TransactionBuilder::new(account).with_outputs(client_output);
812
813 let operation_meta_gen = move |change_outpoint_range| {
814 LightningOperationMeta::Send(SendOperationMeta {
815 change_outpoint_range,
816 gateway: gateway_api.clone(),
817 contract: contract.clone(),
818 invoice: LightningInvoice::Bolt11(invoice.clone()),
819 custom_meta: custom_meta.clone(),
820 })
821 };
822
823 self.client_ctx
824 .finalize_and_submit_transaction_with_events(
825 operation_id,
826 LightningCommonInit::KIND.as_str(),
827 operation_meta_gen,
828 transaction,
829 vec![self.client_ctx.make_event(SendPaymentEvent {
830 operation_id,
831 amount: Amount::from_msats(amount),
832 fee: send_fee.fee(amount),
833 account,
834 })],
835 )
836 .await
837 .map_err(|e| match e {
838 TransactionSubmitError::InsufficientFunds(e) => {
839 SendPaymentError::InsufficientFunds(e)
840 }
841 e => SendPaymentError::FailedToFundPayment(e.fmt_compact().to_string()),
842 })?;
843
844 Ok(operation_id)
845 }
846
847 pub async fn get_invoice_send_status(
853 &self,
854 invoice: &Bolt11Invoice,
855 ) -> Result<InvoiceSendStatus, OperationLookupError> {
856 let mut last_op = None;
861
862 for attempt in 0_u64.. {
863 let operation_id = OperationId::from_encodable(&(invoice.clone(), attempt));
864
865 if !self.client_ctx.operation_exists(operation_id).await {
866 break;
867 }
868
869 last_op = Some(operation_id);
870 }
871
872 let Some(operation_id) = last_op else {
873 return Ok(InvoiceSendStatus::NotAttempted);
874 };
875
876 if self.client_ctx.has_active_states(operation_id).await {
877 return Ok(InvoiceSendStatus::InFlight(operation_id));
878 }
879
880 let mut stream = self
883 .subscribe_send_operation_state_updates(operation_id)
884 .await?
885 .into_stream();
886
887 while let Some(state) = stream.next().await {
888 if let SendOperationState::Success(_) = state {
889 return Ok(InvoiceSendStatus::Succeeded(operation_id));
890 }
891 }
892
893 Ok(InvoiceSendStatus::Failed(operation_id))
894 }
895
896 pub async fn subscribe_send_operation_state_updates(
898 &self,
899 operation_id: OperationId,
900 ) -> Result<UpdateStreamOrOutcome<SendOperationState>, OperationLookupError> {
901 let operation = self.client_ctx.get_operation(operation_id).await?;
902 let mut stream = self.notifier.subscribe(operation_id).await;
903 let client_ctx = self.client_ctx.clone();
904 let module_api = self.module_api.clone();
905
906 Ok(self.client_ctx.outcome_or_updates(&operation, operation_id, |state| match state {
907 SendOperationState::Funding
908 | SendOperationState::Funded
909 | SendOperationState::Refunding => false,
910 SendOperationState::Success(_)
911 | SendOperationState::Refunded
912 | SendOperationState::Failure => true,
913 }, move || {
914 stream! {
915 loop {
916 if let Some(LightningClientStateMachines::Send(state)) = stream.next().await {
917 match state.state {
918 SendSMState::Funding => yield SendOperationState::Funding,
919 SendSMState::Funded => yield SendOperationState::Funded,
920 SendSMState::Success(preimage) => {
921 assert!(state.common.contract.verify_preimage(&preimage));
923
924 yield SendOperationState::Success(preimage);
925 return;
926 },
927 SendSMState::Refunding(out_points) => {
928 yield SendOperationState::Refunding;
929
930 if client_ctx.await_primary_module_outputs(operation_id, out_points.clone()).await.is_ok() {
931 yield SendOperationState::Refunded;
932 return;
933 }
934
935 if let Some(preimage) = module_api.await_preimage(
939 state.common.outpoint,
940 0
941 ).await
942 && state.common.contract.verify_preimage(&preimage) {
943 yield SendOperationState::Success(preimage);
944 return;
945 }
946
947 yield SendOperationState::Failure;
948 return;
949 },
950 SendSMState::Rejected(..) => {
951 yield SendOperationState::Failure;
952 return;
953 },
954 }
955 }
956 }
957 }
958 }))
959 }
960
961 pub async fn await_final_send_operation_state(
963 &self,
964 operation_id: OperationId,
965 ) -> Result<FinalSendOperationState, OperationLookupError> {
966 let mut stream = self
967 .subscribe_send_operation_state_updates(operation_id)
968 .await?
969 .into_stream();
970
971 let mut final_state = None;
972
973 while let Some(state) = stream.next().await {
974 match state {
975 SendOperationState::Success(preimage) => {
976 final_state = Some(FinalSendOperationState::Success(preimage));
977 }
978 SendOperationState::Refunded => {
979 final_state = Some(FinalSendOperationState::Refunded);
980 }
981 SendOperationState::Failure => final_state = Some(FinalSendOperationState::Failure),
982 _ => {}
983 }
984 }
985
986 Ok(final_state.expect("Stream contains one final state"))
987 }
988
989 pub async fn receive(
1001 &self,
1002 account: Account,
1003 amount: Amount,
1004 expiry_secs: u32,
1005 description: Bolt11InvoiceDescription,
1006 gateway: Option<SafeUrl>,
1007 custom_meta: Value,
1008 ) -> Result<(Bolt11Invoice, OperationId), ReceiveError> {
1009 if !self
1010 .client_ctx
1011 .supports_account(AmountUnit::BITCOIN, account)
1012 {
1013 return Err(ReceiveError::AccountNotSupported);
1014 }
1015
1016 if MAX_INVOICE_EXPIRY_SECS < expiry_secs {
1017 return Err(ReceiveError::InvoiceExpiryTooLong);
1018 }
1019
1020 let (gateway, routing_info) = self.resolve_receive_gateway(gateway).await?;
1021
1022 self.receive_with_routing_info(
1023 account,
1024 amount,
1025 expiry_secs,
1026 description,
1027 gateway,
1028 routing_info,
1029 custom_meta,
1030 )
1031 .await
1032 }
1033
1034 #[allow(clippy::too_many_arguments)]
1047 pub async fn receive_with_terms(
1048 &self,
1049 account: Account,
1050 amount: Amount,
1051 expiry_secs: u32,
1052 description: Bolt11InvoiceDescription,
1053 gateway: SafeUrl,
1054 receive_fee: PaymentFee,
1055 custom_meta: Value,
1056 ) -> Result<(Bolt11Invoice, OperationId), ReceiveWithTermsError> {
1057 if !self
1058 .client_ctx
1059 .supports_account(AmountUnit::BITCOIN, account)
1060 {
1061 return Err(ReceiveError::AccountNotSupported.into());
1062 }
1063
1064 if MAX_INVOICE_EXPIRY_SECS < expiry_secs {
1065 return Err(ReceiveError::InvoiceExpiryTooLong.into());
1066 }
1067
1068 let (gateway, routing_info) = self.resolve_receive_gateway(Some(gateway)).await?;
1069
1070 if routing_info.receive_fee != receive_fee {
1071 return Err(ReceiveWithTermsError::TermsChanged {
1072 receive_fee: routing_info.receive_fee,
1073 });
1074 }
1075
1076 let (invoice, operation_id) = self
1077 .receive_with_routing_info(
1078 account,
1079 amount,
1080 expiry_secs,
1081 description,
1082 gateway,
1083 routing_info,
1084 custom_meta,
1085 )
1086 .await?;
1087
1088 Ok((invoice, operation_id))
1089 }
1090
1091 async fn resolve_receive_gateway(
1095 &self,
1096 gateway: Option<SafeUrl>,
1097 ) -> Result<(SafeUrl, RoutingInfo), ReceiveError> {
1098 match gateway {
1099 Some(gateway) => {
1100 let routing_info = self
1101 .routing_info(&gateway)
1102 .await
1103 .map_err(|e| ReceiveError::FailedToConnectToGateway(e.to_string()))?
1104 .ok_or(ReceiveError::FederationNotSupported)?;
1105
1106 if !routing_info.receive_enabled {
1107 return Err(ReceiveError::ReceiveDisabled);
1108 }
1109
1110 Ok((gateway, routing_info))
1111 }
1112 None => self
1113 .select_receive_gateway()
1114 .await
1115 .map_err(ReceiveError::SelectGateway),
1116 }
1117 }
1118
1119 async fn select_receive_gateway(&self) -> Result<(SafeUrl, RoutingInfo), SelectGatewayError> {
1124 let gateways = self
1125 .module_api
1126 .gateways()
1127 .await
1128 .map_err(|e| SelectGatewayError::FailedToRequestGateways(e.to_string()))?;
1129
1130 if gateways.is_empty() {
1131 return Err(SelectGatewayError::NoGatewaysAvailable);
1132 }
1133
1134 let mut any_responded = false;
1135
1136 for gateway in gateways {
1137 if let Ok(Some(routing_info)) = self.routing_info(&gateway).await {
1138 any_responded = true;
1139
1140 if routing_info.receive_enabled {
1141 return Ok((gateway, routing_info));
1142 }
1143 }
1144 }
1145
1146 if any_responded {
1147 Err(SelectGatewayError::NoGatewayAcceptsReceives)
1148 } else {
1149 Err(SelectGatewayError::GatewaysUnresponsive)
1150 }
1151 }
1152
1153 #[allow(clippy::too_many_arguments)]
1157 async fn receive_with_routing_info(
1158 &self,
1159 account: Account,
1160 amount: Amount,
1161 expiry_secs: u32,
1162 description: Bolt11InvoiceDescription,
1163 gateway: SafeUrl,
1164 routing_info: RoutingInfo,
1165 custom_meta: Value,
1166 ) -> Result<(Bolt11Invoice, OperationId), ReceiveError> {
1167 if !routing_info
1168 .receive_fee
1169 .is_within(&PaymentFee::RECEIVE_FEE_LIMIT)
1170 {
1171 return Err(ReceiveError::GatewayFeeExceedsLimit);
1172 }
1173
1174 let contract_amount = routing_info.receive_fee.subtract_from(amount.msats);
1175
1176 if !self.is_worth_claiming(account, contract_amount).await {
1180 return Err(ReceiveError::AmountTooSmall);
1181 }
1182
1183 let (contract, preimage, invoice) =
1188 util::retry("gateway-bolt11-invoice", gateway_request_backoff(), || {
1189 self.request_invoice_for_new_contract(
1190 account,
1191 &gateway,
1192 &routing_info,
1193 contract_amount,
1194 amount,
1195 description.clone(),
1196 expiry_secs,
1197 )
1198 })
1199 .await
1200 .map_err(|e| ReceiveError::FailedToConnectToGateway(e.to_string()))?;
1201
1202 if invoice.payment_hash() != &preimage.consensus_hash() {
1203 return Err(ReceiveError::InvalidInvoice);
1204 }
1205
1206 if invoice.amount_milli_satoshis() != Some(amount.msats) {
1207 return Err(ReceiveError::IncorrectInvoiceAmount);
1208 }
1209
1210 let operation_id = self
1211 .receive_incoming_contract(
1212 account,
1213 self.keys(account).keypair.secret_key(),
1214 contract.clone(),
1215 LightningOperationMeta::Receive(ReceiveOperationMeta {
1216 gateway,
1217 contract,
1218 invoice: LightningInvoice::Bolt11(invoice.clone()),
1219 custom_meta,
1220 }),
1221 )
1222 .await
1223 .expect("The contract has been generated with our public key");
1224
1225 Ok((invoice, operation_id))
1226 }
1227
1228 #[allow(clippy::too_many_arguments)]
1231 async fn request_invoice_for_new_contract(
1232 &self,
1233 account: Account,
1234 gateway: &SafeUrl,
1235 routing_info: &RoutingInfo,
1236 contract_amount: Amount,
1237 amount: Amount,
1238 description: Bolt11InvoiceDescription,
1239 expiry_secs: u32,
1240 ) -> Result<(IncomingContract, [u8; 32], Bolt11Invoice), ServerError> {
1241 let recipient_static_pk = self.keys(account).keypair.public_key();
1242
1243 let (ephemeral_tweak, ephemeral_pk) = tweak::generate(recipient_static_pk);
1244
1245 let encryption_seed = ephemeral_tweak
1246 .consensus_hash::<sha256::Hash>()
1247 .to_byte_array();
1248
1249 let preimage = encryption_seed
1250 .consensus_hash::<sha256::Hash>()
1251 .to_byte_array();
1252
1253 let expiration = duration_since_epoch()
1254 .as_secs()
1255 .saturating_add(u64::from(expiry_secs));
1256
1257 let claim_pk = recipient_static_pk
1258 .mul_tweak(
1259 secp256k1::SECP256K1,
1260 &Scalar::from_be_bytes(ephemeral_tweak).expect("Within curve order"),
1261 )
1262 .expect("Tweak is valid");
1263
1264 let contract = IncomingContract::new(
1265 self.cfg.tpe_agg_pk,
1266 encryption_seed,
1267 preimage,
1268 PaymentImage::Hash(preimage.consensus_hash()),
1269 contract_amount,
1270 expiration,
1271 claim_pk,
1272 routing_info.module_public_key,
1273 ephemeral_pk,
1274 );
1275
1276 let invoice = self
1277 .gateway_conn
1278 .bolt11_invoice(
1279 gateway.clone(),
1280 self.federation_id,
1281 contract.clone(),
1282 amount,
1283 description,
1284 expiry_secs,
1285 )
1286 .await?;
1287
1288 Ok((contract, preimage, invoice))
1289 }
1290
1291 pub async fn receive_fee_quote(
1306 &self,
1307 account: Account,
1308 amount: Amount,
1309 ) -> Result<FeeQuote, TransactionSubmitError> {
1310 self.client_ctx
1311 .fee_quote(
1312 OperationId::new_random(),
1313 FeeQuoteRequest {
1314 input_amount: Amounts::new_bitcoin(amount),
1315 output_amount: Amounts::ZERO,
1316 input_fee: Amounts::new_bitcoin(self.cfg.fee_consensus.fee(amount)),
1317 output_fee: Amounts::ZERO,
1318 account,
1319 },
1320 )
1321 .await
1322 }
1323
1324 async fn is_worth_claiming(&self, account: Account, amount: Amount) -> bool {
1335 match self.receive_fee_quote(account, amount).await {
1336 Ok(quote) => quote.total().get_bitcoin() < amount,
1337 Err(_) => false,
1338 }
1339 }
1340
1341 pub async fn send_fee_quote(
1357 &self,
1358 account: Account,
1359 amount: Amount,
1360 ) -> Result<FeeQuote, TransactionSubmitError> {
1361 self.client_ctx
1362 .fee_quote(
1363 OperationId::new_random(),
1364 FeeQuoteRequest {
1365 input_amount: Amounts::ZERO,
1366 output_amount: Amounts::new_bitcoin(amount),
1367 input_fee: Amounts::ZERO,
1368 output_fee: Amounts::new_bitcoin(self.cfg.fee_consensus.fee(amount)),
1369 account,
1370 },
1371 )
1372 .await
1373 }
1374
1375 pub async fn spendable_amount(
1412 &self,
1413 account: Account,
1414 balance: Amount,
1415 gateway: Option<SafeUrl>,
1416 ) -> Result<Amount, SpendableAmountError> {
1417 let routing_info = match gateway {
1418 Some(gateway) => self
1419 .routing_info(&gateway)
1420 .await?
1421 .ok_or(SpendableAmountError::FederationNotSupported)?,
1422 None => self.select_gateway(None).await?.1,
1423 };
1424
1425 let send_fee = routing_info.send_fee_default;
1430
1431 if !send_fee.is_within(&PaymentFee::SEND_FEE_LIMIT) {
1432 return Err(SpendableAmountError::SendFeeExceedsLimit {
1433 fee: send_fee,
1434 limit: PaymentFee::SEND_FEE_LIMIT,
1435 });
1436 }
1437
1438 max_affordable_send_amount(
1439 balance,
1440 Amount::from_msats(1),
1441 balance,
1442 |invoice_amount: Amount| send_fee.add_to(invoice_amount.msats),
1443 |contract_amount: Amount| self.send_fee_quote(account, contract_amount),
1444 )
1445 .await
1446 .map_err(SpendableAmountError::Quote)?
1447 .ok_or(SpendableAmountError::BalanceTooLow { balance })
1448 }
1449
1450 async fn receive_incoming_contract(
1453 &self,
1454 account: Account,
1455 sk: SecretKey,
1456 contract: IncomingContract,
1457 operation_meta: LightningOperationMeta,
1458 ) -> Option<OperationId> {
1459 let operation_id = OperationId::from_encodable(&contract.clone());
1460
1461 let tpe_agg_pk = self.cfg.tpe_agg_pk;
1462
1463 let (claim_keypair, agg_decryption_key) = runtime::spawn_blocking({
1464 let contract = contract.clone();
1465
1466 move || recover_contract_keys(sk, &tpe_agg_pk, &contract)
1467 })
1468 .await?;
1469
1470 let receive_sm = LightningClientStateMachines::Receive(ReceiveStateMachine {
1471 common: ReceiveSMCommon {
1472 operation_id,
1473 contract: contract.clone(),
1474 claim_keypair,
1475 agg_decryption_key,
1476 },
1477 state: ReceiveSMState::Pending,
1478 });
1479
1480 let _ = self
1483 .client_ctx
1484 .manual_operation_start(
1485 operation_id,
1486 account,
1487 LightningCommonInit::KIND.as_str(),
1488 operation_meta,
1489 vec![self.client_ctx.make_dyn_state(receive_sm)],
1490 )
1491 .await;
1492
1493 Some(operation_id)
1494 }
1495
1496 pub async fn subscribe_receive_operation_state_updates(
1498 &self,
1499 operation_id: OperationId,
1500 ) -> Result<UpdateStreamOrOutcome<ReceiveOperationState>, OperationLookupError> {
1501 let operation = self.client_ctx.get_operation(operation_id).await?;
1502 let mut stream = self.notifier.subscribe(operation_id).await;
1503 let client_ctx = self.client_ctx.clone();
1504
1505 Ok(self.client_ctx.outcome_or_updates(&operation, operation_id, |state| match state {
1506 ReceiveOperationState::Pending | ReceiveOperationState::Claiming => false,
1507 ReceiveOperationState::Expired
1508 | ReceiveOperationState::Claimed
1509 | ReceiveOperationState::Failure
1510 | ReceiveOperationState::Uneconomical => true,
1511 }, move || {
1512 stream! {
1513 loop {
1514 if let Some(LightningClientStateMachines::Receive(state)) = stream.next().await {
1515 match state.state {
1516 ReceiveSMState::Pending => yield ReceiveOperationState::Pending,
1517 ReceiveSMState::Claiming(out_points) => {
1518 yield ReceiveOperationState::Claiming;
1519
1520 if client_ctx.await_primary_module_outputs(operation_id, out_points).await.is_ok() {
1521 yield ReceiveOperationState::Claimed;
1522 } else {
1523 yield ReceiveOperationState::Failure;
1524 }
1525 return;
1526 },
1527 ReceiveSMState::Expired => {
1528 yield ReceiveOperationState::Expired;
1529 return;
1530 }
1531 ReceiveSMState::Uneconomical => {
1532 yield ReceiveOperationState::Uneconomical;
1533 return;
1534 }
1535 }
1536 }
1537 }
1538 }
1539 }))
1540 }
1541
1542 pub async fn await_final_receive_operation_state(
1544 &self,
1545 operation_id: OperationId,
1546 ) -> Result<FinalReceiveOperationState, OperationLookupError> {
1547 let mut stream = self
1548 .subscribe_receive_operation_state_updates(operation_id)
1549 .await?
1550 .into_stream();
1551
1552 let mut final_state = None;
1553
1554 while let Some(state) = stream.next().await {
1555 match state {
1556 ReceiveOperationState::Expired => {
1557 final_state = Some(FinalReceiveOperationState::Expired);
1558 }
1559 ReceiveOperationState::Claimed => {
1560 final_state = Some(FinalReceiveOperationState::Claimed);
1561 }
1562 ReceiveOperationState::Failure => {
1563 final_state = Some(FinalReceiveOperationState::Failure);
1564 }
1565 ReceiveOperationState::Uneconomical => {
1566 final_state = Some(FinalReceiveOperationState::Uneconomical);
1567 }
1568 _ => {}
1569 }
1570 }
1571
1572 Ok(final_state.expect("Stream contains one final state"))
1573 }
1574
1575 pub async fn generate_lnurl(
1578 &self,
1579 account: Account,
1580 recurringd: SafeUrl,
1581 gateway: Option<SafeUrl>,
1582 ) -> Result<String, GenerateLnurlError> {
1583 if !self
1587 .client_ctx
1588 .supports_account(AmountUnit::BITCOIN, account)
1589 {
1590 return Err(GenerateLnurlError::AccountNotSupported);
1591 }
1592
1593 let gateways = if let Some(gateway) = gateway {
1594 vec![gateway]
1595 } else {
1596 let gateways = self
1597 .module_api
1598 .gateways()
1599 .await
1600 .map_err(|e| GenerateLnurlError::FailedToRequestGateways(e.to_string()))?;
1601
1602 if gateways.is_empty() {
1603 return Err(GenerateLnurlError::NoGatewaysAvailable);
1604 }
1605
1606 gateways
1607 };
1608
1609 let payload = fedimint_core::base32::encode_prefixed(
1610 fedimint_core::base32::FEDIMINT_PREFIX,
1611 &lnurl::LnurlRequest {
1612 federation_id: self.federation_id,
1613 recipient_pk: self.keys(account).lnurl_keypair.public_key(),
1614 aggregate_pk: self.cfg.tpe_agg_pk,
1615 gateways,
1616 },
1617 );
1618
1619 Ok(fedimint_lnurl::encode_lnurl(&format!(
1620 "{recurringd}pay/{payload}"
1621 )))
1622 }
1623
1624 fn spawn_receive_lnurl_task(
1625 &self,
1626 custom_meta_fn: Arc<dyn Fn() -> Value + Send + Sync>,
1627 task_group: &TaskGroup,
1628 client_span: &tracing::Span,
1629 ) {
1630 let module = self.clone();
1631 let api = self.module_api.clone();
1632
1633 task_group.spawn_cancellable_with_span(
1634 client_span.clone(),
1635 "receive_lnurl_task",
1636 async move {
1637 api.wait_for_initialized_connections().await;
1638 loop {
1639 module.receive_lnurl(custom_meta_fn()).await;
1640 }
1641 },
1642 );
1643 }
1644
1645 async fn receive_lnurl(&self, custom_meta: Value) {
1646 let stream_index = self
1657 .client_ctx
1658 .module_db()
1659 .begin_transaction_nc()
1660 .await
1661 .get_value(&IncomingContractStreamIndexKey)
1662 .await
1663 .unwrap_or(0);
1664
1665 let (contracts, next_index) = self
1666 .module_api
1667 .await_incoming_contracts(stream_index, 128)
1668 .await;
1669
1670 for contract in &contracts {
1671 let account = runtime::spawn_blocking({
1679 let keys = self.keys.map(|keys| keys.lnurl_keypair.secret_key());
1680 let tpe_agg_pk = self.cfg.tpe_agg_pk;
1681 let contract = contract.clone();
1682
1683 move || {
1684 Account::ALL.into_iter().find(|account| {
1685 recover_contract_keys(
1686 keys[usize::from(account.index())],
1687 &tpe_agg_pk,
1688 &contract,
1689 )
1690 .is_some()
1691 })
1692 }
1693 })
1694 .await;
1695
1696 let Some(account) = account else {
1697 continue;
1698 };
1699
1700 if !self
1703 .is_worth_claiming(account, contract.commitment.amount)
1704 .await
1705 {
1706 warn!(
1707 target: LOG_CLIENT_MODULE_LNV2,
1708 amount = %contract.commitment.amount,
1709 "Ignoring incoming contract, its amount does not cover the claim fee"
1710 );
1711
1712 continue;
1713 }
1714
1715 if let Some(operation_id) = self
1716 .receive_incoming_contract(
1717 account,
1718 self.keys(account).lnurl_keypair.secret_key(),
1719 contract.clone(),
1720 LightningOperationMeta::LnurlReceive(LnurlReceiveOperationMeta {
1721 contract: contract.clone(),
1722 custom_meta: custom_meta.clone(),
1723 }),
1724 )
1725 .await
1726 {
1727 let _ = self.await_final_receive_operation_state(operation_id).await;
1728 }
1729 }
1730
1731 let mut dbtx = self.client_ctx.module_db().begin_transaction().await;
1740
1741 dbtx.insert_entry(&IncomingContractStreamIndexKey, &next_index)
1742 .await;
1743
1744 dbtx.commit_tx().await;
1745 }
1746}
1747
1748#[derive(Error, Debug, Clone, Eq, PartialEq)]
1749pub enum SelectGatewayError {
1750 #[error("Failed to request gateways")]
1751 FailedToRequestGateways(String),
1752 #[error("No gateways are available")]
1753 NoGatewaysAvailable,
1754 #[error("All gateways failed to respond")]
1755 GatewaysUnresponsive,
1756 #[error("No online gateway currently accepts incoming payments for this federation")]
1757 NoGatewayAcceptsReceives,
1758}
1759
1760#[derive(Debug, Clone, Eq, PartialEq)]
1763pub enum InvoiceSendStatus {
1764 NotAttempted,
1766 InFlight(OperationId),
1768 Succeeded(OperationId),
1771 Failed(OperationId),
1773}
1774
1775#[derive(Error, Debug, Clone, Eq, PartialEq)]
1776pub enum SendPaymentError {
1777 #[error("The primary module only holds a balance for the primary account")]
1778 AccountNotSupported,
1779 #[error("Invoice is missing an amount")]
1780 InvoiceMissingAmount,
1781 #[error("Invoice has expired")]
1782 InvoiceExpired,
1783 #[error("Payment attempt is duplicate")]
1784 DuplicatePaymentAttempt(OperationId),
1785 #[error(transparent)]
1786 SelectGateway(SelectGatewayError),
1787 #[error("Failed to connect to gateway")]
1788 FailedToConnectToGateway(String),
1789 #[error("Gateway does not support this federation")]
1790 FederationNotSupported,
1791 #[error("Gateway fee exceeds the allowed limit")]
1792 GatewayFeeExceedsLimit,
1793 #[error("Gateway expiration time exceeds the allowed limit")]
1794 GatewayExpirationExceedsLimit,
1795 #[error("Failed to request block count")]
1796 FailedToRequestBlockCount(String),
1797 #[error("The client does not have sufficient funds to send the payment")]
1799 InsufficientFunds(#[source] InsufficientBalanceError),
1800 #[error("Failed to fund the payment")]
1803 FailedToFundPayment(String),
1804 #[error("Invoice is for a different currency")]
1805 WrongCurrency {
1806 invoice_currency: Currency,
1807 federation_currency: Currency,
1808 },
1809}
1810
1811#[derive(Error, Debug, Clone, Eq, PartialEq)]
1813#[non_exhaustive]
1814pub enum SendWithTermsError {
1815 #[error("Gateway's send terms changed since they were checked")]
1818 TermsChanged {
1819 send_fee: PaymentFee,
1820 expiration_delta: u64,
1821 },
1822 #[error(transparent)]
1824 Send(#[from] SendPaymentError),
1825}
1826
1827#[derive(Error, Debug, Clone, Eq, PartialEq)]
1828pub enum ReceiveError {
1829 #[error("The primary module only holds a balance for the primary account")]
1830 AccountNotSupported,
1831 #[error(transparent)]
1832 SelectGateway(SelectGatewayError),
1833 #[error("Failed to connect to gateway")]
1834 FailedToConnectToGateway(String),
1835 #[error("Gateway does not support this federation")]
1836 FederationNotSupported,
1837 #[error("Gateway does not currently accept incoming payments for this federation")]
1838 ReceiveDisabled,
1839 #[error("Gateway fee exceeds the allowed limit")]
1840 GatewayFeeExceedsLimit,
1841 #[error("Amount is too small to cover fees")]
1842 AmountTooSmall,
1843 #[error("Gateway returned an invalid invoice")]
1844 InvalidInvoice,
1845 #[error("Gateway returned an invoice with incorrect amount")]
1846 IncorrectInvoiceAmount,
1847 #[error("Requested invoice expiry exceeds the maximum of one day")]
1848 InvoiceExpiryTooLong,
1849}
1850
1851#[derive(Error, Debug, Clone, Eq, PartialEq)]
1853#[non_exhaustive]
1854pub enum ReceiveWithTermsError {
1855 #[error("Gateway's receive fee changed since it was checked")]
1858 TermsChanged { receive_fee: PaymentFee },
1859 #[error(transparent)]
1861 Receive(#[from] ReceiveError),
1862}
1863
1864#[derive(Error, Debug, Clone, Eq, PartialEq)]
1865pub enum GenerateLnurlError {
1866 #[error("The primary module only holds a balance for the primary account")]
1867 AccountNotSupported,
1868 #[error("No gateways are available")]
1869 NoGatewaysAvailable,
1870 #[error("Failed to request gateways")]
1871 FailedToRequestGateways(String),
1872}
1873
1874#[derive(Error, Debug, Clone, Eq, PartialEq)]
1875pub enum ListGatewaysError {
1876 #[error("Failed to request gateways")]
1877 FailedToListGateways,
1878}
1879
1880#[derive(Error, Debug, Clone, Eq, PartialEq)]
1881pub enum RoutingInfoError {
1882 #[error("Failed to request routing info")]
1883 FailedToRequestRoutingInfo,
1884}
1885
1886#[derive(Debug, Error)]
1894#[non_exhaustive]
1895pub enum SpendableAmountError {
1896 #[error(transparent)]
1899 RoutingInfo(#[from] RoutingInfoError),
1900
1901 #[error("The gateway does not support this federation")]
1904 FederationNotSupported,
1905
1906 #[error(transparent)]
1909 SelectGateway(#[from] SelectGatewayError),
1910
1911 #[error("The gateway's default send fee {fee} exceeds the limit {limit}")]
1914 SendFeeExceedsLimit {
1915 fee: PaymentFee,
1917 limit: PaymentFee,
1919 },
1920
1921 #[error("The fee quote for the payment failed")]
1923 Quote(#[source] TransactionSubmitError),
1924
1925 #[error("The balance {balance} is too low to send any amount after fees")]
1928 BalanceTooLow {
1929 balance: Amount,
1931 },
1932}
1933
1934#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
1935pub enum LightningClientStateMachines {
1936 Send(SendStateMachine),
1937 Receive(ReceiveStateMachine),
1938}
1939
1940impl IntoDynInstance for LightningClientStateMachines {
1941 type DynType = DynState;
1942
1943 fn into_dyn(self, instance_id: ModuleInstanceId) -> Self::DynType {
1944 DynState::from_typed(instance_id, self)
1945 }
1946}
1947
1948impl State for LightningClientStateMachines {
1949 type ModuleContext = LightningClientContext;
1950
1951 fn transitions(
1952 &self,
1953 context: &Self::ModuleContext,
1954 global_context: &DynGlobalClientContext,
1955 ) -> Vec<StateTransition<Self>> {
1956 match self {
1957 LightningClientStateMachines::Send(state) => {
1958 sm_enum_variant_translation!(
1959 state.transitions(context, global_context),
1960 LightningClientStateMachines::Send
1961 )
1962 }
1963 LightningClientStateMachines::Receive(state) => {
1964 sm_enum_variant_translation!(
1965 state.transitions(context, global_context),
1966 LightningClientStateMachines::Receive
1967 )
1968 }
1969 }
1970 }
1971
1972 fn operation_id(&self) -> OperationId {
1973 match self {
1974 LightningClientStateMachines::Send(state) => state.operation_id(),
1975 LightningClientStateMachines::Receive(state) => state.operation_id(),
1976 }
1977 }
1978}
1979
1980fn recover_contract_keys(
1986 sk: SecretKey,
1987 tpe_agg_pk: &AggregatePublicKey,
1988 contract: &IncomingContract,
1989) -> Option<(Keypair, AggregateDecryptionKey)> {
1990 let tweak = ecdh::SharedSecret::new(&contract.commitment.ephemeral_pk, &sk);
1991
1992 let encryption_seed = tweak
1993 .secret_bytes()
1994 .consensus_hash::<sha256::Hash>()
1995 .to_byte_array();
1996
1997 let claim_keypair = sk
1998 .mul_tweak(&Scalar::from_be_bytes(tweak.secret_bytes()).expect("Within curve order"))
1999 .expect("Tweak is valid")
2000 .keypair(secp256k1::SECP256K1);
2001
2002 if claim_keypair.public_key() != contract.commitment.claim_pk {
2003 return None; }
2005
2006 let agg_decryption_key = derive_agg_dk(tpe_agg_pk, &encryption_seed);
2007
2008 if !contract.verify_agg_decryption_key(tpe_agg_pk, &agg_decryption_key) {
2009 return None; }
2011
2012 contract.decrypt_preimage(&agg_decryption_key)?;
2013
2014 Some((claim_keypair, agg_decryption_key))
2015}