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::sm::{Context, DynState, ModuleNotifier, State, StateTransition};
35use fedimint_client_module::transaction::{
36 ClientOutput, ClientOutputBundle, ClientOutputSM, FeeQuote, FeeQuoteRequest,
37 TransactionBuilder, max_affordable_send_amount,
38};
39use fedimint_client_module::{DynGlobalClientContext, sm_enum_variant_translation};
40use fedimint_core::config::FederationId;
41use fedimint_core::core::{IntoDynInstance, ModuleInstanceId, ModuleKind, OperationId};
42use fedimint_core::db::{AutocommitError, DatabaseTransaction, IDatabaseTransactionOpsCoreTyped};
43use fedimint_core::encoding::{Decodable, Encodable};
44use fedimint_core::module::{
45 Amounts, ApiAuth, ApiVersion, CommonModuleInit, ModuleCommon, ModuleInit, MultiApiVersion,
46};
47use fedimint_core::secp256k1::SECP256K1;
48use fedimint_core::task::TaskGroup;
49use fedimint_core::time::duration_since_epoch;
50use fedimint_core::util::backoff_util::{self, custom_backoff};
51use fedimint_core::util::{self as util, FmtCompact as _, SafeUrl};
52use fedimint_core::{Amount, PeerId, apply, async_trait_maybe_send, runtime};
53use fedimint_derive_secret::{ChildId, DerivableSecret};
54use fedimint_lnv2_common::config::LightningClientConfig;
55use fedimint_lnv2_common::contracts::{IncomingContract, OutgoingContract, PaymentImage};
56use fedimint_lnv2_common::gateway_api::{
57 GatewayConnection, MAX_INVOICE_EXPIRY_SECS, PaymentFee, RealGatewayConnection, RoutingInfo,
58};
59use fedimint_lnv2_common::{
60 Bolt11InvoiceDescription, GatewayApi, KIND, LightningCommonInit, LightningInvoice,
61 LightningModuleTypes, LightningOutput, LightningOutputV0, lnurl, tweak,
62};
63use fedimint_logging::LOG_CLIENT_MODULE_LNV2;
64use futures::StreamExt;
65use lightning_invoice::{Bolt11Invoice, Currency};
66use secp256k1::{Keypair, Scalar, SecretKey, ecdh};
67use serde::{Deserialize, Serialize};
68use serde_json::Value;
69use strum::IntoEnumIterator as _;
70use thiserror::Error;
71use tpe::{AggregateDecryptionKey, AggregatePublicKey, derive_agg_dk};
72use tracing::warn;
73
74use crate::api::LightningFederationApi;
75use crate::events::SendPaymentEvent;
76use crate::htlc::{CreateHtlcOperationMeta, SpendHtlcOperationMeta};
77use crate::receive_sm::{ReceiveSMCommon, ReceiveSMState, ReceiveStateMachine};
78use crate::send_sm::{SendSMCommon, SendSMState, SendStateMachine};
79
80const EXPIRATION_DELTA_LIMIT: u64 = 1440;
83
84const CONTRACT_CONFIRMATION_BUFFER: u64 = 12;
86
87fn gateway_request_backoff() -> backoff_util::FibonacciBackoff {
91 custom_backoff(Duration::from_millis(250), Duration::from_secs(1), Some(3))
92}
93
94#[allow(clippy::large_enum_variant)]
95#[derive(Debug, Clone, Serialize, Deserialize)]
96pub enum LightningOperationMeta {
97 Send(SendOperationMeta),
98 Receive(ReceiveOperationMeta),
99 LnurlReceive(LnurlReceiveOperationMeta),
100 CreateHtlc(CreateHtlcOperationMeta),
101 ClaimHtlc(SpendHtlcOperationMeta),
102 RefundHtlc(SpendHtlcOperationMeta),
103 CancelHtlc(SpendHtlcOperationMeta),
104}
105
106#[derive(Debug, Clone, Serialize, Deserialize)]
107pub struct SendOperationMeta {
108 pub change_outpoint_range: OutPointRange,
109 pub gateway: SafeUrl,
110 pub contract: OutgoingContract,
111 pub invoice: LightningInvoice,
112 pub custom_meta: Value,
113}
114
115impl SendOperationMeta {
116 pub fn gateway_fee(&self) -> Amount {
118 match &self.invoice {
119 LightningInvoice::Bolt11(invoice) => self.contract.amount.saturating_sub(
120 Amount::from_msats(invoice.amount_milli_satoshis().expect("Invoice has amount")),
121 ),
122 }
123 }
124}
125
126#[derive(Debug, Clone, Serialize, Deserialize)]
127pub struct ReceiveOperationMeta {
128 pub gateway: SafeUrl,
129 pub contract: IncomingContract,
130 pub invoice: LightningInvoice,
131 pub custom_meta: Value,
132}
133
134impl ReceiveOperationMeta {
135 pub fn gateway_fee(&self) -> Amount {
137 match &self.invoice {
138 LightningInvoice::Bolt11(invoice) => {
139 Amount::from_msats(invoice.amount_milli_satoshis().expect("Invoice has amount"))
140 .saturating_sub(self.contract.commitment.amount)
141 }
142 }
143 }
144}
145
146#[derive(Debug, Clone, Serialize, Deserialize)]
147pub struct LnurlReceiveOperationMeta {
148 pub contract: IncomingContract,
149 pub custom_meta: Value,
150}
151
152#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
170pub enum SendOperationState {
171 Funding,
173 Funded,
175 Success([u8; 32]),
177 Refunding,
179 Refunded,
181 Failure,
183}
184
185#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
187pub enum FinalSendOperationState {
188 Success(#[serde(with = "fedimint_core::hex::serde")] [u8; 32]),
191 Refunded,
193 Failure,
195}
196
197pub type SendResult = Result<OperationId, SendPaymentError>;
198
199#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
211pub enum ReceiveOperationState {
212 Pending,
214 Expired,
216 Claiming,
218 Claimed,
220 Failure,
222 Uneconomical,
226}
227
228#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
230pub enum FinalReceiveOperationState {
231 Expired,
233 Claimed,
235 Failure,
237 Uneconomical,
240}
241
242pub type ReceiveResult = Result<(Bolt11Invoice, OperationId), ReceiveError>;
243
244#[derive(Clone)]
245pub struct LightningClientInit {
246 pub gateway_conn: Option<Arc<dyn GatewayConnection + Send + Sync>>,
247 pub custom_meta_fn: Arc<dyn Fn() -> Value + Send + Sync>,
248}
249
250impl std::fmt::Debug for LightningClientInit {
251 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
252 f.debug_struct("LightningClientInit")
253 .field("gateway_conn", &self.gateway_conn)
254 .field("custom_meta_fn", &"<function>")
255 .finish()
256 }
257}
258
259impl Default for LightningClientInit {
260 fn default() -> Self {
261 LightningClientInit {
262 gateway_conn: None,
263 custom_meta_fn: Arc::new(|| Value::Null),
264 }
265 }
266}
267
268impl ModuleInit for LightningClientInit {
269 type Common = LightningCommonInit;
270
271 async fn dump_database(
272 &self,
273 _dbtx: &mut DatabaseTransaction<'_>,
274 _prefix_names: Vec<String>,
275 ) -> Box<dyn Iterator<Item = (String, Box<dyn erased_serde::Serialize + Send>)> + '_> {
276 Box::new(BTreeMap::new().into_iter())
277 }
278}
279
280#[apply(async_trait_maybe_send!)]
281impl ClientModuleInit for LightningClientInit {
282 type Module = LightningClientModule;
283
284 fn supported_api_versions(&self) -> MultiApiVersion {
285 MultiApiVersion::try_from_iter([ApiVersion { major: 0, minor: 0 }])
286 .expect("no version conflicts")
287 }
288
289 async fn init(
290 &self,
291 args: &ClientModuleInitArgs<Self>,
292 ) -> Result<Self::Module, ClientModuleError> {
293 let gateway_conn = if let Some(gateway_conn) = self.gateway_conn.clone() {
294 gateway_conn
295 } else {
296 let api = GatewayApi::new(None, args.connector_registry.clone());
297 Arc::new(RealGatewayConnection { api })
298 };
299 Ok(LightningClientModule::new(
300 *args.federation_id(),
301 args.cfg().clone(),
302 args.notifier().clone(),
303 args.context(),
304 args.module_api().clone(),
305 args.module_root_secret(),
306 gateway_conn,
307 self.custom_meta_fn.clone(),
308 args.admin_auth().cloned(),
309 args.task_group(),
310 args.client_span(),
311 ))
312 }
313
314 fn used_db_prefixes(&self) -> Option<BTreeSet<u8>> {
315 Some(
316 DbKeyPrefix::iter()
317 .map(|p| p as u8)
318 .chain(
319 DbKeyPrefix::ExternalReservedStart as u8
320 ..=DbKeyPrefix::CoreInternalReservedEnd as u8,
321 )
322 .collect(),
323 )
324 }
325}
326
327#[derive(Debug, Clone)]
328pub struct LightningClientContext {
329 federation_id: FederationId,
330 gateway_conn: Arc<dyn GatewayConnection + Send + Sync>,
331 pub(crate) client_ctx: ClientContext<LightningClientModule>,
332}
333
334impl Context for LightningClientContext {
335 const KIND: Option<ModuleKind> = Some(KIND);
336}
337
338#[derive(Debug, Clone)]
339pub struct LightningClientModule {
340 federation_id: FederationId,
341 cfg: LightningClientConfig,
342 notifier: ModuleNotifier<LightningClientStateMachines>,
343 client_ctx: ClientContext<Self>,
344 module_api: DynModuleApi,
345 keypair: Keypair,
346 lnurl_keypair: Keypair,
347 gateway_conn: Arc<dyn GatewayConnection + Send + Sync>,
348 #[allow(unused)] admin_auth: Option<ApiAuth>,
350}
351
352#[apply(async_trait_maybe_send!)]
353impl ClientModule for LightningClientModule {
354 type Init = LightningClientInit;
355 type Common = LightningModuleTypes;
356 type Backup = NoModuleBackup;
357 type ModuleStateMachineContext = LightningClientContext;
358 type States = LightningClientStateMachines;
359
360 fn context(&self) -> Self::ModuleStateMachineContext {
361 LightningClientContext {
362 federation_id: self.federation_id,
363 gateway_conn: self.gateway_conn.clone(),
364 client_ctx: self.client_ctx.clone(),
365 }
366 }
367
368 fn input_fee(
369 &self,
370 amounts: &Amounts,
371 _input: &<Self::Common as ModuleCommon>::Input,
372 ) -> Option<Amounts> {
373 Some(Amounts::new_bitcoin(
374 self.cfg.fee_consensus.fee(amounts.expect_only_bitcoin()),
375 ))
376 }
377
378 fn output_fee(
379 &self,
380 amounts: &Amounts,
381 _output: &<Self::Common as ModuleCommon>::Output,
382 ) -> Option<Amounts> {
383 Some(Amounts::new_bitcoin(
384 self.cfg.fee_consensus.fee(amounts.expect_only_bitcoin()),
385 ))
386 }
387
388 #[cfg(feature = "cli")]
389 async fn handle_cli_command(
390 &self,
391 args: &[std::ffi::OsString],
392 ) -> Result<serde_json::Value, ClientModuleError> {
393 cli::handle_cli_command(self, args)
394 .await
395 .map_err(ClientModuleError::other)
396 }
397}
398
399impl LightningClientModule {
400 #[allow(clippy::too_many_arguments)]
401 fn new(
402 federation_id: FederationId,
403 cfg: LightningClientConfig,
404 notifier: ModuleNotifier<LightningClientStateMachines>,
405 client_ctx: ClientContext<Self>,
406 module_api: DynModuleApi,
407 module_root_secret: &DerivableSecret,
408 gateway_conn: Arc<dyn GatewayConnection + Send + Sync>,
409 custom_meta_fn: Arc<dyn Fn() -> Value + Send + Sync>,
410 admin_auth: Option<ApiAuth>,
411 task_group: &TaskGroup,
412 client_span: &tracing::Span,
413 ) -> Self {
414 let module = Self {
415 federation_id,
416 cfg,
417 notifier,
418 client_ctx,
419 module_api,
420 keypair: module_root_secret
421 .child_key(ChildId(0))
422 .to_secp_key(SECP256K1),
423 lnurl_keypair: module_root_secret
424 .child_key(ChildId(1))
425 .to_secp_key(SECP256K1),
426 gateway_conn,
427 admin_auth,
428 };
429
430 module.spawn_receive_lnurl_task(custom_meta_fn, task_group, client_span);
431
432 module.spawn_gateway_map_update_task(task_group, client_span);
433
434 module
435 }
436
437 fn spawn_gateway_map_update_task(&self, task_group: &TaskGroup, client_span: &tracing::Span) {
438 let module = self.clone();
439 let api = self.module_api.clone();
440
441 task_group.spawn_cancellable_with_span(
442 client_span.clone(),
443 "gateway_map_update_task",
444 async move {
445 api.wait_for_initialized_connections().await;
446 module.update_gateway_map().await;
447 },
448 );
449 }
450
451 async fn update_gateway_map(&self) {
452 if let Ok(gateways) = self.module_api.gateways().await {
459 let mut dbtx = self.client_ctx.module_db().begin_transaction().await;
460
461 for gateway in gateways {
462 if let Ok(Some(routing_info)) = self
463 .gateway_conn
464 .routing_info(gateway.clone(), &self.federation_id)
465 .await
466 {
467 dbtx.insert_entry(&GatewayKey(routing_info.lightning_public_key), &gateway)
468 .await;
469 }
470 }
471
472 if let Err(e) = dbtx.commit_tx_result().await {
473 warn!("Failed to commit the updated gateway mapping to the database: {e}");
474 }
475 }
476 }
477
478 pub async fn select_gateway(
483 &self,
484 invoice: Option<Bolt11Invoice>,
485 ) -> Result<(SafeUrl, RoutingInfo), SelectGatewayError> {
486 let gateways = self
487 .module_api
488 .gateways()
489 .await
490 .map_err(|e| SelectGatewayError::FailedToRequestGateways(e.to_string()))?;
491
492 if gateways.is_empty() {
493 return Err(SelectGatewayError::NoGatewaysAvailable);
494 }
495
496 if let Some(invoice) = invoice
497 && let Some(gateway) = self
498 .client_ctx
499 .module_db()
500 .begin_transaction_nc()
501 .await
502 .get_value(&GatewayKey(invoice.recover_payee_pub_key()))
503 .await
504 .filter(|gateway| gateways.contains(gateway))
505 && let Ok(Some(routing_info)) = self.routing_info(&gateway).await
506 {
507 return Ok((gateway, routing_info));
508 }
509
510 for gateway in gateways {
511 if let Ok(Some(routing_info)) = self.routing_info(&gateway).await {
512 return Ok((gateway, routing_info));
513 }
514 }
515
516 Err(SelectGatewayError::GatewaysUnresponsive)
517 }
518
519 pub async fn list_gateways(
522 &self,
523 peer: Option<PeerId>,
524 ) -> Result<Vec<SafeUrl>, ListGatewaysError> {
525 if let Some(peer) = peer {
526 self.module_api
527 .gateways_from_peer(peer)
528 .await
529 .map_err(|_| ListGatewaysError::FailedToListGateways)
530 } else {
531 self.module_api
532 .gateways()
533 .await
534 .map_err(|_| ListGatewaysError::FailedToListGateways)
535 }
536 }
537
538 pub async fn routing_info(
545 &self,
546 gateway: &SafeUrl,
547 ) -> Result<Option<RoutingInfo>, RoutingInfoError> {
548 util::retry("gateway-routing-info", gateway_request_backoff(), || {
549 self.gateway_conn
550 .routing_info(gateway.clone(), &self.federation_id)
551 })
552 .await
553 .map_err(|_| RoutingInfoError::FailedToRequestRoutingInfo)
554 }
555
556 pub async fn send(
573 &self,
574 invoice: Bolt11Invoice,
575 gateway: Option<SafeUrl>,
576 custom_meta: Value,
577 ) -> Result<OperationId, SendPaymentError> {
578 let (amount, operation_id) = self.validate_send_invoice(&invoice).await?;
579
580 let (gateway_api, routing_info) = self.resolve_send_gateway(&invoice, gateway).await?;
581
582 self.fund_outgoing_contract(
583 invoice,
584 amount,
585 operation_id,
586 gateway_api,
587 routing_info,
588 custom_meta,
589 )
590 .await
591 }
592
593 pub async fn send_with_terms(
609 &self,
610 invoice: Bolt11Invoice,
611 gateway: SafeUrl,
612 send_fee: PaymentFee,
613 expiration_delta: u64,
614 custom_meta: Value,
615 ) -> Result<OperationId, SendWithTermsError> {
616 let (amount, operation_id) = self.validate_send_invoice(&invoice).await?;
617
618 let (gateway_api, routing_info) =
619 self.resolve_send_gateway(&invoice, Some(gateway)).await?;
620
621 let current = routing_info.send_parameters(&invoice);
622
623 if current != (send_fee, expiration_delta) {
624 return Err(SendWithTermsError::TermsChanged {
625 send_fee: current.0,
626 expiration_delta: current.1,
627 });
628 }
629
630 let operation_id = self
631 .fund_outgoing_contract(
632 invoice,
633 amount,
634 operation_id,
635 gateway_api,
636 routing_info,
637 custom_meta,
638 )
639 .await?;
640
641 Ok(operation_id)
642 }
643
644 async fn validate_send_invoice(
648 &self,
649 invoice: &Bolt11Invoice,
650 ) -> Result<(u64, OperationId), SendPaymentError> {
651 let amount = invoice
652 .amount_milli_satoshis()
653 .ok_or(SendPaymentError::InvoiceMissingAmount)?;
654
655 if invoice.would_expire(duration_since_epoch()) {
656 return Err(SendPaymentError::InvoiceExpired);
657 }
658
659 if self.cfg.network != invoice.currency().into() {
660 return Err(SendPaymentError::WrongCurrency {
661 invoice_currency: invoice.currency(),
662 federation_currency: self.cfg.network.into(),
663 });
664 }
665
666 let operation_id = OperationId::from_encodable(&(invoice.clone(), 0u64));
670
671 if self.client_ctx.operation_exists(operation_id).await {
672 return Err(SendPaymentError::DuplicatePaymentAttempt(operation_id));
673 }
674
675 Ok((amount, operation_id))
676 }
677
678 async fn resolve_send_gateway(
681 &self,
682 invoice: &Bolt11Invoice,
683 gateway: Option<SafeUrl>,
684 ) -> Result<(SafeUrl, RoutingInfo), SendPaymentError> {
685 match gateway {
686 Some(gateway_api) => Ok((
687 gateway_api.clone(),
688 self.routing_info(&gateway_api)
689 .await
690 .map_err(|e| SendPaymentError::FailedToConnectToGateway(e.to_string()))?
691 .ok_or(SendPaymentError::FederationNotSupported)?,
692 )),
693 None => self
694 .select_gateway(Some(invoice.clone()))
695 .await
696 .map_err(SendPaymentError::SelectGateway),
697 }
698 }
699
700 #[allow(clippy::too_many_lines)]
703 async fn fund_outgoing_contract(
704 &self,
705 invoice: Bolt11Invoice,
706 amount: u64,
707 operation_id: OperationId,
708 gateway_api: SafeUrl,
709 routing_info: RoutingInfo,
710 custom_meta: Value,
711 ) -> Result<OperationId, SendPaymentError> {
712 let (ephemeral_tweak, ephemeral_pk) = tweak::generate(self.keypair.public_key());
713
714 let refund_keypair = SecretKey::from_slice(&ephemeral_tweak)
715 .expect("32 bytes, within curve order")
716 .keypair(secp256k1::SECP256K1);
717
718 let (send_fee, expiration_delta) = routing_info.send_parameters(&invoice);
719
720 if !send_fee.is_within(&PaymentFee::SEND_FEE_LIMIT) {
721 return Err(SendPaymentError::GatewayFeeExceedsLimit);
722 }
723
724 if EXPIRATION_DELTA_LIMIT < expiration_delta {
725 return Err(SendPaymentError::GatewayExpirationExceedsLimit);
726 }
727
728 let consensus_block_count = self
729 .module_api
730 .consensus_block_count()
731 .await
732 .map_err(|e| SendPaymentError::FailedToRequestBlockCount(e.to_string()))?;
733
734 let contract = OutgoingContract {
735 payment_image: PaymentImage::Hash(*invoice.payment_hash()),
736 amount: send_fee.add_to(amount),
737 expiration: consensus_block_count + expiration_delta + CONTRACT_CONFIRMATION_BUFFER,
738 claim_pk: routing_info.module_public_key,
739 refund_pk: refund_keypair.public_key(),
740 ephemeral_pk,
741 };
742
743 let contract_clone = contract.clone();
744 let gateway_api_clone = gateway_api.clone();
745 let invoice_clone = invoice.clone();
746
747 let client_output = ClientOutput::<LightningOutput> {
748 output: LightningOutput::V0(LightningOutputV0::Outgoing(contract.clone())),
749 amounts: Amounts::new_bitcoin(contract.amount),
750 };
751
752 let client_output_sm = ClientOutputSM::<LightningClientStateMachines> {
753 state_machines: Arc::new(move |range: OutPointRange| {
754 vec![LightningClientStateMachines::Send(SendStateMachine {
755 common: SendSMCommon {
756 operation_id,
757 outpoint: range.into_iter().next().unwrap(),
758 contract: contract_clone.clone(),
759 gateway_api: Some(gateway_api_clone.clone()),
760 invoice: Some(LightningInvoice::Bolt11(invoice_clone.clone())),
761 refund_keypair,
762 },
763 state: SendSMState::Funding,
764 })]
765 }),
766 };
767
768 let client_output = self.client_ctx.make_client_outputs(ClientOutputBundle::new(
769 vec![client_output],
770 vec![client_output_sm],
771 ));
772
773 let transaction = TransactionBuilder::new().with_outputs(client_output);
774
775 let operation_meta_gen = move |change_outpoint_range| {
776 LightningOperationMeta::Send(SendOperationMeta {
777 change_outpoint_range,
778 gateway: gateway_api.clone(),
779 contract: contract.clone(),
780 invoice: LightningInvoice::Bolt11(invoice.clone()),
781 custom_meta: custom_meta.clone(),
782 })
783 };
784
785 self.client_ctx
787 .module_db()
788 .autocommit(
789 |dbtx, _| {
790 let operation_meta_gen = operation_meta_gen.clone();
791 let transaction = transaction.clone();
792 Box::pin(async move {
793 self.client_ctx
794 .finalize_and_submit_transaction_dbtx(
795 dbtx,
796 operation_id,
797 LightningCommonInit::KIND.as_str(),
798 operation_meta_gen,
799 transaction,
800 )
801 .await?;
802
803 self.client_ctx
804 .log_event(
805 dbtx,
806 SendPaymentEvent {
807 operation_id,
808 amount: Amount::from_msats(amount),
809 fee: send_fee.fee(amount),
810 },
811 )
812 .await;
813
814 Ok::<_, TransactionSubmitError>(())
815 })
816 },
817 Some(100),
818 )
819 .await
820 .map_err(|error| match error {
821 AutocommitError::ClosureError { error, .. } => error,
822 AutocommitError::CommitFailed { last_error, .. } => {
823 TransactionSubmitError::Database(last_error)
824 }
825 })
826 .map_err(|e| match e {
827 TransactionSubmitError::InsufficientFunds(e) => {
828 SendPaymentError::InsufficientFunds(e)
829 }
830 e => SendPaymentError::FailedToFundPayment(e.fmt_compact().to_string()),
831 })?;
832
833 Ok(operation_id)
834 }
835
836 pub async fn get_invoice_send_status(
842 &self,
843 invoice: &Bolt11Invoice,
844 ) -> Result<InvoiceSendStatus, OperationLookupError> {
845 let mut last_op = None;
850
851 for attempt in 0_u64.. {
852 let operation_id = OperationId::from_encodable(&(invoice.clone(), attempt));
853
854 if !self.client_ctx.operation_exists(operation_id).await {
855 break;
856 }
857
858 last_op = Some(operation_id);
859 }
860
861 let Some(operation_id) = last_op else {
862 return Ok(InvoiceSendStatus::NotAttempted);
863 };
864
865 if self.client_ctx.has_active_states(operation_id).await {
866 return Ok(InvoiceSendStatus::InFlight(operation_id));
867 }
868
869 let mut stream = self
872 .subscribe_send_operation_state_updates(operation_id)
873 .await?
874 .into_stream();
875
876 while let Some(state) = stream.next().await {
877 if let SendOperationState::Success(_) = state {
878 return Ok(InvoiceSendStatus::Succeeded(operation_id));
879 }
880 }
881
882 Ok(InvoiceSendStatus::Failed(operation_id))
883 }
884
885 pub async fn subscribe_send_operation_state_updates(
887 &self,
888 operation_id: OperationId,
889 ) -> Result<UpdateStreamOrOutcome<SendOperationState>, OperationLookupError> {
890 let operation = self.client_ctx.get_operation(operation_id).await?;
891 let mut stream = self.notifier.subscribe(operation_id).await;
892 let client_ctx = self.client_ctx.clone();
893 let module_api = self.module_api.clone();
894
895 Ok(self.client_ctx.outcome_or_updates(&operation, operation_id, |state| match state {
896 SendOperationState::Funding
897 | SendOperationState::Funded
898 | SendOperationState::Refunding => false,
899 SendOperationState::Success(_)
900 | SendOperationState::Refunded
901 | SendOperationState::Failure => true,
902 }, move || {
903 stream! {
904 loop {
905 if let Some(LightningClientStateMachines::Send(state)) = stream.next().await {
906 match state.state {
907 SendSMState::Funding => yield SendOperationState::Funding,
908 SendSMState::Funded => yield SendOperationState::Funded,
909 SendSMState::Success(preimage) => {
910 assert!(state.common.contract.verify_preimage(&preimage));
912
913 yield SendOperationState::Success(preimage);
914 return;
915 },
916 SendSMState::Refunding(out_points) => {
917 yield SendOperationState::Refunding;
918
919 if client_ctx.await_primary_module_outputs(operation_id, out_points.clone()).await.is_ok() {
920 yield SendOperationState::Refunded;
921 return;
922 }
923
924 if let Some(preimage) = module_api.await_preimage(
928 state.common.outpoint,
929 0
930 ).await
931 && state.common.contract.verify_preimage(&preimage) {
932 yield SendOperationState::Success(preimage);
933 return;
934 }
935
936 yield SendOperationState::Failure;
937 return;
938 },
939 SendSMState::Rejected(..) => {
940 yield SendOperationState::Failure;
941 return;
942 },
943 }
944 }
945 }
946 }
947 }))
948 }
949
950 pub async fn await_final_send_operation_state(
952 &self,
953 operation_id: OperationId,
954 ) -> Result<FinalSendOperationState, OperationLookupError> {
955 let mut stream = self
956 .subscribe_send_operation_state_updates(operation_id)
957 .await?
958 .into_stream();
959
960 let mut final_state = None;
961
962 while let Some(state) = stream.next().await {
963 match state {
964 SendOperationState::Success(preimage) => {
965 final_state = Some(FinalSendOperationState::Success(preimage));
966 }
967 SendOperationState::Refunded => {
968 final_state = Some(FinalSendOperationState::Refunded);
969 }
970 SendOperationState::Failure => final_state = Some(FinalSendOperationState::Failure),
971 _ => {}
972 }
973 }
974
975 Ok(final_state.expect("Stream contains one final state"))
976 }
977
978 pub async fn receive(
990 &self,
991 amount: Amount,
992 expiry_secs: u32,
993 description: Bolt11InvoiceDescription,
994 gateway: Option<SafeUrl>,
995 custom_meta: Value,
996 ) -> Result<(Bolt11Invoice, OperationId), ReceiveError> {
997 if MAX_INVOICE_EXPIRY_SECS < expiry_secs {
998 return Err(ReceiveError::InvoiceExpiryTooLong);
999 }
1000
1001 let (gateway, routing_info) = self.resolve_receive_gateway(gateway).await?;
1002
1003 self.receive_with_routing_info(
1004 amount,
1005 expiry_secs,
1006 description,
1007 gateway,
1008 routing_info,
1009 custom_meta,
1010 )
1011 .await
1012 }
1013
1014 pub async fn receive_with_terms(
1027 &self,
1028 amount: Amount,
1029 expiry_secs: u32,
1030 description: Bolt11InvoiceDescription,
1031 gateway: SafeUrl,
1032 receive_fee: PaymentFee,
1033 custom_meta: Value,
1034 ) -> Result<(Bolt11Invoice, OperationId), ReceiveWithTermsError> {
1035 if MAX_INVOICE_EXPIRY_SECS < expiry_secs {
1036 return Err(ReceiveError::InvoiceExpiryTooLong.into());
1037 }
1038
1039 let (gateway, routing_info) = self.resolve_receive_gateway(Some(gateway)).await?;
1040
1041 if routing_info.receive_fee != receive_fee {
1042 return Err(ReceiveWithTermsError::TermsChanged {
1043 receive_fee: routing_info.receive_fee,
1044 });
1045 }
1046
1047 let (invoice, operation_id) = self
1048 .receive_with_routing_info(
1049 amount,
1050 expiry_secs,
1051 description,
1052 gateway,
1053 routing_info,
1054 custom_meta,
1055 )
1056 .await?;
1057
1058 Ok((invoice, operation_id))
1059 }
1060
1061 async fn resolve_receive_gateway(
1065 &self,
1066 gateway: Option<SafeUrl>,
1067 ) -> Result<(SafeUrl, RoutingInfo), ReceiveError> {
1068 match gateway {
1069 Some(gateway) => {
1070 let routing_info = self
1071 .routing_info(&gateway)
1072 .await
1073 .map_err(|e| ReceiveError::FailedToConnectToGateway(e.to_string()))?
1074 .ok_or(ReceiveError::FederationNotSupported)?;
1075
1076 if !routing_info.receive_enabled {
1077 return Err(ReceiveError::ReceiveDisabled);
1078 }
1079
1080 Ok((gateway, routing_info))
1081 }
1082 None => self
1083 .select_receive_gateway()
1084 .await
1085 .map_err(ReceiveError::SelectGateway),
1086 }
1087 }
1088
1089 async fn select_receive_gateway(&self) -> Result<(SafeUrl, RoutingInfo), SelectGatewayError> {
1094 let gateways = self
1095 .module_api
1096 .gateways()
1097 .await
1098 .map_err(|e| SelectGatewayError::FailedToRequestGateways(e.to_string()))?;
1099
1100 if gateways.is_empty() {
1101 return Err(SelectGatewayError::NoGatewaysAvailable);
1102 }
1103
1104 let mut any_responded = false;
1105
1106 for gateway in gateways {
1107 if let Ok(Some(routing_info)) = self.routing_info(&gateway).await {
1108 any_responded = true;
1109
1110 if routing_info.receive_enabled {
1111 return Ok((gateway, routing_info));
1112 }
1113 }
1114 }
1115
1116 if any_responded {
1117 Err(SelectGatewayError::NoGatewayAcceptsReceives)
1118 } else {
1119 Err(SelectGatewayError::GatewaysUnresponsive)
1120 }
1121 }
1122
1123 async fn receive_with_routing_info(
1127 &self,
1128 amount: Amount,
1129 expiry_secs: u32,
1130 description: Bolt11InvoiceDescription,
1131 gateway: SafeUrl,
1132 routing_info: RoutingInfo,
1133 custom_meta: Value,
1134 ) -> Result<(Bolt11Invoice, OperationId), ReceiveError> {
1135 if !routing_info
1136 .receive_fee
1137 .is_within(&PaymentFee::RECEIVE_FEE_LIMIT)
1138 {
1139 return Err(ReceiveError::GatewayFeeExceedsLimit);
1140 }
1141
1142 let contract_amount = routing_info.receive_fee.subtract_from(amount.msats);
1143
1144 if !self.is_worth_claiming(contract_amount).await {
1148 return Err(ReceiveError::AmountTooSmall);
1149 }
1150
1151 let (contract, preimage, invoice) =
1156 util::retry("gateway-bolt11-invoice", gateway_request_backoff(), || {
1157 self.request_invoice_for_new_contract(
1158 &gateway,
1159 &routing_info,
1160 contract_amount,
1161 amount,
1162 description.clone(),
1163 expiry_secs,
1164 )
1165 })
1166 .await
1167 .map_err(|e| ReceiveError::FailedToConnectToGateway(e.to_string()))?;
1168
1169 if invoice.payment_hash() != &preimage.consensus_hash() {
1170 return Err(ReceiveError::InvalidInvoice);
1171 }
1172
1173 if invoice.amount_milli_satoshis() != Some(amount.msats) {
1174 return Err(ReceiveError::IncorrectInvoiceAmount);
1175 }
1176
1177 let operation_id = self
1178 .receive_incoming_contract(
1179 self.keypair.secret_key(),
1180 contract.clone(),
1181 LightningOperationMeta::Receive(ReceiveOperationMeta {
1182 gateway,
1183 contract,
1184 invoice: LightningInvoice::Bolt11(invoice.clone()),
1185 custom_meta,
1186 }),
1187 )
1188 .await
1189 .expect("The contract has been generated with our public key");
1190
1191 Ok((invoice, operation_id))
1192 }
1193
1194 async fn request_invoice_for_new_contract(
1197 &self,
1198 gateway: &SafeUrl,
1199 routing_info: &RoutingInfo,
1200 contract_amount: Amount,
1201 amount: Amount,
1202 description: Bolt11InvoiceDescription,
1203 expiry_secs: u32,
1204 ) -> Result<(IncomingContract, [u8; 32], Bolt11Invoice), ServerError> {
1205 let recipient_static_pk = self.keypair.public_key();
1206
1207 let (ephemeral_tweak, ephemeral_pk) = tweak::generate(recipient_static_pk);
1208
1209 let encryption_seed = ephemeral_tweak
1210 .consensus_hash::<sha256::Hash>()
1211 .to_byte_array();
1212
1213 let preimage = encryption_seed
1214 .consensus_hash::<sha256::Hash>()
1215 .to_byte_array();
1216
1217 let expiration = duration_since_epoch()
1218 .as_secs()
1219 .saturating_add(u64::from(expiry_secs));
1220
1221 let claim_pk = recipient_static_pk
1222 .mul_tweak(
1223 secp256k1::SECP256K1,
1224 &Scalar::from_be_bytes(ephemeral_tweak).expect("Within curve order"),
1225 )
1226 .expect("Tweak is valid");
1227
1228 let contract = IncomingContract::new(
1229 self.cfg.tpe_agg_pk,
1230 encryption_seed,
1231 preimage,
1232 PaymentImage::Hash(preimage.consensus_hash()),
1233 contract_amount,
1234 expiration,
1235 claim_pk,
1236 routing_info.module_public_key,
1237 ephemeral_pk,
1238 );
1239
1240 let invoice = self
1241 .gateway_conn
1242 .bolt11_invoice(
1243 gateway.clone(),
1244 self.federation_id,
1245 contract.clone(),
1246 amount,
1247 description,
1248 expiry_secs,
1249 )
1250 .await?;
1251
1252 Ok((contract, preimage, invoice))
1253 }
1254
1255 pub async fn receive_fee_quote(
1270 &self,
1271 amount: Amount,
1272 ) -> Result<FeeQuote, TransactionSubmitError> {
1273 self.client_ctx
1274 .fee_quote(
1275 OperationId::new_random(),
1276 FeeQuoteRequest {
1277 input_amount: Amounts::new_bitcoin(amount),
1278 output_amount: Amounts::ZERO,
1279 input_fee: Amounts::new_bitcoin(self.cfg.fee_consensus.fee(amount)),
1280 output_fee: Amounts::ZERO,
1281 },
1282 )
1283 .await
1284 }
1285
1286 async fn is_worth_claiming(&self, amount: Amount) -> bool {
1297 match self.receive_fee_quote(amount).await {
1298 Ok(quote) => quote.total().get_bitcoin() < amount,
1299 Err(_) => false,
1300 }
1301 }
1302
1303 pub async fn send_fee_quote(&self, amount: Amount) -> Result<FeeQuote, TransactionSubmitError> {
1319 self.client_ctx
1320 .fee_quote(
1321 OperationId::new_random(),
1322 FeeQuoteRequest {
1323 input_amount: Amounts::ZERO,
1324 output_amount: Amounts::new_bitcoin(amount),
1325 input_fee: Amounts::ZERO,
1326 output_fee: Amounts::new_bitcoin(self.cfg.fee_consensus.fee(amount)),
1327 },
1328 )
1329 .await
1330 }
1331
1332 pub async fn spendable_amount(
1369 &self,
1370 balance: Amount,
1371 gateway: Option<SafeUrl>,
1372 ) -> Result<Amount, SpendableAmountError> {
1373 let routing_info = match gateway {
1374 Some(gateway) => self
1375 .routing_info(&gateway)
1376 .await?
1377 .ok_or(SpendableAmountError::FederationNotSupported)?,
1378 None => self.select_gateway(None).await?.1,
1379 };
1380
1381 let send_fee = routing_info.send_fee_default;
1386
1387 if !send_fee.is_within(&PaymentFee::SEND_FEE_LIMIT) {
1388 return Err(SpendableAmountError::SendFeeExceedsLimit {
1389 fee: send_fee,
1390 limit: PaymentFee::SEND_FEE_LIMIT,
1391 });
1392 }
1393
1394 max_affordable_send_amount(
1395 balance,
1396 Amount::from_msats(1),
1397 balance,
1398 |invoice_amount: Amount| send_fee.add_to(invoice_amount.msats),
1399 |contract_amount: Amount| self.send_fee_quote(contract_amount),
1400 )
1401 .await
1402 .map_err(SpendableAmountError::Quote)?
1403 .ok_or(SpendableAmountError::BalanceTooLow { balance })
1404 }
1405
1406 async fn receive_incoming_contract(
1409 &self,
1410 sk: SecretKey,
1411 contract: IncomingContract,
1412 operation_meta: LightningOperationMeta,
1413 ) -> Option<OperationId> {
1414 let operation_id = OperationId::from_encodable(&contract.clone());
1415
1416 let tpe_agg_pk = self.cfg.tpe_agg_pk;
1417
1418 let (claim_keypair, agg_decryption_key) = runtime::spawn_blocking({
1419 let contract = contract.clone();
1420
1421 move || recover_contract_keys(sk, &tpe_agg_pk, &contract)
1422 })
1423 .await?;
1424
1425 let receive_sm = LightningClientStateMachines::Receive(ReceiveStateMachine {
1426 common: ReceiveSMCommon {
1427 operation_id,
1428 contract: contract.clone(),
1429 claim_keypair,
1430 agg_decryption_key,
1431 },
1432 state: ReceiveSMState::Pending,
1433 });
1434
1435 self.client_ctx
1438 .manual_operation_start(
1439 operation_id,
1440 LightningCommonInit::KIND.as_str(),
1441 operation_meta,
1442 vec![self.client_ctx.make_dyn_state(receive_sm)],
1443 )
1444 .await
1445 .ok();
1446
1447 Some(operation_id)
1448 }
1449
1450 pub async fn subscribe_receive_operation_state_updates(
1452 &self,
1453 operation_id: OperationId,
1454 ) -> Result<UpdateStreamOrOutcome<ReceiveOperationState>, OperationLookupError> {
1455 let operation = self.client_ctx.get_operation(operation_id).await?;
1456 let mut stream = self.notifier.subscribe(operation_id).await;
1457 let client_ctx = self.client_ctx.clone();
1458
1459 Ok(self.client_ctx.outcome_or_updates(&operation, operation_id, |state| match state {
1460 ReceiveOperationState::Pending | ReceiveOperationState::Claiming => false,
1461 ReceiveOperationState::Expired
1462 | ReceiveOperationState::Claimed
1463 | ReceiveOperationState::Failure
1464 | ReceiveOperationState::Uneconomical => true,
1465 }, move || {
1466 stream! {
1467 loop {
1468 if let Some(LightningClientStateMachines::Receive(state)) = stream.next().await {
1469 match state.state {
1470 ReceiveSMState::Pending => yield ReceiveOperationState::Pending,
1471 ReceiveSMState::Claiming(out_points) => {
1472 yield ReceiveOperationState::Claiming;
1473
1474 if client_ctx.await_primary_module_outputs(operation_id, out_points).await.is_ok() {
1475 yield ReceiveOperationState::Claimed;
1476 } else {
1477 yield ReceiveOperationState::Failure;
1478 }
1479 return;
1480 },
1481 ReceiveSMState::Expired => {
1482 yield ReceiveOperationState::Expired;
1483 return;
1484 }
1485 ReceiveSMState::Uneconomical => {
1486 yield ReceiveOperationState::Uneconomical;
1487 return;
1488 }
1489 }
1490 }
1491 }
1492 }
1493 }))
1494 }
1495
1496 pub async fn await_final_receive_operation_state(
1498 &self,
1499 operation_id: OperationId,
1500 ) -> Result<FinalReceiveOperationState, OperationLookupError> {
1501 let mut stream = self
1502 .subscribe_receive_operation_state_updates(operation_id)
1503 .await?
1504 .into_stream();
1505
1506 let mut final_state = None;
1507
1508 while let Some(state) = stream.next().await {
1509 match state {
1510 ReceiveOperationState::Expired => {
1511 final_state = Some(FinalReceiveOperationState::Expired);
1512 }
1513 ReceiveOperationState::Claimed => {
1514 final_state = Some(FinalReceiveOperationState::Claimed);
1515 }
1516 ReceiveOperationState::Failure => {
1517 final_state = Some(FinalReceiveOperationState::Failure);
1518 }
1519 ReceiveOperationState::Uneconomical => {
1520 final_state = Some(FinalReceiveOperationState::Uneconomical);
1521 }
1522 _ => {}
1523 }
1524 }
1525
1526 Ok(final_state.expect("Stream contains one final state"))
1527 }
1528
1529 pub async fn generate_lnurl(
1532 &self,
1533 recurringd: SafeUrl,
1534 gateway: Option<SafeUrl>,
1535 ) -> Result<String, GenerateLnurlError> {
1536 let gateways = if let Some(gateway) = gateway {
1537 vec![gateway]
1538 } else {
1539 let gateways = self
1540 .module_api
1541 .gateways()
1542 .await
1543 .map_err(|e| GenerateLnurlError::FailedToRequestGateways(e.to_string()))?;
1544
1545 if gateways.is_empty() {
1546 return Err(GenerateLnurlError::NoGatewaysAvailable);
1547 }
1548
1549 gateways
1550 };
1551
1552 let payload = fedimint_core::base32::encode_prefixed(
1553 fedimint_core::base32::FEDIMINT_PREFIX,
1554 &lnurl::LnurlRequest {
1555 federation_id: self.federation_id,
1556 recipient_pk: self.lnurl_keypair.public_key(),
1557 aggregate_pk: self.cfg.tpe_agg_pk,
1558 gateways,
1559 },
1560 );
1561
1562 Ok(fedimint_lnurl::encode_lnurl(&format!(
1563 "{recurringd}pay/{payload}"
1564 )))
1565 }
1566
1567 fn spawn_receive_lnurl_task(
1568 &self,
1569 custom_meta_fn: Arc<dyn Fn() -> Value + Send + Sync>,
1570 task_group: &TaskGroup,
1571 client_span: &tracing::Span,
1572 ) {
1573 let module = self.clone();
1574 let api = self.module_api.clone();
1575
1576 task_group.spawn_cancellable_with_span(
1577 client_span.clone(),
1578 "receive_lnurl_task",
1579 async move {
1580 api.wait_for_initialized_connections().await;
1581 loop {
1582 module.receive_lnurl(custom_meta_fn()).await;
1583 }
1584 },
1585 );
1586 }
1587
1588 async fn receive_lnurl(&self, custom_meta: Value) {
1589 let stream_index = self
1600 .client_ctx
1601 .module_db()
1602 .begin_transaction_nc()
1603 .await
1604 .get_value(&IncomingContractStreamIndexKey)
1605 .await
1606 .unwrap_or(0);
1607
1608 let (contracts, next_index) = self
1609 .module_api
1610 .await_incoming_contracts(stream_index, 128)
1611 .await;
1612
1613 for contract in &contracts {
1614 let keys = runtime::spawn_blocking({
1620 let sk = self.lnurl_keypair.secret_key();
1621 let tpe_agg_pk = self.cfg.tpe_agg_pk;
1622 let contract = contract.clone();
1623
1624 move || recover_contract_keys(sk, &tpe_agg_pk, &contract)
1625 })
1626 .await;
1627
1628 if keys.is_none() {
1629 continue;
1630 }
1631
1632 if !self.is_worth_claiming(contract.commitment.amount).await {
1633 warn!(
1634 target: LOG_CLIENT_MODULE_LNV2,
1635 amount = %contract.commitment.amount,
1636 "Ignoring incoming contract, its amount does not cover the claim fee"
1637 );
1638
1639 continue;
1640 }
1641
1642 if let Some(operation_id) = self
1643 .receive_incoming_contract(
1644 self.lnurl_keypair.secret_key(),
1645 contract.clone(),
1646 LightningOperationMeta::LnurlReceive(LnurlReceiveOperationMeta {
1647 contract: contract.clone(),
1648 custom_meta: custom_meta.clone(),
1649 }),
1650 )
1651 .await
1652 {
1653 self.await_final_receive_operation_state(operation_id)
1654 .await
1655 .ok();
1656 }
1657 }
1658
1659 let mut dbtx = self.client_ctx.module_db().begin_transaction().await;
1668
1669 dbtx.insert_entry(&IncomingContractStreamIndexKey, &next_index)
1670 .await;
1671
1672 dbtx.commit_tx().await;
1673 }
1674}
1675
1676#[derive(Error, Debug, Clone, Eq, PartialEq)]
1677pub enum SelectGatewayError {
1678 #[error("Failed to request gateways")]
1679 FailedToRequestGateways(String),
1680 #[error("No gateways are available")]
1681 NoGatewaysAvailable,
1682 #[error("All gateways failed to respond")]
1683 GatewaysUnresponsive,
1684 #[error("No online gateway currently accepts incoming payments for this federation")]
1685 NoGatewayAcceptsReceives,
1686}
1687
1688#[derive(Debug, Clone, Eq, PartialEq)]
1691pub enum InvoiceSendStatus {
1692 NotAttempted,
1694 InFlight(OperationId),
1696 Succeeded(OperationId),
1699 Failed(OperationId),
1701}
1702
1703#[derive(Error, Debug, Clone, Eq, PartialEq)]
1704pub enum SendPaymentError {
1705 #[error("Invoice is missing an amount")]
1706 InvoiceMissingAmount,
1707 #[error("Invoice has expired")]
1708 InvoiceExpired,
1709 #[error("Payment attempt is duplicate")]
1710 DuplicatePaymentAttempt(OperationId),
1711 #[error(transparent)]
1712 SelectGateway(SelectGatewayError),
1713 #[error("Failed to connect to gateway")]
1714 FailedToConnectToGateway(String),
1715 #[error("Gateway does not support this federation")]
1716 FederationNotSupported,
1717 #[error("Gateway fee exceeds the allowed limit")]
1718 GatewayFeeExceedsLimit,
1719 #[error("Gateway expiration time exceeds the allowed limit")]
1720 GatewayExpirationExceedsLimit,
1721 #[error("Failed to request block count")]
1722 FailedToRequestBlockCount(String),
1723 #[error("The client does not have sufficient funds to send the payment")]
1725 InsufficientFunds(#[source] InsufficientBalanceError),
1726 #[error("Failed to fund the payment")]
1729 FailedToFundPayment(String),
1730 #[error("Invoice is for a different currency")]
1731 WrongCurrency {
1732 invoice_currency: Currency,
1733 federation_currency: Currency,
1734 },
1735}
1736
1737#[derive(Error, Debug, Clone, Eq, PartialEq)]
1739#[non_exhaustive]
1740pub enum SendWithTermsError {
1741 #[error("Gateway's send terms changed since they were checked")]
1744 TermsChanged {
1745 send_fee: PaymentFee,
1746 expiration_delta: u64,
1747 },
1748 #[error(transparent)]
1750 Send(#[from] SendPaymentError),
1751}
1752
1753#[derive(Error, Debug, Clone, Eq, PartialEq)]
1754pub enum ReceiveError {
1755 #[error(transparent)]
1756 SelectGateway(SelectGatewayError),
1757 #[error("Failed to connect to gateway")]
1758 FailedToConnectToGateway(String),
1759 #[error("Gateway does not support this federation")]
1760 FederationNotSupported,
1761 #[error("Gateway does not currently accept incoming payments for this federation")]
1762 ReceiveDisabled,
1763 #[error("Gateway fee exceeds the allowed limit")]
1764 GatewayFeeExceedsLimit,
1765 #[error("Amount is too small to cover fees")]
1766 AmountTooSmall,
1767 #[error("Gateway returned an invalid invoice")]
1768 InvalidInvoice,
1769 #[error("Gateway returned an invoice with incorrect amount")]
1770 IncorrectInvoiceAmount,
1771 #[error("Requested invoice expiry exceeds the maximum of one day")]
1772 InvoiceExpiryTooLong,
1773}
1774
1775#[derive(Error, Debug, Clone, Eq, PartialEq)]
1777#[non_exhaustive]
1778pub enum ReceiveWithTermsError {
1779 #[error("Gateway's receive fee changed since it was checked")]
1782 TermsChanged { receive_fee: PaymentFee },
1783 #[error(transparent)]
1785 Receive(#[from] ReceiveError),
1786}
1787
1788#[derive(Error, Debug, Clone, Eq, PartialEq)]
1789pub enum GenerateLnurlError {
1790 #[error("No gateways are available")]
1791 NoGatewaysAvailable,
1792 #[error("Failed to request gateways")]
1793 FailedToRequestGateways(String),
1794}
1795
1796#[derive(Error, Debug, Clone, Eq, PartialEq)]
1797pub enum ListGatewaysError {
1798 #[error("Failed to request gateways")]
1799 FailedToListGateways,
1800}
1801
1802#[derive(Error, Debug, Clone, Eq, PartialEq)]
1803pub enum RoutingInfoError {
1804 #[error("Failed to request routing info")]
1805 FailedToRequestRoutingInfo,
1806}
1807
1808#[derive(Debug, Error)]
1816#[non_exhaustive]
1817pub enum SpendableAmountError {
1818 #[error(transparent)]
1821 RoutingInfo(#[from] RoutingInfoError),
1822
1823 #[error("The gateway does not support this federation")]
1826 FederationNotSupported,
1827
1828 #[error(transparent)]
1831 SelectGateway(#[from] SelectGatewayError),
1832
1833 #[error("The gateway's default send fee {fee} exceeds the limit {limit}")]
1836 SendFeeExceedsLimit {
1837 fee: PaymentFee,
1839 limit: PaymentFee,
1841 },
1842
1843 #[error("The fee quote for the payment failed")]
1845 Quote(#[source] TransactionSubmitError),
1846
1847 #[error("The balance {balance} is too low to send any amount after fees")]
1850 BalanceTooLow {
1851 balance: Amount,
1853 },
1854}
1855
1856#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
1857pub enum LightningClientStateMachines {
1858 Send(SendStateMachine),
1859 Receive(ReceiveStateMachine),
1860}
1861
1862impl IntoDynInstance for LightningClientStateMachines {
1863 type DynType = DynState;
1864
1865 fn into_dyn(self, instance_id: ModuleInstanceId) -> Self::DynType {
1866 DynState::from_typed(instance_id, self)
1867 }
1868}
1869
1870impl State for LightningClientStateMachines {
1871 type ModuleContext = LightningClientContext;
1872
1873 fn transitions(
1874 &self,
1875 context: &Self::ModuleContext,
1876 global_context: &DynGlobalClientContext,
1877 ) -> Vec<StateTransition<Self>> {
1878 match self {
1879 LightningClientStateMachines::Send(state) => {
1880 sm_enum_variant_translation!(
1881 state.transitions(context, global_context),
1882 LightningClientStateMachines::Send
1883 )
1884 }
1885 LightningClientStateMachines::Receive(state) => {
1886 sm_enum_variant_translation!(
1887 state.transitions(context, global_context),
1888 LightningClientStateMachines::Receive
1889 )
1890 }
1891 }
1892 }
1893
1894 fn operation_id(&self) -> OperationId {
1895 match self {
1896 LightningClientStateMachines::Send(state) => state.operation_id(),
1897 LightningClientStateMachines::Receive(state) => state.operation_id(),
1898 }
1899 }
1900}
1901
1902fn recover_contract_keys(
1908 sk: SecretKey,
1909 tpe_agg_pk: &AggregatePublicKey,
1910 contract: &IncomingContract,
1911) -> Option<(Keypair, AggregateDecryptionKey)> {
1912 let tweak = ecdh::SharedSecret::new(&contract.commitment.ephemeral_pk, &sk);
1913
1914 let encryption_seed = tweak
1915 .secret_bytes()
1916 .consensus_hash::<sha256::Hash>()
1917 .to_byte_array();
1918
1919 let claim_keypair = sk
1920 .mul_tweak(&Scalar::from_be_bytes(tweak.secret_bytes()).expect("Within curve order"))
1921 .expect("Tweak is valid")
1922 .keypair(secp256k1::SECP256K1);
1923
1924 if claim_keypair.public_key() != contract.commitment.claim_pk {
1925 return None; }
1927
1928 let agg_decryption_key = derive_agg_dk(tpe_agg_pk, &encryption_seed);
1929
1930 if !contract.verify_agg_decryption_key(tpe_agg_pk, &agg_decryption_key) {
1931 return None; }
1933
1934 contract.decrypt_preimage(&agg_decryption_key)?;
1935
1936 Some((claim_keypair, agg_decryption_key))
1937}