Skip to main content

fedimint_lnv2_client/
lib.rs

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
80/// Number of blocks until outgoing lightning contracts times out and user
81/// client can refund it unilaterally
82const EXPIRATION_DELTA_LIMIT: u64 = 1440;
83
84/// A two hour buffer in case either the client or gateway go offline
85const CONTRACT_CONFIRMATION_BUFFER: u64 = 12;
86
87/// Backoff for a gateway request made while the user waits: three retries,
88/// with about two seconds of waiting between them in total. The requests
89/// themselves are not bounded by this.
90fn 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    /// Calculate the absolute fee paid to the gateway on success.
117    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    /// Calculate the absolute fee paid to the gateway on success.
136    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/// The state of an operation sending a payment over lightning.
153///
154/// ```mermaid
155/// graph LR
156/// classDef virtual fill:#fff,stroke-dasharray: 5 5
157///
158///     Funding -- funding transaction is rejected --> Rejected
159///     Funding -- funding transaction is accepted --> Funded
160///     Funded -- payment is confirmed  --> Success
161///     Funded -- payment attempt expires --> Refunding
162///     Funded -- gateway cancels payment attempt --> Refunding
163///     Refunding -- payment is confirmed --> Success
164///     Refunding -- ecash is minted --> Refunded
165///     Refunding -- minting ecash fails --> Failure
166/// ```
167/// The transition from Refunding to Success is only possible if the gateway
168/// misbehaves.
169#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
170pub enum SendOperationState {
171    /// We are funding the contract to incentivize the gateway.
172    Funding,
173    /// We are waiting for the gateway to complete the payment.
174    Funded,
175    /// The payment was successful.
176    Success([u8; 32]),
177    /// The payment has failed and we are refunding the contract.
178    Refunding,
179    /// The payment has been refunded.
180    Refunded,
181    /// Either a programming error has occurred or the federation is malicious.
182    Failure,
183}
184
185/// The final state of an operation sending a payment over lightning.
186#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
187pub enum FinalSendOperationState {
188    /// The payment was successful. Carries the payment preimage proving
189    /// the gateway settled the invoice, serialized as a lowercase hex string.
190    Success(#[serde(with = "fedimint_core::hex::serde")] [u8; 32]),
191    /// The payment has been refunded.
192    Refunded,
193    /// Either a programming error has occurred or the federation is malicious.
194    Failure,
195}
196
197pub type SendResult = Result<OperationId, SendPaymentError>;
198
199/// The state of an operation receiving a payment over lightning.
200///
201/// ```mermaid
202/// graph LR
203/// classDef virtual fill:#fff,stroke-dasharray: 5 5
204///
205///     Pending -- payment is confirmed --> Claiming
206///     Pending -- invoice expires --> Expired
207///     Claiming -- ecash is minted --> Claimed
208///     Claiming -- minting ecash fails --> Failure
209/// ```
210#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
211pub enum ReceiveOperationState {
212    /// We are waiting for the payment.
213    Pending,
214    /// The payment request has expired.
215    Expired,
216    /// The payment has been confirmed and we are issuing the ecash.
217    Claiming,
218    /// The payment has been successful.
219    Claimed,
220    /// Either a programming error has occurred or the federation is malicious.
221    Failure,
222    /// The contract is worth less than the federation charges to claim it, so
223    /// it was left unclaimed. Reachable without any payment request of ours:
224    /// anyone can address an incoming contract to a published lnurl key.
225    Uneconomical,
226}
227
228/// The final state of an operation receiving a payment over lightning.
229#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
230pub enum FinalReceiveOperationState {
231    /// The payment request has expired.
232    Expired,
233    /// The payment has been successful.
234    Claimed,
235    /// Either a programming error has occurred or the federation is malicious.
236    Failure,
237    /// The contract is worth less than the federation charges to claim it, so
238    /// it was left unclaimed.
239    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)] // The field is only used by the cli feature
349    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        // Update the mapping from lightning node public keys to gateway api
453        // endpoints maintained in the module database. When paying an invoice this
454        // enables the client to select the gateway that has created the invoice,
455        // if possible, such that the payment does not go over lightning, reducing
456        // fees and latency.
457
458        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    /// Selects an available gateway by querying the federation's registered
479    /// gateways, checking if one of them match the invoice's payee public
480    /// key, then queries the gateway for `RoutingInfo` to determine if it is
481    /// online.
482    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    /// Sends a request to each peer for their registered gateway list and
520    /// returns a `Vec<SafeUrl` of all registered gateways to the client.
521    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    /// Requests the `RoutingInfo`, including fee information, from the gateway
539    /// available at the `SafeUrl`.
540    ///
541    /// A failed request is retried a few times, so that one dropped or slow
542    /// request does not make the gateway look offline. The request is a read,
543    /// so retrying it is safe.
544    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    /// Pay an invoice. For testing you can optionally specify a gateway to
557    /// route with, otherwise a gateway will be selected automatically. If the
558    /// invoice was created by a gateway connected to our federation, the same
559    /// gateway will be selected to allow for a direct ecash swap. Otherwise we
560    /// select a random online gateway.
561    ///
562    /// The fee for this payment may depend on the selected gateway but
563    /// will be limited to one and a half percent plus one hundred satoshis.
564    /// This fee accounts for the fee charged by the gateway as well as
565    /// the additional fee required to reliably route this payment over
566    /// lightning if necessary. Since the gateway has been vetted by at least
567    /// one guardian we trust it to set a reasonable fee and only enforce a
568    /// rather high limit.
569    ///
570    /// The absolute fee for a payment can be calculated from the operation meta
571    /// to be shown to the user in the transaction history.
572    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    /// Pays `invoice` through `gateway` at the terms the caller already
594    /// checked.
595    ///
596    /// [`Self::send`] reads the gateway's terms itself, so a caller that showed
597    /// the user a fee and asked for approval has no guarantee the funded
598    /// contract carries that fee: the gateway may change its schedule between
599    /// the two reads. This variant takes the `send_fee` and `expiration_delta`
600    /// the caller obtained from [`RoutingInfo::send_parameters`] and refuses
601    /// with [`SendWithTermsError::TermsChanged`], before funding anything, if
602    /// the gateway currently reports different terms. A cheaper fee counts
603    /// as changed too, so the funded contract always matches what was
604    /// approved. This binds the funded contract to the approved terms, not
605    /// the gateway's acceptance: a gateway that raises its schedule after the
606    /// check can still refuse the contract, in which case the payment is
607    /// refunded. The error carries the current terms for re-quoting.
608    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    /// Checks that `invoice` is payable by this client and has not been
645    /// attempted before, returning its amount in millisatoshis and the
646    /// operation id a payment of it uses.
647    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        // The attempt index is fixed at `0` so the operation id matches the one
667        // older clients derived for the first payment attempt, ensuring an
668        // already-paid or in-flight invoice is still detected after an upgrade.
669        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    /// Resolves the gateway to pay `invoice` through and its current routing
679    /// info: the given one, or an automatically selected one when `None`.
680    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    /// Funds an outgoing contract for `invoice` at the terms in `routing_info`
701    /// and starts the state machine that hands it to `gateway_api`.
702    #[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        // The operation and the event announcing it must survive a restart together.
786        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    /// The status of a previous [`Self::send`] for this invoice.
837    ///
838    /// Callers deciding whether an invoice is safe to pay through another
839    /// mechanism must treat anything but [`InvoiceSendStatus::NotAttempted`]
840    /// as a potential double payment.
841    pub async fn get_invoice_send_status(
842        &self,
843        invoice: &Bolt11Invoice,
844    ) -> Result<InvoiceSendStatus, OperationLookupError> {
845        // Send only creates attempt index 0 nowadays, but older clients
846        // allocated a fresh index per retry, so scan for the latest attempt.
847        // No new attempt was ever allocated after a success, so the latest
848        // attempt alone determines the status.
849        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        // The operation is finished; replaying its (already terminated) update
870        // stream yields the cached outcome without blocking.
871        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    /// Subscribe to all state updates of the send operation.
886    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                                // the preimage has been verified by the state machine previously
911                                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                                // The gateway may have incorrectly claimed the outgoing contract thereby causing
925                                // our refund transaction to be rejected. Therefore, we check one last time if
926                                // the preimage is available before we enter the failure state.
927                                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    /// Await the final state of the send operation.
951    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    /// Request an invoice. For testing you can optionally specify a gateway to
979    /// generate the invoice, otherwise a random online gateway will be selected
980    /// automatically.
981    ///
982    /// The total fee for this payment may depend on the chosen gateway but
983    /// will be limited to half of one percent plus fifty satoshis. Since the
984    /// selected gateway has been vetted by at least one guardian we trust it to
985    /// set a reasonable fee and only enforce a rather high limit.
986    ///
987    /// The absolute fee for a payment can be calculated from the operation meta
988    /// to be shown to the user in the transaction history.
989    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    /// Requests an invoice from `gateway` at the receive fee the caller
1015    /// already checked.
1016    ///
1017    /// [`Self::receive`] reads the gateway's fee itself, so a caller that
1018    /// showed the user a fee has no guarantee the incoming contract is
1019    /// created at that fee: the gateway may change its schedule between the
1020    /// two reads. This variant takes the `receive_fee` the caller obtained
1021    /// from [`RoutingInfo::receive_fee`] and refuses with
1022    /// [`ReceiveWithTermsError::TermsChanged`], before creating anything, if
1023    /// the gateway currently reports a different fee. A cheaper fee counts as
1024    /// changed too, so the contract always matches what was approved; the
1025    /// error carries the current fee for re-quoting.
1026    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    /// Resolves the gateway to request an invoice from and its current
1062    /// routing info: the given one, or an automatically selected one when
1063    /// `None`.
1064    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    /// Selects the first registered gateway that is online and currently
1090    /// accepts incoming payments for this federation. A gateway that answers
1091    /// but has turned receives off is skipped rather than handed an invoice
1092    /// request it would refuse.
1093    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    /// Creates the incoming contract locked to a public key derived from our
1124    /// static module public key, fetches its invoice from `gateway` at the
1125    /// terms in `routing_info`, then starts the receive operation.
1126    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        // Quoting the claim against this federation's fee consensus is exact, where a
1145        // fixed floor is either too permissive or too strict depending on how the
1146        // federation is configured.
1147        if !self.is_worth_claiming(contract_amount).await {
1148            return Err(ReceiveError::AmountTooSmall);
1149        }
1150
1151        // The gateway registers each payment hash once, so a request whose
1152        // response was lost cannot be repeated with the same contract. Each
1153        // attempt creates a new contract instead. Nothing is stored before the
1154        // invoice arrives, and the gateway lets an unused registration expire.
1155        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    /// Creates a new incoming contract locked to a public key derived from
1195    /// our static module public key and requests its invoice from `gateway`.
1196    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    /// Computes the federation fee a `receive` of `amount` would incur, without
1256    /// submitting anything.
1257    ///
1258    /// When the incoming contract is claimed, the client submits a transaction
1259    /// with a single Lightning input worth the contract amount; the primary
1260    /// module balances it by minting the change credited to the wallet. This
1261    /// quotes the fee of that transaction — the Lightning input fee, the mint
1262    /// output fees, and any sub-denomination dust — via the shared,
1263    /// module-agnostic fee quote.
1264    ///
1265    /// The gateway's off-chain Lightning fee is deliberately excluded: this is
1266    /// only the fee of the on-federation transaction. For that reason the quote
1267    /// is taken on `amount` directly (rather than the gateway-reduced contract
1268    /// amount), and no gateway round-trip is needed.
1269    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    /// Whether an incoming contract worth `amount` is worth claiming, i.e.
1287    /// whether claiming it would leave the wallet better off than leaving it.
1288    ///
1289    /// This is the computed counterpart of a fixed dust limit: it prices the
1290    /// actual claim - the lightning input fee at this federation's fee
1291    /// consensus, the change the primary module has to mint, and the
1292    /// sub-denomination remainder that cannot be minted at all - rather than
1293    /// assuming a floor. A quote that fails outright is the same verdict: the
1294    /// claim spends the contract as the transaction's only input, so a fee
1295    /// larger than the contract leaves a transaction that cannot be balanced.
1296    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    /// Computes the federation fee a `send` funding an outgoing contract worth
1304    /// `amount` would incur, without submitting anything.
1305    ///
1306    /// When a payment is sent, the client submits a transaction with a single
1307    /// Lightning output (the outgoing contract) worth `amount`; the primary
1308    /// module balances it by spending ecash to fund the contract and minting
1309    /// any change. This quotes the fee of that transaction — the Lightning
1310    /// output fee, the mint input fees on the funding notes, any mint change
1311    /// output fees, and sub-denomination dust — via the shared, module-agnostic
1312    /// fee quote.
1313    ///
1314    /// The gateway's off-chain Lightning fee is deliberately excluded: it is
1315    /// part of the contract `amount` the gateway claims, not the on-federation
1316    /// transaction fee. So `amount` is the full outgoing contract value
1317    /// (`send_fee.add_to(invoice_amount)`).
1318    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    /// Computes the largest invoice amount the client can pay in full out of
1333    /// `balance`, i.e. the amount to request an invoice for in order to spend
1334    /// (close to) the entire balance.
1335    ///
1336    /// Paying an invoice deducts two kinds of fee from the balance:
1337    /// - the *gateway* fee, which is added on top of the invoice amount to form
1338    ///   the outgoing contract (`send_fee.add_to(invoice_amount)`), and
1339    /// - the *federation* fee of funding that contract — the Lightning output
1340    ///   fee, the mint input fees on the funding notes, the mint output fees on
1341    ///   any change, and sub-denomination dust — as quoted by
1342    ///   [`Self::send_fee_quote`].
1343    ///
1344    /// `balance` is the client's current Bitcoin balance (e.g. from
1345    /// `Client::get_balance_for_btc`). `gateway` optionally pins the gateway
1346    /// whose fee schedule to use; if `None` one is selected automatically, the
1347    /// same way [`Self::send`] does when no gateway is given. The gateway's
1348    /// *default* send fee is used — the higher of its two send fees, applied to
1349    /// a Lightning swap rather than a direct fedimint-to-fedimint swap — so the
1350    /// returned amount stays payable even when the eventual invoice is routed
1351    /// over Lightning.
1352    ///
1353    /// The maximum payable amount is found by binary search over the real fee
1354    /// quote (see [`max_affordable_send_amount`]) rather than a closed form,
1355    /// because the federation fee is stepwise in the amount. The quote is
1356    /// point-in-time and moves with the balance, exactly like
1357    /// [`Self::send_fee_quote`]; the eventual [`Self::send`] remains the source
1358    /// of truth and may still fail if balance or gateway state changes in
1359    /// between.
1360    ///
1361    /// Returns [`SpendableAmountError::BalanceTooLow`] if the balance cannot
1362    /// cover even the smallest payable amount plus fees, and
1363    /// [`SpendableAmountError::Quote`] if the fee probe itself failed; only
1364    /// the first of the two says the wallet is short. Any LNURL
1365    /// `minSendable`/`maxSendable` bounds are the caller's responsibility to
1366    /// apply. The remaining variants of [`SpendableAmountError`] are
1367    /// gateway-side, and none of them means the wallet is short.
1368    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        // The default (Lightning-swap) send fee is the higher of the gateway's
1382        // two send fees, so using it keeps the result payable even if the
1383        // eventual invoice is routed over Lightning instead of settled by a
1384        // direct swap.
1385        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    // Receive an incoming contract locked to a public key derived from our
1407    // static module public key.
1408    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        // this may only fail if the operation id is already in use, in which case we
1436        // ignore the error such that the method is idempotent
1437        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    /// Subscribe to all state updates of the receive operation.
1451    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    /// Await the final state of the receive operation.
1497    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    /// Generate an lnurl for the client. You can optionally specify a gateway
1530    /// to use for testing purposes.
1531    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        // Read the stream cursor with a short-lived transaction. It must NOT stay open
1590        // across the long-poll below: RocksDB's optimistic transactions validate a
1591        // commit against bounded memtable history, so a transaction held open
1592        // for minutes fails with `DatabaseError::SnapshotTooOld` once enough
1593        // concurrent writes flush that history — not because anything conflicted,
1594        // but because the backend can no longer tell — and the panicking
1595        // `commit_tx()` then killed this task permanently, silently
1596        // stalling every future receive for the lifetime of the process. Long-lived
1597        // clients (daemons) hit this reproducibly under concurrent lnv2 activity.
1598        // See <https://github.com/fedimint/fedimint/issues/8872>.
1599        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            // The stream carries every incoming contract the federation funded, and
1615            // anyone can address one to a published lnurl key. Check that it is ours
1616            // before quoting - recovering the keys is local arithmetic, the quote
1617            // reads the wallet - and skip the contracts the claim fee would swallow,
1618            // so that unsolicited dust never becomes an operation in the first place.
1619            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        // Advance the cursor in its own short transaction. This is the only writer of
1660        // this key and it runs in a single sequential loop, so there is no concurrent
1661        // writer to guard against; and because this transaction is short-lived — opened
1662        // after the long-poll and committed immediately — it cannot hit the
1663        // `SnapshotTooOld` failure that a transaction held open across the long-poll
1664        // would, so a plain `commit_tx()` is safe. Ordering is unchanged: the cursor
1665        // only moves after the batch above was processed, and a crash in between
1666        // re-fetches the same batch on the next iteration.
1667        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/// The status of the latest send attempt for an invoice, derived from the
1689/// operation log.
1690#[derive(Debug, Clone, Eq, PartialEq)]
1691pub enum InvoiceSendStatus {
1692    /// No payment operation exists for this invoice.
1693    NotAttempted,
1694    /// A payment operation is still being driven to completion.
1695    InFlight(OperationId),
1696    /// The payment succeeded; paying the invoice again would be a double
1697    /// payment.
1698    Succeeded(OperationId),
1699    /// The payment failed and any funds were refunded.
1700    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    /// The client's balance cannot fund the payment and its fees.
1724    #[error("The client does not have sufficient funds to send the payment")]
1725    InsufficientFunds(#[source] InsufficientBalanceError),
1726    /// The funding transaction could not be submitted for a reason that is
1727    /// not about the balance.
1728    #[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/// A failure of [`LightningClientModule::send_with_terms`].
1738#[derive(Error, Debug, Clone, Eq, PartialEq)]
1739#[non_exhaustive]
1740pub enum SendWithTermsError {
1741    /// The gateway's current send terms differ from the ones the caller
1742    /// checked. Carries the current terms so the caller can re-quote.
1743    #[error("Gateway's send terms changed since they were checked")]
1744    TermsChanged {
1745        send_fee: PaymentFee,
1746        expiration_delta: u64,
1747    },
1748    /// Any failure [`LightningClientModule::send`] can report.
1749    #[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/// A failure of [`LightningClientModule::receive_with_terms`].
1776#[derive(Error, Debug, Clone, Eq, PartialEq)]
1777#[non_exhaustive]
1778pub enum ReceiveWithTermsError {
1779    /// The gateway's current receive fee differs from the one the caller
1780    /// checked. Carries the current fee so the caller can re-quote.
1781    #[error("Gateway's receive fee changed since it was checked")]
1782    TermsChanged { receive_fee: PaymentFee },
1783    /// Any failure [`LightningClientModule::receive`] can report.
1784    #[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/// A failure to work out the largest invoice amount the client could pay in
1809/// full.
1810///
1811/// The answer depends on a gateway's fee schedule as well as on the balance,
1812/// so it can be missing either because no schedule could be obtained or
1813/// because the balance does not reach the smallest payable amount once both
1814/// fees are applied.
1815#[derive(Debug, Error)]
1816#[non_exhaustive]
1817pub enum SpendableAmountError {
1818    /// The caller named a gateway and its routing information could not be
1819    /// fetched, so there is no fee schedule to compute against.
1820    #[error(transparent)]
1821    RoutingInfo(#[from] RoutingInfoError),
1822
1823    /// The caller named a gateway and it answered, but it does not serve this
1824    /// federation.
1825    #[error("The gateway does not support this federation")]
1826    FederationNotSupported,
1827
1828    /// The caller named no gateway and none could be picked automatically, so
1829    /// there is no fee schedule to compute against.
1830    #[error(transparent)]
1831    SelectGateway(#[from] SelectGatewayError),
1832
1833    /// The gateway's default send fee is above the limit this module accepts,
1834    /// so an amount computed against it would not be payable through it.
1835    #[error("The gateway's default send fee {fee} exceeds the limit {limit}")]
1836    SendFeeExceedsLimit {
1837        /// The default send fee the gateway announced.
1838        fee: PaymentFee,
1839        /// The largest default send fee this module accepts.
1840        limit: PaymentFee,
1841    },
1842
1843    /// The fee probe failed for a reason unrelated to the balance.
1844    #[error("The fee quote for the payment failed")]
1845    Quote(#[source] TransactionSubmitError),
1846
1847    /// The balance cannot cover the smallest payable amount plus the gateway
1848    /// and federation fees, so there is no amount to send.
1849    #[error("The balance {balance} is too low to send any amount after fees")]
1850    BalanceTooLow {
1851        /// The balance the answer was computed against.
1852        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
1902/// The claim keypair and aggregate decryption key of an incoming contract
1903/// addressed to `sk`, or none when it is not ours.
1904///
1905/// Verifying the key is four pairings, so callers run this off the async
1906/// workers.
1907fn 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; // The claim key is not derived from our pk
1926    }
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; // The decryption key is not derived from our pk
1932    }
1933
1934    contract.decrypt_preimage(&agg_decryption_key)?;
1935
1936    Some((claim_keypair, agg_decryption_key))
1937}