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::secret::DeriveableSecretClientExt;
35use fedimint_client_module::sm::{Context, DynState, ModuleNotifier, State, StateTransition};
36use fedimint_client_module::transaction::{
37    ClientOutput, ClientOutputBundle, ClientOutputSM, FeeQuote, FeeQuoteRequest,
38    TransactionBuilder, max_affordable_send_amount,
39};
40use fedimint_client_module::{DynGlobalClientContext, sm_enum_variant_translation};
41use fedimint_core::bolt11::{currency_for_network, currency_matches_network};
42use fedimint_core::config::FederationId;
43use fedimint_core::core::{Account, IntoDynInstance, ModuleInstanceId, ModuleKind, OperationId};
44use fedimint_core::db::{DatabaseTransaction, IDatabaseTransactionOpsCoreTyped};
45use fedimint_core::encoding::{Decodable, Encodable};
46use fedimint_core::module::{
47    AmountUnit, Amounts, ApiAuth, ApiVersion, CommonModuleInit, ModuleCommon, ModuleInit,
48    MultiApiVersion,
49};
50use fedimint_core::secp256k1::SECP256K1;
51use fedimint_core::task::TaskGroup;
52use fedimint_core::time::duration_since_epoch;
53use fedimint_core::util::backoff_util::{self, custom_backoff};
54use fedimint_core::util::{self as util, FmtCompact as _, SafeUrl};
55use fedimint_core::{Amount, PeerId, apply, async_trait_maybe_send, runtime};
56use fedimint_derive_secret::{ChildId, DerivableSecret};
57use fedimint_lnv2_common::config::LightningClientConfig;
58use fedimint_lnv2_common::contracts::{IncomingContract, OutgoingContract, PaymentImage};
59use fedimint_lnv2_common::gateway_api::{
60    GatewayConnection, MAX_INVOICE_EXPIRY_SECS, PaymentFee, RealGatewayConnection, RoutingInfo,
61};
62use fedimint_lnv2_common::{
63    Bolt11InvoiceDescription, GatewayApi, KIND, LightningCommonInit, LightningInvoice,
64    LightningModuleTypes, LightningOutput, LightningOutputV0, lnurl, tweak,
65};
66use fedimint_logging::LOG_CLIENT_MODULE_LNV2;
67use futures::StreamExt;
68use lightning_invoice::{Bolt11Invoice, Currency};
69use secp256k1::{Keypair, Scalar, SecretKey, ecdh};
70use serde::{Deserialize, Serialize};
71use serde_json::Value;
72use strum::IntoEnumIterator as _;
73use thiserror::Error;
74use tpe::{AggregateDecryptionKey, AggregatePublicKey, derive_agg_dk};
75use tracing::warn;
76
77use crate::api::LightningFederationApi;
78use crate::events::SendPaymentEvent;
79use crate::htlc::{CreateHtlcOperationMeta, SpendHtlcOperationMeta};
80use crate::receive_sm::{ReceiveSMCommon, ReceiveSMState, ReceiveStateMachine};
81use crate::send_sm::{SendSMCommon, SendSMState, SendStateMachine};
82
83/// Number of blocks until outgoing lightning contracts times out and user
84/// client can refund it unilaterally
85const EXPIRATION_DELTA_LIMIT: u64 = 1440;
86
87/// A two hour buffer in case either the client or gateway go offline
88const CONTRACT_CONFIRMATION_BUFFER: u64 = 12;
89
90/// Backoff for a gateway request made while the user waits: three retries,
91/// with about two seconds of waiting between them in total. The requests
92/// themselves are not bounded by this.
93fn gateway_request_backoff() -> backoff_util::FibonacciBackoff {
94    custom_backoff(Duration::from_millis(250), Duration::from_secs(1), Some(3))
95}
96
97#[allow(clippy::large_enum_variant)]
98#[derive(Debug, Clone, Serialize, Deserialize)]
99pub enum LightningOperationMeta {
100    Send(SendOperationMeta),
101    Receive(ReceiveOperationMeta),
102    LnurlReceive(LnurlReceiveOperationMeta),
103    CreateHtlc(CreateHtlcOperationMeta),
104    ClaimHtlc(SpendHtlcOperationMeta),
105    RefundHtlc(SpendHtlcOperationMeta),
106    CancelHtlc(SpendHtlcOperationMeta),
107}
108
109#[derive(Debug, Clone, Serialize, Deserialize)]
110pub struct SendOperationMeta {
111    pub change_outpoint_range: OutPointRange,
112    pub gateway: SafeUrl,
113    pub contract: OutgoingContract,
114    pub invoice: LightningInvoice,
115    pub custom_meta: Value,
116}
117
118impl SendOperationMeta {
119    /// Calculate the absolute fee paid to the gateway on success.
120    pub fn gateway_fee(&self) -> Amount {
121        match &self.invoice {
122            LightningInvoice::Bolt11(invoice) => self.contract.amount.saturating_sub(
123                Amount::from_msats(invoice.amount_milli_satoshis().expect("Invoice has amount")),
124            ),
125        }
126    }
127}
128
129#[derive(Debug, Clone, Serialize, Deserialize)]
130pub struct ReceiveOperationMeta {
131    pub gateway: SafeUrl,
132    pub contract: IncomingContract,
133    pub invoice: LightningInvoice,
134    pub custom_meta: Value,
135}
136
137impl ReceiveOperationMeta {
138    /// Calculate the absolute fee paid to the gateway on success.
139    pub fn gateway_fee(&self) -> Amount {
140        match &self.invoice {
141            LightningInvoice::Bolt11(invoice) => {
142                Amount::from_msats(invoice.amount_milli_satoshis().expect("Invoice has amount"))
143                    .saturating_sub(self.contract.commitment.amount)
144            }
145        }
146    }
147}
148
149#[derive(Debug, Clone, Serialize, Deserialize)]
150pub struct LnurlReceiveOperationMeta {
151    pub contract: IncomingContract,
152    pub custom_meta: Value,
153}
154
155/// The state of an operation sending a payment over lightning.
156///
157/// ```mermaid
158/// graph LR
159/// classDef virtual fill:#fff,stroke-dasharray: 5 5
160///
161///     Funding -- funding transaction is rejected --> Rejected
162///     Funding -- funding transaction is accepted --> Funded
163///     Funded -- payment is confirmed  --> Success
164///     Funded -- payment attempt expires --> Refunding
165///     Funded -- gateway cancels payment attempt --> Refunding
166///     Refunding -- payment is confirmed --> Success
167///     Refunding -- ecash is minted --> Refunded
168///     Refunding -- minting ecash fails --> Failure
169/// ```
170/// The transition from Refunding to Success is only possible if the gateway
171/// misbehaves.
172#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
173pub enum SendOperationState {
174    /// We are funding the contract to incentivize the gateway.
175    Funding,
176    /// We are waiting for the gateway to complete the payment.
177    Funded,
178    /// The payment was successful.
179    Success([u8; 32]),
180    /// The payment has failed and we are refunding the contract.
181    Refunding,
182    /// The payment has been refunded.
183    Refunded,
184    /// Either a programming error has occurred or the federation is malicious.
185    Failure,
186}
187
188/// The final state of an operation sending a payment over lightning.
189#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
190pub enum FinalSendOperationState {
191    /// The payment was successful. Carries the payment preimage proving
192    /// the gateway settled the invoice, serialized as a lowercase hex string.
193    Success(#[serde(with = "fedimint_core::hex::serde")] [u8; 32]),
194    /// The payment has been refunded.
195    Refunded,
196    /// Either a programming error has occurred or the federation is malicious.
197    Failure,
198}
199
200pub type SendResult = Result<OperationId, SendPaymentError>;
201
202/// The state of an operation receiving a payment over lightning.
203///
204/// ```mermaid
205/// graph LR
206/// classDef virtual fill:#fff,stroke-dasharray: 5 5
207///
208///     Pending -- payment is confirmed --> Claiming
209///     Pending -- invoice expires --> Expired
210///     Claiming -- ecash is minted --> Claimed
211///     Claiming -- minting ecash fails --> Failure
212/// ```
213#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
214pub enum ReceiveOperationState {
215    /// We are waiting for the payment.
216    Pending,
217    /// The payment request has expired.
218    Expired,
219    /// The payment has been confirmed and we are issuing the ecash.
220    Claiming,
221    /// The payment has been successful.
222    Claimed,
223    /// Either a programming error has occurred or the federation is malicious.
224    Failure,
225    /// The contract is worth less than the federation charges to claim it, so
226    /// it was left unclaimed. Reachable without any payment request of ours:
227    /// anyone can address an incoming contract to a published lnurl key.
228    Uneconomical,
229}
230
231/// The final state of an operation receiving a payment over lightning.
232#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
233pub enum FinalReceiveOperationState {
234    /// The payment request has expired.
235    Expired,
236    /// The payment has been successful.
237    Claimed,
238    /// Either a programming error has occurred or the federation is malicious.
239    Failure,
240    /// The contract is worth less than the federation charges to claim it, so
241    /// it was left unclaimed.
242    Uneconomical,
243}
244
245pub type ReceiveResult = Result<(Bolt11Invoice, OperationId), ReceiveError>;
246
247#[derive(Clone)]
248pub struct LightningClientInit {
249    pub gateway_conn: Option<Arc<dyn GatewayConnection + Send + Sync>>,
250    pub custom_meta_fn: Arc<dyn Fn() -> Value + Send + Sync>,
251}
252
253impl std::fmt::Debug for LightningClientInit {
254    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
255        f.debug_struct("LightningClientInit")
256            .field("gateway_conn", &self.gateway_conn)
257            .field("custom_meta_fn", &"<function>")
258            .finish()
259    }
260}
261
262impl Default for LightningClientInit {
263    fn default() -> Self {
264        LightningClientInit {
265            gateway_conn: None,
266            custom_meta_fn: Arc::new(|| Value::Null),
267        }
268    }
269}
270
271impl ModuleInit for LightningClientInit {
272    type Common = LightningCommonInit;
273
274    async fn dump_database(
275        &self,
276        _dbtx: &mut DatabaseTransaction<'_>,
277        _prefix_names: Vec<String>,
278    ) -> Box<dyn Iterator<Item = (String, Box<dyn erased_serde::Serialize + Send>)> + '_> {
279        Box::new(BTreeMap::new().into_iter())
280    }
281}
282
283#[apply(async_trait_maybe_send!)]
284impl ClientModuleInit for LightningClientInit {
285    type Module = LightningClientModule;
286
287    fn supported_api_versions(&self) -> MultiApiVersion {
288        MultiApiVersion::try_from_iter([ApiVersion { major: 0, minor: 0 }])
289            .expect("no version conflicts")
290    }
291
292    async fn init(
293        &self,
294        args: &ClientModuleInitArgs<Self>,
295    ) -> Result<Self::Module, ClientModuleError> {
296        let gateway_conn = if let Some(gateway_conn) = self.gateway_conn.clone() {
297            gateway_conn
298        } else {
299            let api = GatewayApi::new(None, args.connector_registry.clone());
300            Arc::new(RealGatewayConnection { api })
301        };
302        Ok(LightningClientModule::new(
303            *args.federation_id(),
304            args.cfg().clone(),
305            args.notifier().clone(),
306            args.context(),
307            args.module_api().clone(),
308            args.module_root_secret(),
309            gateway_conn,
310            self.custom_meta_fn.clone(),
311            args.admin_auth().cloned(),
312            args.task_group(),
313            args.client_span(),
314        ))
315    }
316
317    fn used_db_prefixes(&self) -> Option<BTreeSet<u8>> {
318        Some(
319            DbKeyPrefix::iter()
320                .map(|p| p as u8)
321                .chain(
322                    DbKeyPrefix::ExternalReservedStart as u8
323                        ..=DbKeyPrefix::CoreInternalReservedEnd as u8,
324                )
325                .collect(),
326        )
327    }
328}
329
330#[derive(Debug, Clone)]
331pub struct LightningClientContext {
332    federation_id: FederationId,
333    gateway_conn: Arc<dyn GatewayConnection + Send + Sync>,
334    pub(crate) client_ctx: ClientContext<LightningClientModule>,
335}
336
337impl Context for LightningClientContext {
338    const KIND: Option<ModuleKind> = Some(KIND);
339}
340
341#[derive(Debug, Clone)]
342pub struct LightningClientModule {
343    federation_id: FederationId,
344    cfg: LightningClientConfig,
345    notifier: ModuleNotifier<LightningClientStateMachines>,
346    client_ctx: ClientContext<Self>,
347    module_api: DynModuleApi,
348    /// Every account's static receive key and lnurl key, derived once at
349    /// startup and indexed by [`Account::index`]. Both are static per account,
350    /// so an extra account costs one more trial decryption per streamed
351    /// contract rather than another pass over the stream.
352    keys: [AccountKeys; Account::ALL.len()],
353    gateway_conn: Arc<dyn GatewayConnection + Send + Sync>,
354    #[allow(unused)] // The field is only used by the cli feature
355    admin_auth: Option<ApiAuth>,
356}
357
358#[apply(async_trait_maybe_send!)]
359impl ClientModule for LightningClientModule {
360    type Init = LightningClientInit;
361    type Common = LightningModuleTypes;
362    type Backup = NoModuleBackup;
363    type ModuleStateMachineContext = LightningClientContext;
364    type States = LightningClientStateMachines;
365
366    fn context(&self) -> Self::ModuleStateMachineContext {
367        LightningClientContext {
368            federation_id: self.federation_id,
369            gateway_conn: self.gateway_conn.clone(),
370            client_ctx: self.client_ctx.clone(),
371        }
372    }
373
374    fn input_fee(
375        &self,
376        amounts: &Amounts,
377        _input: &<Self::Common as ModuleCommon>::Input,
378    ) -> Option<Amounts> {
379        Some(Amounts::new_bitcoin(
380            self.cfg.fee_consensus.fee(amounts.expect_only_bitcoin()),
381        ))
382    }
383
384    fn output_fee(
385        &self,
386        amounts: &Amounts,
387        _output: &<Self::Common as ModuleCommon>::Output,
388    ) -> Option<Amounts> {
389        Some(Amounts::new_bitcoin(
390            self.cfg.fee_consensus.fee(amounts.expect_only_bitcoin()),
391        ))
392    }
393
394    #[cfg(feature = "cli")]
395    async fn handle_cli_command(
396        &self,
397        args: &[std::ffi::OsString],
398    ) -> Result<serde_json::Value, ClientModuleError> {
399        cli::handle_cli_command(self, args)
400            .await
401            .map_err(ClientModuleError::other)
402    }
403}
404
405/// The two static keys an account receives on.
406#[derive(Debug, Clone, Copy)]
407struct AccountKeys {
408    /// Contracts are locked to a tweak of this, so it is what a gateway
409    /// invoice names and what the stream scanner trials each contract against.
410    keypair: Keypair,
411    /// The key an lnurl advertises, kept distinct from `keypair` so a
412    /// shareable address cannot be correlated with a one-shot invoice.
413    lnurl_keypair: Keypair,
414}
415
416impl LightningClientModule {
417    fn keys(&self, account: Account) -> AccountKeys {
418        self.keys[usize::from(account.index())]
419    }
420
421    #[allow(clippy::too_many_arguments)]
422    fn new(
423        federation_id: FederationId,
424        cfg: LightningClientConfig,
425        notifier: ModuleNotifier<LightningClientStateMachines>,
426        client_ctx: ClientContext<Self>,
427        module_api: DynModuleApi,
428        module_root_secret: &DerivableSecret,
429        gateway_conn: Arc<dyn GatewayConnection + Send + Sync>,
430        custom_meta_fn: Arc<dyn Fn() -> Value + Send + Sync>,
431        admin_auth: Option<ApiAuth>,
432        task_group: &TaskGroup,
433        client_span: &tracing::Span,
434    ) -> Self {
435        let module = Self {
436            federation_id,
437            cfg,
438            notifier,
439            client_ctx,
440            module_api,
441            keys: Account::ALL.map(|account| {
442                let account_secret = module_root_secret.derive_account_secret(account);
443
444                AccountKeys {
445                    keypair: account_secret.child_key(ChildId(0)).to_secp_key(SECP256K1),
446                    lnurl_keypair: account_secret.child_key(ChildId(1)).to_secp_key(SECP256K1),
447                }
448            }),
449            gateway_conn,
450            admin_auth,
451        };
452
453        module.spawn_receive_lnurl_task(custom_meta_fn, task_group, client_span);
454
455        module.spawn_gateway_map_update_task(task_group, client_span);
456
457        module
458    }
459
460    fn spawn_gateway_map_update_task(&self, task_group: &TaskGroup, client_span: &tracing::Span) {
461        let module = self.clone();
462        let api = self.module_api.clone();
463
464        task_group.spawn_cancellable_with_span(
465            client_span.clone(),
466            "gateway_map_update_task",
467            async move {
468                api.wait_for_initialized_connections().await;
469                module.update_gateway_map().await;
470            },
471        );
472    }
473
474    async fn update_gateway_map(&self) {
475        // Update the mapping from lightning node public keys to gateway api
476        // endpoints maintained in the module database. When paying an invoice this
477        // enables the client to select the gateway that has created the invoice,
478        // if possible, such that the payment does not go over lightning, reducing
479        // fees and latency.
480
481        if let Ok(gateways) = self.module_api.gateways().await {
482            let mut dbtx = self.client_ctx.module_db().begin_transaction().await;
483
484            for gateway in gateways {
485                if let Ok(Some(routing_info)) = self
486                    .gateway_conn
487                    .routing_info(gateway.clone(), &self.federation_id)
488                    .await
489                {
490                    dbtx.insert_entry(&GatewayKey(routing_info.lightning_public_key), &gateway)
491                        .await;
492                }
493            }
494
495            if let Err(e) = dbtx.commit_tx_result().await {
496                warn!("Failed to commit the updated gateway mapping to the database: {e}");
497            }
498        }
499    }
500
501    /// Selects an available gateway by querying the federation's registered
502    /// gateways, checking if one of them match the invoice's payee public
503    /// key, then queries the gateway for `RoutingInfo` to determine if it is
504    /// online.
505    pub async fn select_gateway(
506        &self,
507        invoice: Option<Bolt11Invoice>,
508    ) -> Result<(SafeUrl, RoutingInfo), SelectGatewayError> {
509        let gateways = self
510            .module_api
511            .gateways()
512            .await
513            .map_err(|e| SelectGatewayError::FailedToRequestGateways(e.to_string()))?;
514
515        if gateways.is_empty() {
516            return Err(SelectGatewayError::NoGatewaysAvailable);
517        }
518
519        if let Some(invoice) = invoice
520            && let Some(gateway) = self
521                .client_ctx
522                .module_db()
523                .begin_transaction_nc()
524                .await
525                .get_value(&GatewayKey(invoice.recover_payee_pub_key()))
526                .await
527                .filter(|gateway| gateways.contains(gateway))
528            && let Ok(Some(routing_info)) = self.routing_info(&gateway).await
529        {
530            return Ok((gateway, routing_info));
531        }
532
533        for gateway in gateways {
534            if let Ok(Some(routing_info)) = self.routing_info(&gateway).await {
535                return Ok((gateway, routing_info));
536            }
537        }
538
539        Err(SelectGatewayError::GatewaysUnresponsive)
540    }
541
542    /// Sends a request to each peer for their registered gateway list and
543    /// returns a `Vec<SafeUrl` of all registered gateways to the client.
544    pub async fn list_gateways(
545        &self,
546        peer: Option<PeerId>,
547    ) -> Result<Vec<SafeUrl>, ListGatewaysError> {
548        if let Some(peer) = peer {
549            self.module_api
550                .gateways_from_peer(peer)
551                .await
552                .map_err(|_| ListGatewaysError::FailedToListGateways)
553        } else {
554            self.module_api
555                .gateways()
556                .await
557                .map_err(|_| ListGatewaysError::FailedToListGateways)
558        }
559    }
560
561    /// Requests the `RoutingInfo`, including fee information, from the gateway
562    /// available at the `SafeUrl`.
563    ///
564    /// A failed request is retried a few times, so that one dropped or slow
565    /// request does not make the gateway look offline. The request is a read,
566    /// so retrying it is safe.
567    pub async fn routing_info(
568        &self,
569        gateway: &SafeUrl,
570    ) -> Result<Option<RoutingInfo>, RoutingInfoError> {
571        util::retry("gateway-routing-info", gateway_request_backoff(), || {
572            self.gateway_conn
573                .routing_info(gateway.clone(), &self.federation_id)
574        })
575        .await
576        .map_err(|_| RoutingInfoError::FailedToRequestRoutingInfo)
577    }
578
579    /// Pay an invoice. For testing you can optionally specify a gateway to
580    /// route with, otherwise a gateway will be selected automatically. If the
581    /// invoice was created by a gateway connected to our federation, the same
582    /// gateway will be selected to allow for a direct ecash swap. Otherwise we
583    /// select a random online gateway.
584    ///
585    /// The fee for this payment may depend on the selected gateway but
586    /// will be limited to one and a half percent plus one hundred satoshis.
587    /// This fee accounts for the fee charged by the gateway as well as
588    /// the additional fee required to reliably route this payment over
589    /// lightning if necessary. Since the gateway has been vetted by at least
590    /// one guardian we trust it to set a reasonable fee and only enforce a
591    /// rather high limit.
592    ///
593    /// The absolute fee for a payment can be calculated from the operation meta
594    /// to be shown to the user in the transaction history.
595    pub async fn send(
596        &self,
597        account: Account,
598        invoice: Bolt11Invoice,
599        gateway: Option<SafeUrl>,
600        custom_meta: Value,
601    ) -> Result<OperationId, SendPaymentError> {
602        let (amount, operation_id) = self.validate_send_invoice(account, &invoice).await?;
603
604        let (gateway_api, routing_info) = self.resolve_send_gateway(&invoice, gateway).await?;
605
606        self.fund_outgoing_contract(
607            account,
608            invoice,
609            amount,
610            operation_id,
611            gateway_api,
612            routing_info,
613            custom_meta,
614        )
615        .await
616    }
617
618    /// Pays `invoice` through `gateway` at the terms the caller already
619    /// checked.
620    ///
621    /// [`Self::send`] reads the gateway's terms itself, so a caller that showed
622    /// the user a fee and asked for approval has no guarantee the funded
623    /// contract carries that fee: the gateway may change its schedule between
624    /// the two reads. This variant takes the `send_fee` and `expiration_delta`
625    /// the caller obtained from [`RoutingInfo::send_parameters`] and refuses
626    /// with [`SendWithTermsError::TermsChanged`], before funding anything, if
627    /// the gateway currently reports different terms. A cheaper fee counts
628    /// as changed too, so the funded contract always matches what was
629    /// approved. This binds the funded contract to the approved terms, not
630    /// the gateway's acceptance: a gateway that raises its schedule after the
631    /// check can still refuse the contract, in which case the payment is
632    /// refunded. The error carries the current terms for re-quoting.
633    pub async fn send_with_terms(
634        &self,
635        account: Account,
636        invoice: Bolt11Invoice,
637        gateway: SafeUrl,
638        send_fee: PaymentFee,
639        expiration_delta: u64,
640        custom_meta: Value,
641    ) -> Result<OperationId, SendWithTermsError> {
642        let (amount, operation_id) = self.validate_send_invoice(account, &invoice).await?;
643
644        let (gateway_api, routing_info) =
645            self.resolve_send_gateway(&invoice, Some(gateway)).await?;
646
647        let current = routing_info.send_parameters(&invoice);
648
649        if current != (send_fee, expiration_delta) {
650            return Err(SendWithTermsError::TermsChanged {
651                send_fee: current.0,
652                expiration_delta: current.1,
653            });
654        }
655
656        let operation_id = self
657            .fund_outgoing_contract(
658                account,
659                invoice,
660                amount,
661                operation_id,
662                gateway_api,
663                routing_info,
664                custom_meta,
665            )
666            .await?;
667
668        Ok(operation_id)
669    }
670
671    /// Checks that `invoice` is payable by this client and has not been
672    /// attempted before, returning its amount in millisatoshis and the
673    /// operation id a payment of it uses.
674    async fn validate_send_invoice(
675        &self,
676        account: Account,
677        invoice: &Bolt11Invoice,
678    ) -> Result<(u64, OperationId), SendPaymentError> {
679        let amount = invoice
680            .amount_milli_satoshis()
681            .ok_or(SendPaymentError::InvoiceMissingAmount)?;
682
683        if invoice.would_expire(duration_since_epoch()) {
684            return Err(SendPaymentError::InvoiceExpired);
685        }
686
687        if !currency_matches_network(&invoice.currency(), self.cfg.network) {
688            return Err(SendPaymentError::WrongCurrency {
689                invoice_currency: invoice.currency(),
690                federation_currency: currency_for_network(self.cfg.network),
691            });
692        }
693
694        if !self
695            .client_ctx
696            .supports_account(AmountUnit::BITCOIN, account)
697        {
698            return Err(SendPaymentError::AccountNotSupported);
699        }
700
701        // The attempt index is fixed at `0` so the operation id matches the one
702        // older clients derived for the first payment attempt, ensuring an
703        // already-paid or in-flight invoice is still detected after an upgrade.
704        let operation_id = OperationId::from_encodable(&(invoice.clone(), 0u64));
705
706        if self.client_ctx.operation_exists(operation_id).await {
707            return Err(SendPaymentError::DuplicatePaymentAttempt(operation_id));
708        }
709
710        Ok((amount, operation_id))
711    }
712
713    /// Resolves the gateway to pay `invoice` through and its current routing
714    /// info: the given one, or an automatically selected one when `None`.
715    async fn resolve_send_gateway(
716        &self,
717        invoice: &Bolt11Invoice,
718        gateway: Option<SafeUrl>,
719    ) -> Result<(SafeUrl, RoutingInfo), SendPaymentError> {
720        match gateway {
721            Some(gateway_api) => Ok((
722                gateway_api.clone(),
723                self.routing_info(&gateway_api)
724                    .await
725                    .map_err(|e| SendPaymentError::FailedToConnectToGateway(e.to_string()))?
726                    .ok_or(SendPaymentError::FederationNotSupported)?,
727            )),
728            None => self
729                .select_gateway(Some(invoice.clone()))
730                .await
731                .map_err(SendPaymentError::SelectGateway),
732        }
733    }
734
735    /// Funds an outgoing contract for `invoice` at the terms in `routing_info`
736    /// and starts the state machine that hands it to `gateway_api`.
737    #[allow(clippy::too_many_lines)]
738    #[allow(clippy::too_many_arguments)]
739    async fn fund_outgoing_contract(
740        &self,
741        account: Account,
742        invoice: Bolt11Invoice,
743        amount: u64,
744        operation_id: OperationId,
745        gateway_api: SafeUrl,
746        routing_info: RoutingInfo,
747        custom_meta: Value,
748    ) -> Result<OperationId, SendPaymentError> {
749        let (ephemeral_tweak, ephemeral_pk) =
750            tweak::generate(self.keys(account).keypair.public_key());
751
752        let refund_keypair = SecretKey::from_slice(&ephemeral_tweak)
753            .expect("32 bytes, within curve order")
754            .keypair(secp256k1::SECP256K1);
755
756        let (send_fee, expiration_delta) = routing_info.send_parameters(&invoice);
757
758        if !send_fee.is_within(&PaymentFee::SEND_FEE_LIMIT) {
759            return Err(SendPaymentError::GatewayFeeExceedsLimit);
760        }
761
762        if EXPIRATION_DELTA_LIMIT < expiration_delta {
763            return Err(SendPaymentError::GatewayExpirationExceedsLimit);
764        }
765
766        let consensus_block_count = self
767            .module_api
768            .consensus_block_count()
769            .await
770            .map_err(|e| SendPaymentError::FailedToRequestBlockCount(e.to_string()))?;
771
772        let contract = OutgoingContract {
773            payment_image: PaymentImage::Hash(*invoice.payment_hash()),
774            amount: send_fee.add_to(amount),
775            expiration: consensus_block_count + expiration_delta + CONTRACT_CONFIRMATION_BUFFER,
776            claim_pk: routing_info.module_public_key,
777            refund_pk: refund_keypair.public_key(),
778            ephemeral_pk,
779        };
780
781        let contract_clone = contract.clone();
782        let gateway_api_clone = gateway_api.clone();
783        let invoice_clone = invoice.clone();
784
785        let client_output = ClientOutput::<LightningOutput> {
786            output: LightningOutput::V0(LightningOutputV0::Outgoing(contract.clone())),
787            amounts: Amounts::new_bitcoin(contract.amount),
788        };
789
790        let client_output_sm = ClientOutputSM::<LightningClientStateMachines> {
791            state_machines: Arc::new(move |range: OutPointRange| {
792                vec![LightningClientStateMachines::Send(SendStateMachine {
793                    common: SendSMCommon {
794                        operation_id,
795                        outpoint: range.into_iter().next().unwrap(),
796                        contract: contract_clone.clone(),
797                        gateway_api: Some(gateway_api_clone.clone()),
798                        invoice: Some(LightningInvoice::Bolt11(invoice_clone.clone())),
799                        refund_keypair,
800                    },
801                    state: SendSMState::Funding,
802                })]
803            }),
804        };
805
806        let client_output = self.client_ctx.make_client_outputs(ClientOutputBundle::new(
807            vec![client_output],
808            vec![client_output_sm],
809        ));
810
811        let transaction = TransactionBuilder::new(account).with_outputs(client_output);
812
813        let operation_meta_gen = move |change_outpoint_range| {
814            LightningOperationMeta::Send(SendOperationMeta {
815                change_outpoint_range,
816                gateway: gateway_api.clone(),
817                contract: contract.clone(),
818                invoice: LightningInvoice::Bolt11(invoice.clone()),
819                custom_meta: custom_meta.clone(),
820            })
821        };
822
823        self.client_ctx
824            .finalize_and_submit_transaction_with_events(
825                operation_id,
826                LightningCommonInit::KIND.as_str(),
827                operation_meta_gen,
828                transaction,
829                vec![self.client_ctx.make_event(SendPaymentEvent {
830                    operation_id,
831                    amount: Amount::from_msats(amount),
832                    fee: send_fee.fee(amount),
833                    account,
834                })],
835            )
836            .await
837            .map_err(|e| match e {
838                TransactionSubmitError::InsufficientFunds(e) => {
839                    SendPaymentError::InsufficientFunds(e)
840                }
841                e => SendPaymentError::FailedToFundPayment(e.fmt_compact().to_string()),
842            })?;
843
844        Ok(operation_id)
845    }
846
847    /// The status of a previous [`Self::send`] for this invoice.
848    ///
849    /// Callers deciding whether an invoice is safe to pay through another
850    /// mechanism must treat anything but [`InvoiceSendStatus::NotAttempted`]
851    /// as a potential double payment.
852    pub async fn get_invoice_send_status(
853        &self,
854        invoice: &Bolt11Invoice,
855    ) -> Result<InvoiceSendStatus, OperationLookupError> {
856        // Send only creates attempt index 0 nowadays, but older clients
857        // allocated a fresh index per retry, so scan for the latest attempt.
858        // No new attempt was ever allocated after a success, so the latest
859        // attempt alone determines the status.
860        let mut last_op = None;
861
862        for attempt in 0_u64.. {
863            let operation_id = OperationId::from_encodable(&(invoice.clone(), attempt));
864
865            if !self.client_ctx.operation_exists(operation_id).await {
866                break;
867            }
868
869            last_op = Some(operation_id);
870        }
871
872        let Some(operation_id) = last_op else {
873            return Ok(InvoiceSendStatus::NotAttempted);
874        };
875
876        if self.client_ctx.has_active_states(operation_id).await {
877            return Ok(InvoiceSendStatus::InFlight(operation_id));
878        }
879
880        // The operation is finished; replaying its (already terminated) update
881        // stream yields the cached outcome without blocking.
882        let mut stream = self
883            .subscribe_send_operation_state_updates(operation_id)
884            .await?
885            .into_stream();
886
887        while let Some(state) = stream.next().await {
888            if let SendOperationState::Success(_) = state {
889                return Ok(InvoiceSendStatus::Succeeded(operation_id));
890            }
891        }
892
893        Ok(InvoiceSendStatus::Failed(operation_id))
894    }
895
896    /// Subscribe to all state updates of the send operation.
897    pub async fn subscribe_send_operation_state_updates(
898        &self,
899        operation_id: OperationId,
900    ) -> Result<UpdateStreamOrOutcome<SendOperationState>, OperationLookupError> {
901        let operation = self.client_ctx.get_operation(operation_id).await?;
902        let mut stream = self.notifier.subscribe(operation_id).await;
903        let client_ctx = self.client_ctx.clone();
904        let module_api = self.module_api.clone();
905
906        Ok(self.client_ctx.outcome_or_updates(&operation, operation_id, |state| match state {
907                SendOperationState::Funding
908                | SendOperationState::Funded
909                | SendOperationState::Refunding => false,
910                SendOperationState::Success(_)
911                | SendOperationState::Refunded
912                | SendOperationState::Failure => true,
913            }, move || {
914            stream! {
915                loop {
916                    if let Some(LightningClientStateMachines::Send(state)) = stream.next().await {
917                        match state.state {
918                            SendSMState::Funding => yield SendOperationState::Funding,
919                            SendSMState::Funded => yield SendOperationState::Funded,
920                            SendSMState::Success(preimage) => {
921                                // the preimage has been verified by the state machine previously
922                                assert!(state.common.contract.verify_preimage(&preimage));
923
924                                yield SendOperationState::Success(preimage);
925                                return;
926                            },
927                            SendSMState::Refunding(out_points) => {
928                                yield SendOperationState::Refunding;
929
930                                if client_ctx.await_primary_module_outputs(operation_id, out_points.clone()).await.is_ok() {
931                                    yield SendOperationState::Refunded;
932                                    return;
933                                }
934
935                                // The gateway may have incorrectly claimed the outgoing contract thereby causing
936                                // our refund transaction to be rejected. Therefore, we check one last time if
937                                // the preimage is available before we enter the failure state.
938                                if let Some(preimage) = module_api.await_preimage(
939                                    state.common.outpoint,
940                                    0
941                                ).await
942                                    && state.common.contract.verify_preimage(&preimage) {
943                                        yield SendOperationState::Success(preimage);
944                                        return;
945                                    }
946
947                                yield SendOperationState::Failure;
948                                return;
949                            },
950                            SendSMState::Rejected(..) => {
951                                yield SendOperationState::Failure;
952                                return;
953                            },
954                        }
955                    }
956                }
957            }
958        }))
959    }
960
961    /// Await the final state of the send operation.
962    pub async fn await_final_send_operation_state(
963        &self,
964        operation_id: OperationId,
965    ) -> Result<FinalSendOperationState, OperationLookupError> {
966        let mut stream = self
967            .subscribe_send_operation_state_updates(operation_id)
968            .await?
969            .into_stream();
970
971        let mut final_state = None;
972
973        while let Some(state) = stream.next().await {
974            match state {
975                SendOperationState::Success(preimage) => {
976                    final_state = Some(FinalSendOperationState::Success(preimage));
977                }
978                SendOperationState::Refunded => {
979                    final_state = Some(FinalSendOperationState::Refunded);
980                }
981                SendOperationState::Failure => final_state = Some(FinalSendOperationState::Failure),
982                _ => {}
983            }
984        }
985
986        Ok(final_state.expect("Stream contains one final state"))
987    }
988
989    /// Request an invoice. For testing you can optionally specify a gateway to
990    /// generate the invoice, otherwise a random online gateway will be selected
991    /// automatically.
992    ///
993    /// The total fee for this payment may depend on the chosen gateway but
994    /// will be limited to half of one percent plus fifty satoshis. Since the
995    /// selected gateway has been vetted by at least one guardian we trust it to
996    /// set a reasonable fee and only enforce a rather high limit.
997    ///
998    /// The absolute fee for a payment can be calculated from the operation meta
999    /// to be shown to the user in the transaction history.
1000    pub async fn receive(
1001        &self,
1002        account: Account,
1003        amount: Amount,
1004        expiry_secs: u32,
1005        description: Bolt11InvoiceDescription,
1006        gateway: Option<SafeUrl>,
1007        custom_meta: Value,
1008    ) -> Result<(Bolt11Invoice, OperationId), ReceiveError> {
1009        if !self
1010            .client_ctx
1011            .supports_account(AmountUnit::BITCOIN, account)
1012        {
1013            return Err(ReceiveError::AccountNotSupported);
1014        }
1015
1016        if MAX_INVOICE_EXPIRY_SECS < expiry_secs {
1017            return Err(ReceiveError::InvoiceExpiryTooLong);
1018        }
1019
1020        let (gateway, routing_info) = self.resolve_receive_gateway(gateway).await?;
1021
1022        self.receive_with_routing_info(
1023            account,
1024            amount,
1025            expiry_secs,
1026            description,
1027            gateway,
1028            routing_info,
1029            custom_meta,
1030        )
1031        .await
1032    }
1033
1034    /// Requests an invoice from `gateway` at the receive fee the caller
1035    /// already checked.
1036    ///
1037    /// [`Self::receive`] reads the gateway's fee itself, so a caller that
1038    /// showed the user a fee has no guarantee the incoming contract is
1039    /// created at that fee: the gateway may change its schedule between the
1040    /// two reads. This variant takes the `receive_fee` the caller obtained
1041    /// from [`RoutingInfo::receive_fee`] and refuses with
1042    /// [`ReceiveWithTermsError::TermsChanged`], before creating anything, if
1043    /// the gateway currently reports a different fee. A cheaper fee counts as
1044    /// changed too, so the contract always matches what was approved; the
1045    /// error carries the current fee for re-quoting.
1046    #[allow(clippy::too_many_arguments)]
1047    pub async fn receive_with_terms(
1048        &self,
1049        account: Account,
1050        amount: Amount,
1051        expiry_secs: u32,
1052        description: Bolt11InvoiceDescription,
1053        gateway: SafeUrl,
1054        receive_fee: PaymentFee,
1055        custom_meta: Value,
1056    ) -> Result<(Bolt11Invoice, OperationId), ReceiveWithTermsError> {
1057        if !self
1058            .client_ctx
1059            .supports_account(AmountUnit::BITCOIN, account)
1060        {
1061            return Err(ReceiveError::AccountNotSupported.into());
1062        }
1063
1064        if MAX_INVOICE_EXPIRY_SECS < expiry_secs {
1065            return Err(ReceiveError::InvoiceExpiryTooLong.into());
1066        }
1067
1068        let (gateway, routing_info) = self.resolve_receive_gateway(Some(gateway)).await?;
1069
1070        if routing_info.receive_fee != receive_fee {
1071            return Err(ReceiveWithTermsError::TermsChanged {
1072                receive_fee: routing_info.receive_fee,
1073            });
1074        }
1075
1076        let (invoice, operation_id) = self
1077            .receive_with_routing_info(
1078                account,
1079                amount,
1080                expiry_secs,
1081                description,
1082                gateway,
1083                routing_info,
1084                custom_meta,
1085            )
1086            .await?;
1087
1088        Ok((invoice, operation_id))
1089    }
1090
1091    /// Resolves the gateway to request an invoice from and its current
1092    /// routing info: the given one, or an automatically selected one when
1093    /// `None`.
1094    async fn resolve_receive_gateway(
1095        &self,
1096        gateway: Option<SafeUrl>,
1097    ) -> Result<(SafeUrl, RoutingInfo), ReceiveError> {
1098        match gateway {
1099            Some(gateway) => {
1100                let routing_info = self
1101                    .routing_info(&gateway)
1102                    .await
1103                    .map_err(|e| ReceiveError::FailedToConnectToGateway(e.to_string()))?
1104                    .ok_or(ReceiveError::FederationNotSupported)?;
1105
1106                if !routing_info.receive_enabled {
1107                    return Err(ReceiveError::ReceiveDisabled);
1108                }
1109
1110                Ok((gateway, routing_info))
1111            }
1112            None => self
1113                .select_receive_gateway()
1114                .await
1115                .map_err(ReceiveError::SelectGateway),
1116        }
1117    }
1118
1119    /// Selects the first registered gateway that is online and currently
1120    /// accepts incoming payments for this federation. A gateway that answers
1121    /// but has turned receives off is skipped rather than handed an invoice
1122    /// request it would refuse.
1123    async fn select_receive_gateway(&self) -> Result<(SafeUrl, RoutingInfo), SelectGatewayError> {
1124        let gateways = self
1125            .module_api
1126            .gateways()
1127            .await
1128            .map_err(|e| SelectGatewayError::FailedToRequestGateways(e.to_string()))?;
1129
1130        if gateways.is_empty() {
1131            return Err(SelectGatewayError::NoGatewaysAvailable);
1132        }
1133
1134        let mut any_responded = false;
1135
1136        for gateway in gateways {
1137            if let Ok(Some(routing_info)) = self.routing_info(&gateway).await {
1138                any_responded = true;
1139
1140                if routing_info.receive_enabled {
1141                    return Ok((gateway, routing_info));
1142                }
1143            }
1144        }
1145
1146        if any_responded {
1147            Err(SelectGatewayError::NoGatewayAcceptsReceives)
1148        } else {
1149            Err(SelectGatewayError::GatewaysUnresponsive)
1150        }
1151    }
1152
1153    /// Creates the incoming contract locked to a public key derived from our
1154    /// static module public key, fetches its invoice from `gateway` at the
1155    /// terms in `routing_info`, then starts the receive operation.
1156    #[allow(clippy::too_many_arguments)]
1157    async fn receive_with_routing_info(
1158        &self,
1159        account: Account,
1160        amount: Amount,
1161        expiry_secs: u32,
1162        description: Bolt11InvoiceDescription,
1163        gateway: SafeUrl,
1164        routing_info: RoutingInfo,
1165        custom_meta: Value,
1166    ) -> Result<(Bolt11Invoice, OperationId), ReceiveError> {
1167        if !routing_info
1168            .receive_fee
1169            .is_within(&PaymentFee::RECEIVE_FEE_LIMIT)
1170        {
1171            return Err(ReceiveError::GatewayFeeExceedsLimit);
1172        }
1173
1174        let contract_amount = routing_info.receive_fee.subtract_from(amount.msats);
1175
1176        // Quoting the claim against this federation's fee consensus is exact, where a
1177        // fixed floor is either too permissive or too strict depending on how the
1178        // federation is configured.
1179        if !self.is_worth_claiming(account, contract_amount).await {
1180            return Err(ReceiveError::AmountTooSmall);
1181        }
1182
1183        // The gateway registers each payment hash once, so a request whose
1184        // response was lost cannot be repeated with the same contract. Each
1185        // attempt creates a new contract instead. Nothing is stored before the
1186        // invoice arrives, and the gateway lets an unused registration expire.
1187        let (contract, preimage, invoice) =
1188            util::retry("gateway-bolt11-invoice", gateway_request_backoff(), || {
1189                self.request_invoice_for_new_contract(
1190                    account,
1191                    &gateway,
1192                    &routing_info,
1193                    contract_amount,
1194                    amount,
1195                    description.clone(),
1196                    expiry_secs,
1197                )
1198            })
1199            .await
1200            .map_err(|e| ReceiveError::FailedToConnectToGateway(e.to_string()))?;
1201
1202        if invoice.payment_hash() != &preimage.consensus_hash() {
1203            return Err(ReceiveError::InvalidInvoice);
1204        }
1205
1206        if invoice.amount_milli_satoshis() != Some(amount.msats) {
1207            return Err(ReceiveError::IncorrectInvoiceAmount);
1208        }
1209
1210        let operation_id = self
1211            .receive_incoming_contract(
1212                account,
1213                self.keys(account).keypair.secret_key(),
1214                contract.clone(),
1215                LightningOperationMeta::Receive(ReceiveOperationMeta {
1216                    gateway,
1217                    contract,
1218                    invoice: LightningInvoice::Bolt11(invoice.clone()),
1219                    custom_meta,
1220                }),
1221            )
1222            .await
1223            .expect("The contract has been generated with our public key");
1224
1225        Ok((invoice, operation_id))
1226    }
1227
1228    /// Creates a new incoming contract locked to a public key derived from
1229    /// our static module public key and requests its invoice from `gateway`.
1230    #[allow(clippy::too_many_arguments)]
1231    async fn request_invoice_for_new_contract(
1232        &self,
1233        account: Account,
1234        gateway: &SafeUrl,
1235        routing_info: &RoutingInfo,
1236        contract_amount: Amount,
1237        amount: Amount,
1238        description: Bolt11InvoiceDescription,
1239        expiry_secs: u32,
1240    ) -> Result<(IncomingContract, [u8; 32], Bolt11Invoice), ServerError> {
1241        let recipient_static_pk = self.keys(account).keypair.public_key();
1242
1243        let (ephemeral_tweak, ephemeral_pk) = tweak::generate(recipient_static_pk);
1244
1245        let encryption_seed = ephemeral_tweak
1246            .consensus_hash::<sha256::Hash>()
1247            .to_byte_array();
1248
1249        let preimage = encryption_seed
1250            .consensus_hash::<sha256::Hash>()
1251            .to_byte_array();
1252
1253        let expiration = duration_since_epoch()
1254            .as_secs()
1255            .saturating_add(u64::from(expiry_secs));
1256
1257        let claim_pk = recipient_static_pk
1258            .mul_tweak(
1259                secp256k1::SECP256K1,
1260                &Scalar::from_be_bytes(ephemeral_tweak).expect("Within curve order"),
1261            )
1262            .expect("Tweak is valid");
1263
1264        let contract = IncomingContract::new(
1265            self.cfg.tpe_agg_pk,
1266            encryption_seed,
1267            preimage,
1268            PaymentImage::Hash(preimage.consensus_hash()),
1269            contract_amount,
1270            expiration,
1271            claim_pk,
1272            routing_info.module_public_key,
1273            ephemeral_pk,
1274        );
1275
1276        let invoice = self
1277            .gateway_conn
1278            .bolt11_invoice(
1279                gateway.clone(),
1280                self.federation_id,
1281                contract.clone(),
1282                amount,
1283                description,
1284                expiry_secs,
1285            )
1286            .await?;
1287
1288        Ok((contract, preimage, invoice))
1289    }
1290
1291    /// Computes the federation fee a `receive` of `amount` would incur, without
1292    /// submitting anything.
1293    ///
1294    /// When the incoming contract is claimed, the client submits a transaction
1295    /// with a single Lightning input worth the contract amount; the primary
1296    /// module balances it by minting the change credited to the wallet. This
1297    /// quotes the fee of that transaction — the Lightning input fee, the mint
1298    /// output fees, and any sub-denomination dust — via the shared,
1299    /// module-agnostic fee quote.
1300    ///
1301    /// The gateway's off-chain Lightning fee is deliberately excluded: this is
1302    /// only the fee of the on-federation transaction. For that reason the quote
1303    /// is taken on `amount` directly (rather than the gateway-reduced contract
1304    /// amount), and no gateway round-trip is needed.
1305    pub async fn receive_fee_quote(
1306        &self,
1307        account: Account,
1308        amount: Amount,
1309    ) -> Result<FeeQuote, TransactionSubmitError> {
1310        self.client_ctx
1311            .fee_quote(
1312                OperationId::new_random(),
1313                FeeQuoteRequest {
1314                    input_amount: Amounts::new_bitcoin(amount),
1315                    output_amount: Amounts::ZERO,
1316                    input_fee: Amounts::new_bitcoin(self.cfg.fee_consensus.fee(amount)),
1317                    output_fee: Amounts::ZERO,
1318                    account,
1319                },
1320            )
1321            .await
1322    }
1323
1324    /// Whether an incoming contract worth `amount` is worth claiming, i.e.
1325    /// whether claiming it would leave the wallet better off than leaving it.
1326    ///
1327    /// This is the computed counterpart of a fixed dust limit: it prices the
1328    /// actual claim - the lightning input fee at this federation's fee
1329    /// consensus, the change the primary module has to mint, and the
1330    /// sub-denomination remainder that cannot be minted at all - rather than
1331    /// assuming a floor. A quote that fails outright is the same verdict: the
1332    /// claim spends the contract as the transaction's only input, so a fee
1333    /// larger than the contract leaves a transaction that cannot be balanced.
1334    async fn is_worth_claiming(&self, account: Account, amount: Amount) -> bool {
1335        match self.receive_fee_quote(account, amount).await {
1336            Ok(quote) => quote.total().get_bitcoin() < amount,
1337            Err(_) => false,
1338        }
1339    }
1340
1341    /// Computes the federation fee a `send` funding an outgoing contract worth
1342    /// `amount` would incur, without submitting anything.
1343    ///
1344    /// When a payment is sent, the client submits a transaction with a single
1345    /// Lightning output (the outgoing contract) worth `amount`; the primary
1346    /// module balances it by spending ecash to fund the contract and minting
1347    /// any change. This quotes the fee of that transaction — the Lightning
1348    /// output fee, the mint input fees on the funding notes, any mint change
1349    /// output fees, and sub-denomination dust — via the shared, module-agnostic
1350    /// fee quote.
1351    ///
1352    /// The gateway's off-chain Lightning fee is deliberately excluded: it is
1353    /// part of the contract `amount` the gateway claims, not the on-federation
1354    /// transaction fee. So `amount` is the full outgoing contract value
1355    /// (`send_fee.add_to(invoice_amount)`).
1356    pub async fn send_fee_quote(
1357        &self,
1358        account: Account,
1359        amount: Amount,
1360    ) -> Result<FeeQuote, TransactionSubmitError> {
1361        self.client_ctx
1362            .fee_quote(
1363                OperationId::new_random(),
1364                FeeQuoteRequest {
1365                    input_amount: Amounts::ZERO,
1366                    output_amount: Amounts::new_bitcoin(amount),
1367                    input_fee: Amounts::ZERO,
1368                    output_fee: Amounts::new_bitcoin(self.cfg.fee_consensus.fee(amount)),
1369                    account,
1370                },
1371            )
1372            .await
1373    }
1374
1375    /// Computes the largest invoice amount the client can pay in full out of
1376    /// `balance`, i.e. the amount to request an invoice for in order to spend
1377    /// (close to) the entire balance.
1378    ///
1379    /// Paying an invoice deducts two kinds of fee from the balance:
1380    /// - the *gateway* fee, which is added on top of the invoice amount to form
1381    ///   the outgoing contract (`send_fee.add_to(invoice_amount)`), and
1382    /// - the *federation* fee of funding that contract — the Lightning output
1383    ///   fee, the mint input fees on the funding notes, the mint output fees on
1384    ///   any change, and sub-denomination dust — as quoted by
1385    ///   [`Self::send_fee_quote`].
1386    ///
1387    /// `balance` is the client's current Bitcoin balance (e.g. from
1388    /// `Client::get_balance_for_btc`). `gateway` optionally pins the gateway
1389    /// whose fee schedule to use; if `None` one is selected automatically, the
1390    /// same way [`Self::send`] does when no gateway is given. The gateway's
1391    /// *default* send fee is used — the higher of its two send fees, applied to
1392    /// a Lightning swap rather than a direct fedimint-to-fedimint swap — so the
1393    /// returned amount stays payable even when the eventual invoice is routed
1394    /// over Lightning.
1395    ///
1396    /// The maximum payable amount is found by binary search over the real fee
1397    /// quote (see [`max_affordable_send_amount`]) rather than a closed form,
1398    /// because the federation fee is stepwise in the amount. The quote is
1399    /// point-in-time and moves with the balance, exactly like
1400    /// [`Self::send_fee_quote`]; the eventual [`Self::send`] remains the source
1401    /// of truth and may still fail if balance or gateway state changes in
1402    /// between.
1403    ///
1404    /// Returns [`SpendableAmountError::BalanceTooLow`] if the balance cannot
1405    /// cover even the smallest payable amount plus fees, and
1406    /// [`SpendableAmountError::Quote`] if the fee probe itself failed; only
1407    /// the first of the two says the wallet is short. Any LNURL
1408    /// `minSendable`/`maxSendable` bounds are the caller's responsibility to
1409    /// apply. The remaining variants of [`SpendableAmountError`] are
1410    /// gateway-side, and none of them means the wallet is short.
1411    pub async fn spendable_amount(
1412        &self,
1413        account: Account,
1414        balance: Amount,
1415        gateway: Option<SafeUrl>,
1416    ) -> Result<Amount, SpendableAmountError> {
1417        let routing_info = match gateway {
1418            Some(gateway) => self
1419                .routing_info(&gateway)
1420                .await?
1421                .ok_or(SpendableAmountError::FederationNotSupported)?,
1422            None => self.select_gateway(None).await?.1,
1423        };
1424
1425        // The default (Lightning-swap) send fee is the higher of the gateway's
1426        // two send fees, so using it keeps the result payable even if the
1427        // eventual invoice is routed over Lightning instead of settled by a
1428        // direct swap.
1429        let send_fee = routing_info.send_fee_default;
1430
1431        if !send_fee.is_within(&PaymentFee::SEND_FEE_LIMIT) {
1432            return Err(SpendableAmountError::SendFeeExceedsLimit {
1433                fee: send_fee,
1434                limit: PaymentFee::SEND_FEE_LIMIT,
1435            });
1436        }
1437
1438        max_affordable_send_amount(
1439            balance,
1440            Amount::from_msats(1),
1441            balance,
1442            |invoice_amount: Amount| send_fee.add_to(invoice_amount.msats),
1443            |contract_amount: Amount| self.send_fee_quote(account, contract_amount),
1444        )
1445        .await
1446        .map_err(SpendableAmountError::Quote)?
1447        .ok_or(SpendableAmountError::BalanceTooLow { balance })
1448    }
1449
1450    // Receive an incoming contract locked to a public key derived from our
1451    // static module public key.
1452    async fn receive_incoming_contract(
1453        &self,
1454        account: Account,
1455        sk: SecretKey,
1456        contract: IncomingContract,
1457        operation_meta: LightningOperationMeta,
1458    ) -> Option<OperationId> {
1459        let operation_id = OperationId::from_encodable(&contract.clone());
1460
1461        let tpe_agg_pk = self.cfg.tpe_agg_pk;
1462
1463        let (claim_keypair, agg_decryption_key) = runtime::spawn_blocking({
1464            let contract = contract.clone();
1465
1466            move || recover_contract_keys(sk, &tpe_agg_pk, &contract)
1467        })
1468        .await?;
1469
1470        let receive_sm = LightningClientStateMachines::Receive(ReceiveStateMachine {
1471            common: ReceiveSMCommon {
1472                operation_id,
1473                contract: contract.clone(),
1474                claim_keypair,
1475                agg_decryption_key,
1476            },
1477            state: ReceiveSMState::Pending,
1478        });
1479
1480        // this may only fail if the operation id is already in use, in which case we
1481        // ignore the error such that the method is idempotent
1482        let _ = self
1483            .client_ctx
1484            .manual_operation_start(
1485                operation_id,
1486                account,
1487                LightningCommonInit::KIND.as_str(),
1488                operation_meta,
1489                vec![self.client_ctx.make_dyn_state(receive_sm)],
1490            )
1491            .await;
1492
1493        Some(operation_id)
1494    }
1495
1496    /// Subscribe to all state updates of the receive operation.
1497    pub async fn subscribe_receive_operation_state_updates(
1498        &self,
1499        operation_id: OperationId,
1500    ) -> Result<UpdateStreamOrOutcome<ReceiveOperationState>, OperationLookupError> {
1501        let operation = self.client_ctx.get_operation(operation_id).await?;
1502        let mut stream = self.notifier.subscribe(operation_id).await;
1503        let client_ctx = self.client_ctx.clone();
1504
1505        Ok(self.client_ctx.outcome_or_updates(&operation, operation_id, |state| match state {
1506                ReceiveOperationState::Pending | ReceiveOperationState::Claiming => false,
1507                ReceiveOperationState::Expired
1508                | ReceiveOperationState::Claimed
1509                | ReceiveOperationState::Failure
1510                | ReceiveOperationState::Uneconomical => true,
1511            }, move || {
1512            stream! {
1513                loop {
1514                    if let Some(LightningClientStateMachines::Receive(state)) = stream.next().await {
1515                        match state.state {
1516                            ReceiveSMState::Pending => yield ReceiveOperationState::Pending,
1517                            ReceiveSMState::Claiming(out_points) => {
1518                                yield ReceiveOperationState::Claiming;
1519
1520                                if client_ctx.await_primary_module_outputs(operation_id, out_points).await.is_ok() {
1521                                    yield ReceiveOperationState::Claimed;
1522                                } else {
1523                                    yield ReceiveOperationState::Failure;
1524                                }
1525                                return;
1526                            },
1527                            ReceiveSMState::Expired => {
1528                                yield ReceiveOperationState::Expired;
1529                                return;
1530                            }
1531                            ReceiveSMState::Uneconomical => {
1532                                yield ReceiveOperationState::Uneconomical;
1533                                return;
1534                            }
1535                        }
1536                    }
1537                }
1538            }
1539        }))
1540    }
1541
1542    /// Await the final state of the receive operation.
1543    pub async fn await_final_receive_operation_state(
1544        &self,
1545        operation_id: OperationId,
1546    ) -> Result<FinalReceiveOperationState, OperationLookupError> {
1547        let mut stream = self
1548            .subscribe_receive_operation_state_updates(operation_id)
1549            .await?
1550            .into_stream();
1551
1552        let mut final_state = None;
1553
1554        while let Some(state) = stream.next().await {
1555            match state {
1556                ReceiveOperationState::Expired => {
1557                    final_state = Some(FinalReceiveOperationState::Expired);
1558                }
1559                ReceiveOperationState::Claimed => {
1560                    final_state = Some(FinalReceiveOperationState::Claimed);
1561                }
1562                ReceiveOperationState::Failure => {
1563                    final_state = Some(FinalReceiveOperationState::Failure);
1564                }
1565                ReceiveOperationState::Uneconomical => {
1566                    final_state = Some(FinalReceiveOperationState::Uneconomical);
1567                }
1568                _ => {}
1569            }
1570        }
1571
1572        Ok(final_state.expect("Stream contains one final state"))
1573    }
1574
1575    /// Generate an lnurl for the client. You can optionally specify a gateway
1576    /// to use for testing purposes.
1577    pub async fn generate_lnurl(
1578        &self,
1579        account: Account,
1580        recurringd: SafeUrl,
1581        gateway: Option<SafeUrl>,
1582    ) -> Result<String, GenerateLnurlError> {
1583        // Checked before the lnurl exists: anyone can pay into a published
1584        // key, and a contract locked to an account the primary module cannot
1585        // fund a claim for would strand the payer's money.
1586        if !self
1587            .client_ctx
1588            .supports_account(AmountUnit::BITCOIN, account)
1589        {
1590            return Err(GenerateLnurlError::AccountNotSupported);
1591        }
1592
1593        let gateways = if let Some(gateway) = gateway {
1594            vec![gateway]
1595        } else {
1596            let gateways = self
1597                .module_api
1598                .gateways()
1599                .await
1600                .map_err(|e| GenerateLnurlError::FailedToRequestGateways(e.to_string()))?;
1601
1602            if gateways.is_empty() {
1603                return Err(GenerateLnurlError::NoGatewaysAvailable);
1604            }
1605
1606            gateways
1607        };
1608
1609        let payload = fedimint_core::base32::encode_prefixed(
1610            fedimint_core::base32::FEDIMINT_PREFIX,
1611            &lnurl::LnurlRequest {
1612                federation_id: self.federation_id,
1613                recipient_pk: self.keys(account).lnurl_keypair.public_key(),
1614                aggregate_pk: self.cfg.tpe_agg_pk,
1615                gateways,
1616            },
1617        );
1618
1619        Ok(fedimint_lnurl::encode_lnurl(&format!(
1620            "{recurringd}pay/{payload}"
1621        )))
1622    }
1623
1624    fn spawn_receive_lnurl_task(
1625        &self,
1626        custom_meta_fn: Arc<dyn Fn() -> Value + Send + Sync>,
1627        task_group: &TaskGroup,
1628        client_span: &tracing::Span,
1629    ) {
1630        let module = self.clone();
1631        let api = self.module_api.clone();
1632
1633        task_group.spawn_cancellable_with_span(
1634            client_span.clone(),
1635            "receive_lnurl_task",
1636            async move {
1637                api.wait_for_initialized_connections().await;
1638                loop {
1639                    module.receive_lnurl(custom_meta_fn()).await;
1640                }
1641            },
1642        );
1643    }
1644
1645    async fn receive_lnurl(&self, custom_meta: Value) {
1646        // Read the stream cursor with a short-lived transaction. It must NOT stay open
1647        // across the long-poll below: RocksDB's optimistic transactions validate a
1648        // commit against bounded memtable history, so a transaction held open
1649        // for minutes fails with `DatabaseError::SnapshotTooOld` once enough
1650        // concurrent writes flush that history — not because anything conflicted,
1651        // but because the backend can no longer tell — and the panicking
1652        // `commit_tx()` then killed this task permanently, silently
1653        // stalling every future receive for the lifetime of the process. Long-lived
1654        // clients (daemons) hit this reproducibly under concurrent lnv2 activity.
1655        // See <https://github.com/fedimint/fedimint/issues/8872>.
1656        let stream_index = self
1657            .client_ctx
1658            .module_db()
1659            .begin_transaction_nc()
1660            .await
1661            .get_value(&IncomingContractStreamIndexKey)
1662            .await
1663            .unwrap_or(0);
1664
1665        let (contracts, next_index) = self
1666            .module_api
1667            .await_incoming_contracts(stream_index, 128)
1668            .await;
1669
1670        for contract in &contracts {
1671            // The stream carries every incoming contract the federation funded, and
1672            // anyone can address one to a published lnurl key. Trialling each account's
1673            // key both finds the one the contract is locked to and establishes that it
1674            // is ours at all, before quoting - recovering the keys is local arithmetic,
1675            // the quote reads the wallet. The stream and its cursor are shared, so an
1676            // extra account costs one more trial decryption per contract rather than
1677            // another sweep.
1678            let account = runtime::spawn_blocking({
1679                let keys = self.keys.map(|keys| keys.lnurl_keypair.secret_key());
1680                let tpe_agg_pk = self.cfg.tpe_agg_pk;
1681                let contract = contract.clone();
1682
1683                move || {
1684                    Account::ALL.into_iter().find(|account| {
1685                        recover_contract_keys(
1686                            keys[usize::from(account.index())],
1687                            &tpe_agg_pk,
1688                            &contract,
1689                        )
1690                        .is_some()
1691                    })
1692                }
1693            })
1694            .await;
1695
1696            let Some(account) = account else {
1697                continue;
1698            };
1699
1700            // Skip the contracts the claim fee would swallow, so that unsolicited dust
1701            // never becomes an operation in the first place.
1702            if !self
1703                .is_worth_claiming(account, contract.commitment.amount)
1704                .await
1705            {
1706                warn!(
1707                    target: LOG_CLIENT_MODULE_LNV2,
1708                    amount = %contract.commitment.amount,
1709                    "Ignoring incoming contract, its amount does not cover the claim fee"
1710                );
1711
1712                continue;
1713            }
1714
1715            if let Some(operation_id) = self
1716                .receive_incoming_contract(
1717                    account,
1718                    self.keys(account).lnurl_keypair.secret_key(),
1719                    contract.clone(),
1720                    LightningOperationMeta::LnurlReceive(LnurlReceiveOperationMeta {
1721                        contract: contract.clone(),
1722                        custom_meta: custom_meta.clone(),
1723                    }),
1724                )
1725                .await
1726            {
1727                let _ = self.await_final_receive_operation_state(operation_id).await;
1728            }
1729        }
1730
1731        // Advance the cursor in its own short transaction. This is the only writer of
1732        // this key and it runs in a single sequential loop, so there is no concurrent
1733        // writer to guard against; and because this transaction is short-lived — opened
1734        // after the long-poll and committed immediately — it cannot hit the
1735        // `SnapshotTooOld` failure that a transaction held open across the long-poll
1736        // would, so a plain `commit_tx()` is safe. Ordering is unchanged: the cursor
1737        // only moves after the batch above was processed, and a crash in between
1738        // re-fetches the same batch on the next iteration.
1739        let mut dbtx = self.client_ctx.module_db().begin_transaction().await;
1740
1741        dbtx.insert_entry(&IncomingContractStreamIndexKey, &next_index)
1742            .await;
1743
1744        dbtx.commit_tx().await;
1745    }
1746}
1747
1748#[derive(Error, Debug, Clone, Eq, PartialEq)]
1749pub enum SelectGatewayError {
1750    #[error("Failed to request gateways")]
1751    FailedToRequestGateways(String),
1752    #[error("No gateways are available")]
1753    NoGatewaysAvailable,
1754    #[error("All gateways failed to respond")]
1755    GatewaysUnresponsive,
1756    #[error("No online gateway currently accepts incoming payments for this federation")]
1757    NoGatewayAcceptsReceives,
1758}
1759
1760/// The status of the latest send attempt for an invoice, derived from the
1761/// operation log.
1762#[derive(Debug, Clone, Eq, PartialEq)]
1763pub enum InvoiceSendStatus {
1764    /// No payment operation exists for this invoice.
1765    NotAttempted,
1766    /// A payment operation is still being driven to completion.
1767    InFlight(OperationId),
1768    /// The payment succeeded; paying the invoice again would be a double
1769    /// payment.
1770    Succeeded(OperationId),
1771    /// The payment failed and any funds were refunded.
1772    Failed(OperationId),
1773}
1774
1775#[derive(Error, Debug, Clone, Eq, PartialEq)]
1776pub enum SendPaymentError {
1777    #[error("The primary module only holds a balance for the primary account")]
1778    AccountNotSupported,
1779    #[error("Invoice is missing an amount")]
1780    InvoiceMissingAmount,
1781    #[error("Invoice has expired")]
1782    InvoiceExpired,
1783    #[error("Payment attempt is duplicate")]
1784    DuplicatePaymentAttempt(OperationId),
1785    #[error(transparent)]
1786    SelectGateway(SelectGatewayError),
1787    #[error("Failed to connect to gateway")]
1788    FailedToConnectToGateway(String),
1789    #[error("Gateway does not support this federation")]
1790    FederationNotSupported,
1791    #[error("Gateway fee exceeds the allowed limit")]
1792    GatewayFeeExceedsLimit,
1793    #[error("Gateway expiration time exceeds the allowed limit")]
1794    GatewayExpirationExceedsLimit,
1795    #[error("Failed to request block count")]
1796    FailedToRequestBlockCount(String),
1797    /// The client's balance cannot fund the payment and its fees.
1798    #[error("The client does not have sufficient funds to send the payment")]
1799    InsufficientFunds(#[source] InsufficientBalanceError),
1800    /// The funding transaction could not be submitted for a reason that is
1801    /// not about the balance.
1802    #[error("Failed to fund the payment")]
1803    FailedToFundPayment(String),
1804    #[error("Invoice is for a different currency")]
1805    WrongCurrency {
1806        invoice_currency: Currency,
1807        federation_currency: Currency,
1808    },
1809}
1810
1811/// A failure of [`LightningClientModule::send_with_terms`].
1812#[derive(Error, Debug, Clone, Eq, PartialEq)]
1813#[non_exhaustive]
1814pub enum SendWithTermsError {
1815    /// The gateway's current send terms differ from the ones the caller
1816    /// checked. Carries the current terms so the caller can re-quote.
1817    #[error("Gateway's send terms changed since they were checked")]
1818    TermsChanged {
1819        send_fee: PaymentFee,
1820        expiration_delta: u64,
1821    },
1822    /// Any failure [`LightningClientModule::send`] can report.
1823    #[error(transparent)]
1824    Send(#[from] SendPaymentError),
1825}
1826
1827#[derive(Error, Debug, Clone, Eq, PartialEq)]
1828pub enum ReceiveError {
1829    #[error("The primary module only holds a balance for the primary account")]
1830    AccountNotSupported,
1831    #[error(transparent)]
1832    SelectGateway(SelectGatewayError),
1833    #[error("Failed to connect to gateway")]
1834    FailedToConnectToGateway(String),
1835    #[error("Gateway does not support this federation")]
1836    FederationNotSupported,
1837    #[error("Gateway does not currently accept incoming payments for this federation")]
1838    ReceiveDisabled,
1839    #[error("Gateway fee exceeds the allowed limit")]
1840    GatewayFeeExceedsLimit,
1841    #[error("Amount is too small to cover fees")]
1842    AmountTooSmall,
1843    #[error("Gateway returned an invalid invoice")]
1844    InvalidInvoice,
1845    #[error("Gateway returned an invoice with incorrect amount")]
1846    IncorrectInvoiceAmount,
1847    #[error("Requested invoice expiry exceeds the maximum of one day")]
1848    InvoiceExpiryTooLong,
1849}
1850
1851/// A failure of [`LightningClientModule::receive_with_terms`].
1852#[derive(Error, Debug, Clone, Eq, PartialEq)]
1853#[non_exhaustive]
1854pub enum ReceiveWithTermsError {
1855    /// The gateway's current receive fee differs from the one the caller
1856    /// checked. Carries the current fee so the caller can re-quote.
1857    #[error("Gateway's receive fee changed since it was checked")]
1858    TermsChanged { receive_fee: PaymentFee },
1859    /// Any failure [`LightningClientModule::receive`] can report.
1860    #[error(transparent)]
1861    Receive(#[from] ReceiveError),
1862}
1863
1864#[derive(Error, Debug, Clone, Eq, PartialEq)]
1865pub enum GenerateLnurlError {
1866    #[error("The primary module only holds a balance for the primary account")]
1867    AccountNotSupported,
1868    #[error("No gateways are available")]
1869    NoGatewaysAvailable,
1870    #[error("Failed to request gateways")]
1871    FailedToRequestGateways(String),
1872}
1873
1874#[derive(Error, Debug, Clone, Eq, PartialEq)]
1875pub enum ListGatewaysError {
1876    #[error("Failed to request gateways")]
1877    FailedToListGateways,
1878}
1879
1880#[derive(Error, Debug, Clone, Eq, PartialEq)]
1881pub enum RoutingInfoError {
1882    #[error("Failed to request routing info")]
1883    FailedToRequestRoutingInfo,
1884}
1885
1886/// A failure to work out the largest invoice amount the client could pay in
1887/// full.
1888///
1889/// The answer depends on a gateway's fee schedule as well as on the balance,
1890/// so it can be missing either because no schedule could be obtained or
1891/// because the balance does not reach the smallest payable amount once both
1892/// fees are applied.
1893#[derive(Debug, Error)]
1894#[non_exhaustive]
1895pub enum SpendableAmountError {
1896    /// The caller named a gateway and its routing information could not be
1897    /// fetched, so there is no fee schedule to compute against.
1898    #[error(transparent)]
1899    RoutingInfo(#[from] RoutingInfoError),
1900
1901    /// The caller named a gateway and it answered, but it does not serve this
1902    /// federation.
1903    #[error("The gateway does not support this federation")]
1904    FederationNotSupported,
1905
1906    /// The caller named no gateway and none could be picked automatically, so
1907    /// there is no fee schedule to compute against.
1908    #[error(transparent)]
1909    SelectGateway(#[from] SelectGatewayError),
1910
1911    /// The gateway's default send fee is above the limit this module accepts,
1912    /// so an amount computed against it would not be payable through it.
1913    #[error("The gateway's default send fee {fee} exceeds the limit {limit}")]
1914    SendFeeExceedsLimit {
1915        /// The default send fee the gateway announced.
1916        fee: PaymentFee,
1917        /// The largest default send fee this module accepts.
1918        limit: PaymentFee,
1919    },
1920
1921    /// The fee probe failed for a reason unrelated to the balance.
1922    #[error("The fee quote for the payment failed")]
1923    Quote(#[source] TransactionSubmitError),
1924
1925    /// The balance cannot cover the smallest payable amount plus the gateway
1926    /// and federation fees, so there is no amount to send.
1927    #[error("The balance {balance} is too low to send any amount after fees")]
1928    BalanceTooLow {
1929        /// The balance the answer was computed against.
1930        balance: Amount,
1931    },
1932}
1933
1934#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
1935pub enum LightningClientStateMachines {
1936    Send(SendStateMachine),
1937    Receive(ReceiveStateMachine),
1938}
1939
1940impl IntoDynInstance for LightningClientStateMachines {
1941    type DynType = DynState;
1942
1943    fn into_dyn(self, instance_id: ModuleInstanceId) -> Self::DynType {
1944        DynState::from_typed(instance_id, self)
1945    }
1946}
1947
1948impl State for LightningClientStateMachines {
1949    type ModuleContext = LightningClientContext;
1950
1951    fn transitions(
1952        &self,
1953        context: &Self::ModuleContext,
1954        global_context: &DynGlobalClientContext,
1955    ) -> Vec<StateTransition<Self>> {
1956        match self {
1957            LightningClientStateMachines::Send(state) => {
1958                sm_enum_variant_translation!(
1959                    state.transitions(context, global_context),
1960                    LightningClientStateMachines::Send
1961                )
1962            }
1963            LightningClientStateMachines::Receive(state) => {
1964                sm_enum_variant_translation!(
1965                    state.transitions(context, global_context),
1966                    LightningClientStateMachines::Receive
1967                )
1968            }
1969        }
1970    }
1971
1972    fn operation_id(&self) -> OperationId {
1973        match self {
1974            LightningClientStateMachines::Send(state) => state.operation_id(),
1975            LightningClientStateMachines::Receive(state) => state.operation_id(),
1976        }
1977    }
1978}
1979
1980/// The claim keypair and aggregate decryption key of an incoming contract
1981/// addressed to `sk`, or none when it is not ours.
1982///
1983/// Verifying the key is four pairings, so callers run this off the async
1984/// workers.
1985fn recover_contract_keys(
1986    sk: SecretKey,
1987    tpe_agg_pk: &AggregatePublicKey,
1988    contract: &IncomingContract,
1989) -> Option<(Keypair, AggregateDecryptionKey)> {
1990    let tweak = ecdh::SharedSecret::new(&contract.commitment.ephemeral_pk, &sk);
1991
1992    let encryption_seed = tweak
1993        .secret_bytes()
1994        .consensus_hash::<sha256::Hash>()
1995        .to_byte_array();
1996
1997    let claim_keypair = sk
1998        .mul_tweak(&Scalar::from_be_bytes(tweak.secret_bytes()).expect("Within curve order"))
1999        .expect("Tweak is valid")
2000        .keypair(secp256k1::SECP256K1);
2001
2002    if claim_keypair.public_key() != contract.commitment.claim_pk {
2003        return None; // The claim key is not derived from our pk
2004    }
2005
2006    let agg_decryption_key = derive_agg_dk(tpe_agg_pk, &encryption_seed);
2007
2008    if !contract.verify_agg_decryption_key(tpe_agg_pk, &agg_decryption_key) {
2009        return None; // The decryption key is not derived from our pk
2010    }
2011
2012    contract.decrypt_preimage(&agg_decryption_key)?;
2013
2014    Some((claim_keypair, agg_decryption_key))
2015}