Skip to main content

fedimint_gateway_server/
lib.rs

1#![deny(clippy::pedantic)]
2#![allow(clippy::cast_possible_truncation)]
3#![allow(clippy::cast_possible_wrap)]
4#![allow(clippy::cast_sign_loss)]
5#![allow(clippy::default_trait_access)]
6#![allow(clippy::doc_markdown)]
7#![allow(clippy::missing_errors_doc)]
8#![allow(clippy::missing_panics_doc)]
9#![allow(clippy::module_name_repetitions)]
10#![allow(clippy::must_use_candidate)]
11#![allow(clippy::return_self_not_must_use)]
12#![allow(clippy::similar_names)]
13#![allow(clippy::too_many_lines)]
14#![allow(clippy::large_futures)]
15#![allow(clippy::struct_field_names)]
16
17pub mod client;
18pub mod config;
19pub mod envs;
20mod error;
21mod events;
22mod federation_manager;
23mod federation_status;
24mod iroh_server;
25mod metrics;
26mod rate_limit;
27mod registration_health;
28pub mod rpc_server;
29mod types;
30
31use std::collections::{BTreeMap, BTreeSet};
32use std::env;
33use std::fmt::Display;
34use std::net::SocketAddr;
35use std::str::FromStr;
36use std::sync::Arc;
37use std::time::{Duration, UNIX_EPOCH};
38
39use anyhow::{Context, anyhow};
40use async_trait::async_trait;
41use bitcoin::hashes::sha256;
42use bitcoin::{Address, Network, Txid, secp256k1};
43use clap::Parser;
44use client::GatewayClientBuilder;
45pub use config::GatewayParameters;
46use config::{DatabaseBackend, GatewayOpts};
47use envs::FM_GATEWAY_SKIP_WAIT_FOR_SYNC_ENV;
48use error::FederationNotConnected;
49use events::ALL_GATEWAY_EVENTS;
50use federation_manager::FederationManager;
51use fedimint_bip39::{Bip39RootSecretStrategy, Language, Mnemonic};
52use fedimint_bitcoind::bitcoincore::BitcoindClient;
53use fedimint_bitcoind::{EsploraClient, IBitcoindRpc};
54use fedimint_client::module_init::ClientModuleInitRegistry;
55use fedimint_client::secret::RootSecretStrategy;
56use fedimint_client::{Client, ClientHandleArc};
57use fedimint_core::base32::{self, FEDIMINT_PREFIX};
58use fedimint_core::config::FederationId;
59use fedimint_core::core::{Account, OperationId};
60use fedimint_core::db::{Committable, Database, DatabaseTransaction, apply_migrations};
61use fedimint_core::envs::is_env_var_set;
62use fedimint_core::invite_code::InviteCode;
63use fedimint_core::module::CommonModuleInit;
64use fedimint_core::module::registry::ModuleDecoderRegistry;
65use fedimint_core::rustls::install_crypto_provider;
66use fedimint_core::secp256k1::PublicKey;
67use fedimint_core::secp256k1::schnorr::Signature;
68use fedimint_core::task::{TaskGroup, TaskHandle, TaskShutdownToken, sleep, timeout};
69use fedimint_core::time::duration_since_epoch;
70use fedimint_core::util::backoff_util::fibonacci_max_one_hour;
71use fedimint_core::util::{FmtCompact, SafeUrl, Spanned, retry};
72use fedimint_core::{
73    Amount, BitcoinAmountOrAll, PeerId, TieredCounts, crit, fedimint_build_code_version_env,
74    get_network_for_address,
75};
76use fedimint_eventlog::{DBTransactionEventLogExt, EventLogId, StructuredPaymentEvents};
77use fedimint_gateway_common::{
78    BackupPayload, ChainSource, CloseChannelsWithPeerRequest, CloseChannelsWithPeerResponse,
79    ConnectFedPayload, ConnectPeerRequest, ConnectorType, CreateInvoiceForOperatorPayload,
80    CreateOfferPayload, CreateOfferResponse, DepositAddressPayload, DepositAddressRecheckPayload,
81    FederationBalanceInfo, FederationConfig, FederationInfo, GatewayBalances, GatewayFedConfig,
82    GatewayInfo, GetInvoiceRequest, GetInvoiceResponse, LeaveFedPayload, LightningInfo,
83    LightningMode, ListTransactionsPayload, ListTransactionsResponse, MnemonicResponse,
84    OpenChannelRequest, PayInvoiceForOperatorPayload, PayOfferPayload, PayOfferResponse,
85    PaymentLogPayload, PaymentLogResponse, PaymentPolicy, PaymentPolicyGuard, PaymentStats,
86    PaymentSummaryPayload, PaymentSummaryResponse, PeginFromOnchainPayload, ReceiveEcashPayload,
87    ReceiveEcashResponse, RegisteredProtocol, SendOnchainRequest, SetChannelFeesRequest,
88    SetFeesPayload, SetMnemonicPayload, SetPaymentPolicyPayload, SpendEcashPayload,
89    SpendEcashResponse, V1_API_ENDPOINT, WithdrawPayload, WithdrawPreviewPayload,
90    WithdrawPreviewResponse, WithdrawResponse, WithdrawToOnchainPayload,
91};
92use fedimint_gateway_server_db::{GatewayDbtxNcExt as _, get_gatewayd_database_migrations};
93pub use fedimint_gateway_ui::IAdminGateway;
94use fedimint_gw_client::events::compute_lnv1_stats;
95use fedimint_gw_client::pay::{OutgoingPaymentError, OutgoingPaymentErrorType};
96use fedimint_gw_client::{
97    GatewayClientModule, GatewayClientV1Error, GatewayExtPayStates, GatewayExtReceiveStates, Htlc,
98    IGatewayClientV1, SwapParameters,
99};
100use fedimint_gwv2_client::events::compute_lnv2_stats;
101use fedimint_gwv2_client::{
102    EXPIRATION_DELTA_MINIMUM_V2, FinalReceiveState, GatewayClientModuleV2, GatewayClientV2Error,
103    IGatewayClientV2,
104};
105use fedimint_lightning::ldk::MnemonicSource;
106use fedimint_lightning::lnd::GatewayLndClient;
107use fedimint_lightning::{
108    CreateInvoiceRequest, ILnRpcClient, InterceptPaymentRequest, InterceptPaymentResponse,
109    InvoiceDescription, LightningContext, LightningRpcError, LnRpcTracked, Lnv2HoldInvoiceFilter,
110    PayInvoiceResponse, PaymentAction, RouteHtlcStream, ldk,
111};
112use fedimint_ln_client::pay::PaymentData;
113use fedimint_ln_common::config::LightningClientConfig;
114use fedimint_ln_common::contracts::outgoing::OutgoingContractAccount;
115use fedimint_ln_common::contracts::{IdentifiableContract, Preimage};
116use fedimint_ln_common::{LightningCommonInit, PreimageAuth};
117use fedimint_lnurl::VerifyResponse;
118use fedimint_lnv2_common::Bolt11InvoiceDescription;
119use fedimint_lnv2_common::contracts::{IncomingContract, PaymentImage};
120use fedimint_lnv2_common::gateway_api::{
121    CreateBolt11InvoicePayload, MAX_INVOICE_EXPIRY_SECS, PaymentFee, RoutingInfo,
122    SendPaymentPayload,
123};
124use fedimint_logging::LOG_GATEWAY;
125use fedimint_mint_client::{MintClientInit, MintClientModule, OOBNotes, ReissueExternalNotesState};
126use fedimint_mintv2_client::{
127    MintClientInit as MintV2ClientInit, MintClientModule as MintV2ClientModule,
128};
129use fedimint_wallet_client::{PegOutFees, WalletClientInit, WalletClientModule, WithdrawState};
130use futures::stream::StreamExt;
131use lightning_invoice::{Bolt11Invoice, RoutingFees};
132use rand::rngs::OsRng;
133use tokio::sync::RwLock;
134use tracing::{debug, info, info_span, warn};
135
136use crate::envs::FM_GATEWAY_MNEMONIC_ENV;
137use crate::error::{AdminGatewayError, LNv1Error, LNv2Error, PublicGatewayError};
138use crate::events::get_events_for_duration;
139use crate::rate_limit::TokenBucketRateLimiter;
140use crate::registration_health::RegistrationHealthTracker;
141use crate::rpc_server::run_webserver;
142use crate::types::PrettyInterceptPaymentRequest;
143
144/// How long a gateway announcement stays valid
145const GW_ANNOUNCEMENT_TTL: Duration = Duration::from_mins(10);
146
147/// The default number of route hints that the legacy gateway provides for
148/// invoice creation.
149const DEFAULT_NUM_ROUTE_HINTS: u32 = 1;
150
151/// Default maximum burst of requests to the public invoice creation endpoint.
152const DEFAULT_INVOICE_RATE_LIMIT_BURST: u32 = 50;
153
154/// Default sustained number of requests per second to the public invoice
155/// creation endpoint.
156const DEFAULT_INVOICE_RATE_LIMIT_PER_SECOND: u32 = 5;
157
158/// Default Bitcoin network for testing purposes.
159pub const DEFAULT_NETWORK: Network = Network::Regtest;
160
161/// How long code that needs to talk to the lightning node backs off before
162/// re-checking whether the gateway has (re)connected to it.
163const LIGHTNING_CONTEXT_RETRY_INTERVAL: Duration = Duration::from_secs(5);
164
165/// How long an LNURL-verify request that asked to wait blocks before reporting
166/// the payment as not settled yet.
167///
168/// The payment being waited for may never arrive, so the wait needs an upper
169/// bound to stop callers from parking a request handler indefinitely. Reporting
170/// "not settled" on expiry is a regular LNURL-verify response, so clients
171/// simply poll again.
172const VERIFY_WAIT_TIMEOUT: Duration = Duration::from_secs(30);
173
174pub type Result<T> = std::result::Result<T, PublicGatewayError>;
175pub type AdminResult<T> = std::result::Result<T, AdminGatewayError>;
176
177/// Name of the gateway's database that is used for metadata and configuration
178/// storage.
179const DB_FILE: &str = "gatewayd.db";
180
181/// Name of the folder that the gateway uses to store its node database when
182/// running in LDK mode.
183const LDK_NODE_DB_FOLDER: &str = "ldk_node";
184
185/// ```mermaid
186/// graph LR
187/// classDef virtual fill:#fff,stroke-dasharray: 5 5
188///
189///    NotConfigured -- create or recover wallet --> Disconnected
190///    Disconnected -- establish lightning connection --> Connected
191///    Connected -- load federation clients --> Running
192///    Connected -- not synced to chain --> Syncing
193///    Syncing -- load federation clients --> Running
194///    Running -- disconnected from lightning node --> Disconnected
195///    Running -- shutdown initiated --> ShuttingDown
196/// ```
197#[derive(Clone, Debug)]
198pub enum GatewayState {
199    NotConfigured {
200        // Broadcast channel to alert gateway background threads that the mnemonic has been
201        // created/set, and how it was obtained.
202        mnemonic_sender: tokio::sync::broadcast::Sender<MnemonicSource>,
203    },
204    Disconnected,
205    Syncing,
206    Connected,
207    Running {
208        lightning_context: LightningContext,
209    },
210    ShuttingDown {
211        lightning_context: LightningContext,
212    },
213}
214
215impl Display for GatewayState {
216    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
217        match self {
218            GatewayState::NotConfigured { .. } => write!(f, "NotConfigured"),
219            GatewayState::Disconnected => write!(f, "Disconnected"),
220            GatewayState::Syncing => write!(f, "Syncing"),
221            GatewayState::Connected => write!(f, "Connected"),
222            GatewayState::Running { .. } => write!(f, "Running"),
223            GatewayState::ShuttingDown { .. } => write!(f, "ShuttingDown"),
224        }
225    }
226}
227
228/// Helper struct for storing the registration parameters for LNv1 for each
229/// network protocol.
230#[derive(Debug, Clone)]
231struct Registration {
232    /// The url to advertise in the registration that clients can use to connect
233    endpoint_url: SafeUrl,
234
235    /// Keypair that was used to register the gateway registration
236    keypair: secp256k1::Keypair,
237}
238
239impl Registration {
240    pub async fn new(db: &Database, endpoint_url: SafeUrl, protocol: RegisteredProtocol) -> Self {
241        let keypair = Gateway::load_or_create_gateway_keypair(db, protocol).await;
242        Self {
243            endpoint_url,
244            keypair,
245        }
246    }
247}
248
249#[bon::bon]
250impl Gateway {
251    /// Construct a [`Gateway`] using a fluent builder API.
252    ///
253    /// # Example
254    /// ```ignore
255    /// let gateway = Gateway::builder(lightning_mode, client_builder, gateway_db)
256    ///     .listen(addr)
257    ///     .api_addr(url)
258    ///     .bcrypt_password_hash(hash)
259    ///     .network(Network::Regtest)
260    ///     .gateway_state(state)
261    ///     .chain_source(chain_source)
262    ///     .build()
263    ///     .await?;
264    /// ```
265    #[builder(start_fn = builder, finish_fn = build)]
266    pub async fn new_with_builder(
267        #[builder(start_fn)] lightning_mode: LightningMode,
268        #[builder(start_fn)] client_builder: GatewayClientBuilder,
269        #[builder(start_fn)] gateway_db: Database,
270        bcrypt_password_hash: bcrypt::HashParts,
271        bcrypt_liquidity_manager_password_hash: Option<bcrypt::HashParts>,
272        gateway_state: GatewayState,
273        chain_source: ChainSource,
274        #[builder(default = ([127, 0, 0, 1], 80).into())] listen: SocketAddr,
275        api_addr: Option<SafeUrl>,
276        #[builder(default = DEFAULT_NETWORK)] network: Network,
277        #[builder(default = DEFAULT_NUM_ROUTE_HINTS)] num_route_hints: u32,
278        #[builder(default = PaymentFee::TRANSACTION_FEE_DEFAULT)] default_routing_fees: PaymentFee,
279        #[builder(default = PaymentFee::TRANSACTION_FEE_DEFAULT)]
280        default_transaction_fees: PaymentFee,
281        iroh_listen: Option<SocketAddr>,
282        iroh_dns: Option<SafeUrl>,
283        #[builder(default)] iroh_relays: Vec<SafeUrl>,
284        metrics_listen: Option<SocketAddr>,
285    ) -> anyhow::Result<Gateway> {
286        let versioned_api = api_addr.map(|addr| {
287            addr.join(V1_API_ENDPOINT)
288                .expect("Failed to version gateway API address")
289        });
290
291        let metrics_listen = metrics_listen.unwrap_or_else(|| {
292            SocketAddr::new(
293                std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST),
294                listen.port() + 1,
295            )
296        });
297
298        Gateway::new(
299            lightning_mode,
300            GatewayParameters {
301                listen,
302                versioned_api,
303                bcrypt_password_hash,
304                bcrypt_liquidity_manager_password_hash,
305                network,
306                num_route_hints,
307                default_routing_fees,
308                default_transaction_fees,
309                iroh_listen,
310                iroh_dns,
311                iroh_relays,
312                skip_setup: true,
313                metrics_listen,
314                invoice_rate_limit_burst: DEFAULT_INVOICE_RATE_LIMIT_BURST,
315                invoice_rate_limit_per_second: DEFAULT_INVOICE_RATE_LIMIT_PER_SECOND,
316            },
317            gateway_db,
318            client_builder,
319            gateway_state,
320            chain_source,
321            MnemonicSource::Existing,
322        )
323        .await
324    }
325}
326
327/// The action to take after handling a payment stream.
328enum ReceivePaymentStreamAction {
329    RetryAfterDelay,
330    NoRetry,
331}
332
333#[derive(Clone)]
334pub struct Gateway {
335    /// The gateway's federation manager.
336    federation_manager: Arc<RwLock<FederationManager>>,
337
338    /// The mode that specifies the lightning connection parameters
339    lightning_mode: LightningMode,
340
341    /// The current state of the Gateway.
342    state: Arc<RwLock<GatewayState>>,
343
344    /// Builder struct that allows the gateway to build a Fedimint client, which
345    /// handles the communication with a federation.
346    client_builder: GatewayClientBuilder,
347
348    /// Database for Gateway metadata.
349    gateway_db: Database,
350
351    /// The socket the gateway listens on.
352    listen: SocketAddr,
353
354    /// The socket the gateway's metrics server listens on.
355    metrics_listen: SocketAddr,
356
357    /// The task group for all tasks related to the gateway.
358    task_group: TaskGroup,
359
360    /// The bcrypt password hash used to authenticate the gateway.
361    bcrypt_password_hash: String,
362
363    /// The bcrypt password hash used to authenticate the gateway liquidity
364    /// manager.
365    bcrypt_liquidity_manager_password_hash: Option<String>,
366
367    /// The number of route hints to include in LNv1 invoices.
368    num_route_hints: u32,
369
370    /// The Bitcoin network that the Lightning network is configured to.
371    network: Network,
372
373    /// The source of the Bitcoin blockchain data
374    chain_source: ChainSource,
375
376    /// The default routing fees for new federations
377    default_routing_fees: PaymentFee,
378
379    /// The default transaction fees for new federations
380    default_transaction_fees: PaymentFee,
381
382    /// The secret key for the Iroh `Endpoint`
383    iroh_sk: iroh::SecretKey,
384
385    /// The socket that the gateway listens on for the Iroh `Endpoint`
386    iroh_listen: Option<SocketAddr>,
387
388    /// Optional DNS server used for discovery of the Iroh `Endpoint`
389    iroh_dns: Option<SafeUrl>,
390
391    /// List of additional relays that can be used to establish a connection to
392    /// the Iroh `Endpoint`
393    iroh_relays: Vec<SafeUrl>,
394
395    /// A map of the network protocols the gateway supports to the data needed
396    /// for registering with a federation.
397    registrations: BTreeMap<RegisteredProtocol, Registration>,
398
399    /// Detail-free retained results of LNv1 federation registration attempts.
400    registration_health: RegistrationHealthTracker,
401
402    /// Rate limiter for the public invoice creation endpoint.
403    invoice_rate_limiter: Arc<TokenBucketRateLimiter>,
404
405    /// Locks the payment hash of each HOLD invoice whose delivery is being
406    /// handled, so that a duplicate delivery is dropped; see
407    /// [`Self::handle_lightning_payment`].
408    lnv2_hold_invoice_lock_pool: Arc<lockable::LockPool<sha256::Hash>>,
409
410    /// Serializes payment policy changes against the funding of the payments
411    /// those policies admit.
412    payment_policy_lock: Arc<RwLock<()>>,
413
414    /// How the mnemonic was obtained at startup. When the gateway starts
415    /// unconfigured, the source of the mnemonic set later arrives through the
416    /// `mnemonic_sender` channel instead.
417    mnemonic_source: MnemonicSource,
418}
419
420impl std::fmt::Debug for Gateway {
421    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
422        f.debug_struct("Gateway")
423            .field("federation_manager", &self.federation_manager)
424            .field("state", &self.state)
425            .field("client_builder", &self.client_builder)
426            .field("gateway_db", &self.gateway_db)
427            .field("listen", &self.listen)
428            .field("registrations", &self.registrations)
429            .finish_non_exhaustive()
430    }
431}
432
433/// Internal helper for on-chain withdrawal calculations
434struct WithdrawDetails {
435    amount: Amount,
436    mint_fees: Option<Amount>,
437    peg_out_fees: PegOutFees,
438    flat_peg_out_fee: bool,
439}
440
441/// Waits for the ecash change of a successful withdrawal to be issued.
442///
443/// A withdrawal is reported successful once its transaction is accepted, but
444/// the primary module issues the change from funding it asynchronously. Until
445/// then the change is missing from the balance, so callers that read the
446/// balance right after a withdrawal would see it understated by the change.
447/// The withdrawal itself has already succeeded, so a failure here is only
448/// logged.
449async fn await_withdraw_change(
450    client: &ClientHandleArc,
451    operation_id: OperationId,
452    change: Vec<fedimint_core::OutPoint>,
453) {
454    if let Err(err) = client
455        .await_primary_bitcoin_module_outputs(operation_id, change)
456        .await
457    {
458        warn!(
459            target: LOG_GATEWAY,
460            err = %err.fmt_compact(),
461            ?operation_id,
462            "Failed to await withdrawal change outputs"
463        );
464    }
465}
466
467/// Executes a withdrawal using the walletv2 module
468async fn withdraw_v2(
469    client: &ClientHandleArc,
470    wallet_module: &fedimint_walletv2_client::WalletClientModule,
471    address: &Address,
472    amount: BitcoinAmountOrAll,
473    quoted_fee: Option<bitcoin::Amount>,
474) -> AdminResult<WithdrawResponse> {
475    let current_fee =
476        wallet_module
477            .send_fee()
478            .await
479            .map_err(|e| AdminGatewayError::WithdrawError {
480                failure_reason: e.fmt_compact().to_string(),
481            })?;
482
483    // The federation rejects any send whose fee is below its current send fee,
484    // so a quote that has gone stale would only produce a doomed transaction.
485    // Sending with the quoted fee otherwise keeps the operator paying exactly
486    // what they confirmed in the preview.
487    let fee = match quoted_fee {
488        Some(quoted_fee) if quoted_fee < current_fee => {
489            return Err(AdminGatewayError::WithdrawError {
490                failure_reason: format!(
491                    "The on-chain fee increased from {} to {} sats since the preview, please preview the withdrawal again",
492                    quoted_fee.to_sat(),
493                    current_fee.to_sat()
494                ),
495            });
496        }
497        Some(quoted_fee) => quoted_fee,
498        None => current_fee,
499    };
500
501    let withdraw_amount = match amount {
502        BitcoinAmountOrAll::All => {
503            let balance = client
504                .get_balance_for_btc(Account::Primary)
505                .await
506                .map_err(|err| {
507                    AdminGatewayError::Unexpected(anyhow!(
508                        "Balance not available: {}",
509                        err.fmt_compact()
510                    ))
511                })?;
512
513            // The on-chain fee is only part of the cost: funding the wallet
514            // output also incurs the federation's per-note fees. `fee` is
515            // passed on to `send` below so both are computed against the same
516            // on-chain fee.
517            wallet_module
518                .max_sendable_amount(Account::Primary, balance, fee)
519                .await
520                .map_err(|err| AdminGatewayError::WithdrawError {
521                    failure_reason: format!(
522                        "Insufficient funds. Balance: {balance} Fee: {fee}: {}",
523                        err.fmt_compact()
524                    ),
525                })?
526        }
527        BitcoinAmountOrAll::Amount(a) => a,
528    };
529
530    let operation_id = wallet_module
531        .send(
532            Account::Primary,
533            address.as_unchecked().clone(),
534            withdraw_amount,
535            Some(fee),
536            serde_json::Value::Null,
537        )
538        .await
539        .map_err(|e| AdminGatewayError::WithdrawError {
540            failure_reason: e.fmt_compact().to_string(),
541        })?;
542
543    let result = wallet_module
544        .await_final_send_operation_state(operation_id)
545        .await
546        .map_err(|e| AdminGatewayError::WithdrawError {
547            failure_reason: e.fmt_compact().to_string(),
548        })?;
549
550    let fees = PegOutFees::from_amount(fee);
551
552    match result {
553        fedimint_walletv2_client::FinalSendOperationState::Success(txid) => {
554            if let Some(Ok(fedimint_walletv2_client::WalletOperationMeta::Send(meta))) = client
555                .operation_log()
556                .get_operation(operation_id)
557                .await
558                .map(|operation| operation.try_meta())
559            {
560                await_withdraw_change(
561                    client,
562                    operation_id,
563                    meta.change_outpoint_range.into_iter().collect(),
564                )
565                .await;
566            }
567            info!(target: LOG_GATEWAY, amount = %withdraw_amount, address = %address, "Sent funds via walletv2");
568            Ok(WithdrawResponse { txid, fees })
569        }
570        fedimint_walletv2_client::FinalSendOperationState::Aborted => {
571            Err(AdminGatewayError::WithdrawError {
572                failure_reason: "Withdrawal transaction was aborted".to_string(),
573            })
574        }
575        fedimint_walletv2_client::FinalSendOperationState::Failure => {
576            Err(AdminGatewayError::WithdrawError {
577                failure_reason: "Withdrawal failed".to_string(),
578            })
579        }
580    }
581}
582
583/// Calculates an estimated max withdrawable amount on-chain
584async fn calculate_max_withdrawable(
585    client: &ClientHandleArc,
586    address: &Address,
587) -> AdminResult<WithdrawDetails> {
588    let balance = client
589        .get_balance_for_btc(Account::Primary)
590        .await
591        .map_err(|err| {
592            AdminGatewayError::Unexpected(anyhow!("Balance not available: {}", err.fmt_compact()))
593        })?;
594
595    if let Ok(wallet_module) =
596        client.get_first_module::<fedimint_walletv2_client::WalletClientModule>()
597    {
598        let fee = wallet_module
599            .send_fee()
600            .await
601            .map_err(|e| AdminGatewayError::WithdrawError {
602                failure_reason: e.fmt_compact().to_string(),
603            })?;
604
605        let max_withdrawable = wallet_module
606            .max_sendable_amount(Account::Primary, balance, fee)
607            .await
608            .map_err(|err| AdminGatewayError::WithdrawError {
609                failure_reason: err.fmt_compact().to_string(),
610            })?;
611
612        // Everything the balance does not become an on-chain payment or miner
613        // fee is the federation fee: the wallet output fee, the mint input
614        // fees on the funding notes, any change output fees and dust. This is
615        // exact by construction, so it needs no separate estimate.
616        let federation_fees = balance
617            .saturating_sub(Amount::from_sats(max_withdrawable.to_sat()))
618            .saturating_sub(Amount::from_sats(fee.to_sat()));
619
620        return Ok(WithdrawDetails {
621            amount: Amount::from_sats(max_withdrawable.to_sat()),
622            mint_fees: Some(federation_fees),
623            peg_out_fees: PegOutFees::from_amount(fee),
624            flat_peg_out_fee: true,
625        });
626    }
627
628    let Ok(wallet_module) = client.get_first_module::<WalletClientModule>() else {
629        return Err(AdminGatewayError::Unexpected(anyhow!(
630            "No wallet module found"
631        )));
632    };
633
634    let (max_withdrawable, peg_out_fees) = wallet_module
635        .max_withdrawable_amount(address, balance)
636        .await
637        .map_err(|err| AdminGatewayError::WithdrawError {
638            failure_reason: err.fmt_compact().to_string(),
639        })?;
640
641    // Everything the balance does not become an on-chain payment or miner fee
642    // is the federation fee: the peg-out output fee, the mint input fees on the
643    // funding notes, any change output fees and dust. This is exact by
644    // construction, so it needs no separate estimate.
645    let federation_fees = balance
646        .saturating_sub(Amount::from_sats(max_withdrawable.to_sat()))
647        .saturating_sub(Amount::from_sats(peg_out_fees.amount().to_sat()));
648
649    Ok(WithdrawDetails {
650        amount: Amount::from_sats(max_withdrawable.to_sat()),
651        mint_fees: Some(federation_fees),
652        peg_out_fees,
653        flat_peg_out_fee: false,
654    })
655}
656
657impl Gateway {
658    /// Returns a bitcoind client using the credentials that were passed in from
659    /// the environment variables.
660    fn get_bitcoind_client(
661        opts: &GatewayOpts,
662        network: bitcoin::Network,
663        gateway_id: &PublicKey,
664    ) -> anyhow::Result<(BitcoindClient, ChainSource)> {
665        let bitcoind_username = opts
666            .bitcoind_username
667            .clone()
668            .expect("FM_BITCOIND_URL is set but FM_BITCOIND_USERNAME is not");
669        let url = opts.bitcoind_url.clone().expect("No bitcoind url set");
670        let password = opts
671            .bitcoind_password
672            .clone()
673            .expect("FM_BITCOIND_URL is set but FM_BITCOIND_PASSWORD is not");
674
675        let chain_source = ChainSource::Bitcoind {
676            username: bitcoind_username.clone(),
677            password: password.clone(),
678            server_url: url.clone(),
679        };
680        let wallet_name = format!("gatewayd-{gateway_id}");
681        let client = BitcoindClient::new(&url, bitcoind_username, password, &wallet_name, network)?;
682        Ok((client, chain_source))
683    }
684
685    /// Default function for creating a gateway with the `Mint`, `Wallet`, and
686    /// `Gateway` modules.
687    pub async fn new_with_default_modules(
688        mnemonic_sender: tokio::sync::broadcast::Sender<MnemonicSource>,
689    ) -> anyhow::Result<Gateway> {
690        let mut opts = GatewayOpts::parse();
691        opts.resolve_secret_inputs()?;
692        let gateway_parameters = opts.to_gateway_parameters()?;
693        let decoders = ModuleDecoderRegistry::default();
694
695        let db_path = opts.data_dir.join(DB_FILE);
696        let gateway_db = match opts.db_backend {
697            DatabaseBackend::RocksDb => {
698                debug!(target: LOG_GATEWAY, "Using RocksDB database backend");
699                Database::new(
700                    fedimint_rocksdb::RocksDb::build(db_path).open().await?,
701                    decoders,
702                )
703            }
704            DatabaseBackend::CursedRedb => {
705                debug!(target: LOG_GATEWAY, "Using CursedRedb database backend");
706                Database::new(
707                    fedimint_cursed_redb::MemAndRedb::new(db_path).await?,
708                    decoders,
709                )
710            }
711        };
712
713        // Apply database migrations before using the database to ensure old database
714        // structures are readable.
715        apply_migrations(
716            &gateway_db,
717            (),
718            "gatewayd".to_string(),
719            get_gatewayd_database_migrations(),
720            None,
721            None,
722        )
723        .await?;
724
725        // For legacy reasons, we use the http id for the unique identifier of the
726        // bitcoind watch-only wallet
727        let http_id = Self::load_or_create_gateway_keypair(&gateway_db, RegisteredProtocol::Http)
728            .await
729            .public_key();
730        let (dyn_bitcoin_rpc, chain_source) =
731            match (opts.bitcoind_url.as_ref(), opts.esplora_url.as_ref()) {
732                (Some(_), None) => {
733                    let (client, chain_source) =
734                        Self::get_bitcoind_client(&opts, gateway_parameters.network, &http_id)?;
735                    (client.into_dyn(), chain_source)
736                }
737                (None, Some(url)) => {
738                    let client = EsploraClient::new(url)
739                        .expect("Could not create EsploraClient")
740                        .into_dyn();
741                    let chain_source = ChainSource::Esplora {
742                        server_url: url.clone(),
743                    };
744                    (client, chain_source)
745                }
746                (Some(_), Some(_)) => {
747                    // Use bitcoind by default if both are set
748                    let (client, chain_source) =
749                        Self::get_bitcoind_client(&opts, gateway_parameters.network, &http_id)?;
750                    (client.into_dyn(), chain_source)
751                }
752                _ => unreachable!("ArgGroup already enforced XOR relation"),
753            };
754
755        // Gateway module will be attached when the federation clients are created
756        // because the LN RPC will be injected with `GatewayClientGen`.
757        let mut registry = ClientModuleInitRegistry::new();
758        registry.attach(MintClientInit);
759        registry.attach(MintV2ClientInit);
760        registry.attach(WalletClientInit::new(dyn_bitcoin_rpc));
761        registry.attach(fedimint_walletv2_client::WalletClientInit);
762
763        let client_builder =
764            GatewayClientBuilder::new(opts.data_dir.clone(), registry, opts.db_backend).await?;
765
766        let (gateway_state, mnemonic_source) = if Self::load_mnemonic(&gateway_db).await.is_some() {
767            (GatewayState::Disconnected, MnemonicSource::Existing)
768        } else {
769            // Generate a mnemonic or use one from an environment variable if `skip_setup`
770            // is true
771            if gateway_parameters.skip_setup {
772                let (mnemonic, mnemonic_source) = if let Ok(words) =
773                    std::env::var(FM_GATEWAY_MNEMONIC_ENV)
774                {
775                    info!(target: LOG_GATEWAY, "Using provided mnemonic from environment variable");
776                    let mnemonic = Mnemonic::parse_in_normalized(Language::English, words.as_str())
777                        .map_err(|e| {
778                            AdminGatewayError::MnemonicError(anyhow!(format!(
779                                "Seed phrase provided in environment was invalid {e:?}"
780                            )))
781                        })?;
782                    (mnemonic, MnemonicSource::Existing)
783                } else {
784                    debug!(target: LOG_GATEWAY, "Generating mnemonic and writing entropy to client storage");
785                    (
786                        Bip39RootSecretStrategy::<12>::random(&mut OsRng),
787                        MnemonicSource::Generated,
788                    )
789                };
790
791                Client::store_encodable_client_secret(&gateway_db, mnemonic.to_entropy())
792                    .await
793                    .map_err(|err| AdminGatewayError::MnemonicError(err.into()))?;
794                (GatewayState::Disconnected, mnemonic_source)
795            } else {
796                // The mnemonic's source arrives through `mnemonic_sender` once
797                // it is set
798                (
799                    GatewayState::NotConfigured { mnemonic_sender },
800                    MnemonicSource::Existing,
801                )
802            }
803        };
804
805        info!(
806            target: LOG_GATEWAY,
807            version = %fedimint_build_code_version_env!(),
808            "Starting gatewayd",
809        );
810
811        Gateway::new(
812            opts.mode,
813            gateway_parameters,
814            gateway_db,
815            client_builder,
816            gateway_state,
817            chain_source,
818            mnemonic_source,
819        )
820        .await
821    }
822
823    /// Helper function for creating a gateway from either
824    /// `new_with_default_modules` or `Gateway::builder`.
825    async fn new(
826        lightning_mode: LightningMode,
827        gateway_parameters: GatewayParameters,
828        gateway_db: Database,
829        client_builder: GatewayClientBuilder,
830        gateway_state: GatewayState,
831        chain_source: ChainSource,
832        mnemonic_source: MnemonicSource,
833    ) -> anyhow::Result<Gateway> {
834        let num_route_hints = gateway_parameters.num_route_hints;
835        let network = gateway_parameters.network;
836
837        let task_group = TaskGroup::new();
838        task_group.install_kill_handler();
839
840        let mut registrations = BTreeMap::new();
841        if let Some(http_url) = gateway_parameters.versioned_api {
842            registrations.insert(
843                RegisteredProtocol::Http,
844                Registration::new(&gateway_db, http_url, RegisteredProtocol::Http).await,
845            );
846        }
847
848        let iroh_sk = Self::load_or_create_iroh_key(&gateway_db).await;
849        if gateway_parameters.iroh_listen.is_some() {
850            let endpoint_url = SafeUrl::parse(&format!("iroh://{}", iroh_sk.public()))?;
851            registrations.insert(
852                RegisteredProtocol::Iroh,
853                Registration::new(&gateway_db, endpoint_url, RegisteredProtocol::Iroh).await,
854            );
855        }
856
857        Ok(Self {
858            federation_manager: Arc::new(RwLock::new(FederationManager::new())),
859            lightning_mode,
860            state: Arc::new(RwLock::new(gateway_state)),
861            client_builder,
862            gateway_db: gateway_db.clone(),
863            listen: gateway_parameters.listen,
864            metrics_listen: gateway_parameters.metrics_listen,
865            task_group,
866            bcrypt_password_hash: gateway_parameters.bcrypt_password_hash.to_string(),
867            bcrypt_liquidity_manager_password_hash: gateway_parameters
868                .bcrypt_liquidity_manager_password_hash
869                .map(|h| h.to_string()),
870            num_route_hints,
871            network,
872            chain_source,
873            default_routing_fees: gateway_parameters.default_routing_fees,
874            default_transaction_fees: gateway_parameters.default_transaction_fees,
875            iroh_sk,
876            iroh_dns: gateway_parameters.iroh_dns,
877            iroh_relays: gateway_parameters.iroh_relays,
878            iroh_listen: gateway_parameters.iroh_listen,
879            registrations,
880            registration_health: RegistrationHealthTracker::default(),
881            invoice_rate_limiter: Arc::new(TokenBucketRateLimiter::new(
882                gateway_parameters.invoice_rate_limit_burst,
883                gateway_parameters.invoice_rate_limit_per_second,
884            )),
885            lnv2_hold_invoice_lock_pool: Arc::new(lockable::LockPool::new()),
886            payment_policy_lock: Arc::new(RwLock::new(())),
887            mnemonic_source,
888        })
889    }
890
891    async fn load_or_create_gateway_keypair(
892        gateway_db: &Database,
893        protocol: RegisteredProtocol,
894    ) -> secp256k1::Keypair {
895        let mut dbtx = gateway_db.begin_transaction().await;
896        let keypair = dbtx.load_or_create_gateway_keypair(protocol).await;
897        dbtx.commit_tx().await;
898        keypair
899    }
900
901    /// Returns `iroh::SecretKey` and saves it to the database if it does not
902    /// exist
903    async fn load_or_create_iroh_key(gateway_db: &Database) -> iroh::SecretKey {
904        let mut dbtx = gateway_db.begin_transaction().await;
905        let iroh_sk = dbtx.load_or_create_iroh_key().await;
906        dbtx.commit_tx().await;
907        iroh_sk
908    }
909
910    pub async fn http_gateway_id(&self) -> PublicKey {
911        Self::load_or_create_gateway_keypair(&self.gateway_db, RegisteredProtocol::Http)
912            .await
913            .public_key()
914    }
915
916    async fn get_state(&self) -> GatewayState {
917        self.state.read().await.clone()
918    }
919
920    /// Reads and serializes structures from the Gateway's database for the
921    /// purpose for serializing to JSON for inspection.
922    pub async fn dump_database(
923        dbtx: &mut DatabaseTransaction<'_>,
924        prefix_names: Vec<String>,
925    ) -> BTreeMap<String, Box<dyn erased_serde::Serialize + Send>> {
926        dbtx.dump_database(prefix_names).await
927    }
928
929    /// Main entrypoint into the gateway that starts the client registration
930    /// timer, loads the federation clients from the persisted config,
931    /// begins listening for intercepted payments, and starts the webserver
932    /// to service requests.
933    pub async fn run(
934        self,
935        runtime: Arc<tokio::runtime::Runtime>,
936        mnemonic_receiver: tokio::sync::broadcast::Receiver<MnemonicSource>,
937    ) -> anyhow::Result<TaskShutdownToken> {
938        install_crypto_provider().await;
939        self.register_clients_timer();
940        self.load_clients().await?;
941        self.start_gateway(runtime, mnemonic_receiver.resubscribe());
942        self.spawn_backup_task();
943        self.spawn_prune_registered_contracts_task();
944        // start metrics server
945        fedimint_metrics::spawn_api_server(self.metrics_listen, self.task_group.clone()).await?;
946        // start webserver last to avoid handling requests before fully initialized
947        let handle = self.task_group.make_handle();
948        run_webserver(Arc::new(self), mnemonic_receiver.resubscribe()).await?;
949        let shutdown_receiver = handle.make_shutdown_rx();
950        Ok(shutdown_receiver)
951    }
952
953    /// Spawns a background task that checks every `BACKUP_UPDATE_INTERVAL` to
954    /// see if any federations need to be backed up.
955    fn spawn_backup_task(&self) {
956        let self_copy = self.clone();
957        self.task_group
958            .spawn_cancellable_silent("backup ecash", async move {
959                const BACKUP_UPDATE_INTERVAL: Duration = Duration::from_hours(1);
960                let mut interval = tokio::time::interval(BACKUP_UPDATE_INTERVAL);
961                interval.tick().await;
962                loop {
963                    {
964                        let mut dbtx = self_copy.gateway_db.begin_transaction().await;
965                        self_copy.backup_all_federations(&mut dbtx).await;
966                        dbtx.commit_tx().await;
967                        interval.tick().await;
968                    }
969                }
970            });
971    }
972
973    /// Spawns a background task that periodically deletes registered incoming
974    /// contract records whose invoice has long expired, so unpaid invoice
975    /// registrations cannot grow the database without bound.
976    fn spawn_prune_registered_contracts_task(&self) {
977        let self_copy = self.clone();
978        self.task_group.spawn_cancellable_silent(
979            "prune registered incoming contracts",
980            async move {
981                const PRUNE_INTERVAL: Duration = Duration::from_hours(1);
982                // Records are kept for a day past invoice expiry so payments
983                // settled shortly before expiry can still complete and be
984                // verified via the preimage verification endpoint.
985                const RETENTION_AFTER_EXPIRY: Duration = Duration::from_hours(24);
986
987                let mut interval = tokio::time::interval(PRUNE_INTERVAL);
988                loop {
989                    interval.tick().await;
990
991                    let cutoff_secs = duration_since_epoch()
992                        .saturating_sub(RETENTION_AFTER_EXPIRY)
993                        .as_secs();
994
995                    let mut dbtx = self_copy.gateway_db.begin_transaction().await;
996                    let num_pruned = dbtx.prune_registered_incoming_contracts(cutoff_secs).await;
997                    match dbtx.commit_tx_result().await {
998                        Ok(()) => {
999                            if 0 < num_pruned {
1000                                info!(
1001                                    target: LOG_GATEWAY,
1002                                    num_pruned,
1003                                    "Pruned expired incoming contract records"
1004                                );
1005                            }
1006                        }
1007                        Err(err) => {
1008                            warn!(
1009                                target: LOG_GATEWAY,
1010                                err = %err.fmt_compact(),
1011                                "Failed to prune expired incoming contract records"
1012                            );
1013                        }
1014                    }
1015                }
1016            },
1017        );
1018    }
1019
1020    /// Loops through all federations and checks their last save backup time. If
1021    /// the last saved backup time is past the threshold time, backup the
1022    /// federation.
1023    pub async fn backup_all_federations(&self, dbtx: &mut DatabaseTransaction<'_, Committable>) {
1024        /// How long the federation manager should wait to backup the ecash for
1025        /// each federation
1026        const BACKUP_THRESHOLD_DURATION: Duration = Duration::from_hours(24);
1027
1028        let now = fedimint_core::time::now();
1029        let threshold = now
1030            .checked_sub(BACKUP_THRESHOLD_DURATION)
1031            .expect("Cannot be negative");
1032        for (id, last_backup) in dbtx.load_backup_records().await {
1033            match last_backup {
1034                Some(backup_time) if backup_time < threshold => {
1035                    let fed_manager = self.federation_manager.read().await;
1036                    fed_manager.backup_federation(&id, dbtx, now).await;
1037                }
1038                None => {
1039                    let fed_manager = self.federation_manager.read().await;
1040                    fed_manager.backup_federation(&id, dbtx, now).await;
1041                }
1042                _ => {}
1043            }
1044        }
1045    }
1046
1047    /// Begins the task for listening for intercepted payments from the
1048    /// lightning node.
1049    fn start_gateway(
1050        &self,
1051        runtime: Arc<tokio::runtime::Runtime>,
1052        mut mnemonic_receiver: tokio::sync::broadcast::Receiver<MnemonicSource>,
1053    ) {
1054        const PAYMENT_STREAM_RETRY_SECONDS: u64 = 60;
1055
1056        let self_copy = self.clone();
1057        let tg = self.task_group.clone();
1058        self.task_group.spawn(
1059            "Subscribe to intercepted lightning payments in stream",
1060            |handle| async move {
1061                let mut mnemonic_source = self_copy.mnemonic_source;
1062                // Repeatedly attempt to establish a connection to the lightning node and create a payment stream, re-trying if the connection is broken.
1063                loop {
1064                    if handle.is_shutting_down() {
1065                        info!(target: LOG_GATEWAY, "Gateway lightning payment stream handler loop is shutting down");
1066                        break;
1067                    }
1068
1069                    if let GatewayState::NotConfigured{ .. } = self_copy.get_state().await {
1070                        info!(
1071                            target: LOG_GATEWAY,
1072                            "Waiting for the mnemonic to be set before starting lightning receive loop."
1073                        );
1074                        info!(
1075                            target: LOG_GATEWAY,
1076                            "You might need to provide it from the UI or refer to documentation w.r.t how to initialize it."
1077                        );
1078
1079                        if let Ok(source) = mnemonic_receiver.recv().await {
1080                            mnemonic_source = source;
1081                        }
1082                        info!(
1083                            target: LOG_GATEWAY,
1084                            ?mnemonic_source,
1085                            "Received mnemonic, attempting to start lightning receive loop"
1086                        );
1087                    }
1088
1089                    let payment_stream_task_group = tg.make_subgroup();
1090                    let lnrpc_route = self_copy.create_lightning_client(runtime.clone(), mnemonic_source).await;
1091
1092                    debug!(target: LOG_GATEWAY, "Establishing lightning payment stream...");
1093                    let (stream, ln_client) = match lnrpc_route.route_htlcs(&payment_stream_task_group).await
1094                    {
1095                        Ok((stream, ln_client)) => (stream, ln_client),
1096                        Err(err) => {
1097                            warn!(target: LOG_GATEWAY, err = %err.fmt_compact(), "Failed to open lightning payment stream");
1098                            // `route_htlcs` may have already spawned tasks into the
1099                            // subgroup before failing (e.g. the LNv1 interceptor is
1100                            // spawned before LNv2 setup, which can fail). Tear the
1101                            // subgroup down so no stale task keeps owning the LND HTLC
1102                            // stream, which would prevent the retry from taking over and
1103                            // could cause it to cancel real HTLCs after `gateway_receiver`
1104                            // is dropped.
1105                            if let Err(err) = payment_stream_task_group.shutdown_join_all(None).await {
1106                                crit!(target: LOG_GATEWAY, err = %err.fmt_compact(), "Lightning payment stream task group shutdown");
1107                            }
1108                            sleep(Duration::from_secs(PAYMENT_STREAM_RETRY_SECONDS)).await;
1109                            continue
1110                        }
1111                    };
1112
1113                    // Successful calls to `route_htlcs` establish a connection
1114                    self_copy.set_gateway_state(GatewayState::Connected).await;
1115                    info!(target: LOG_GATEWAY, "Established lightning payment stream");
1116
1117                    let route_payments_response =
1118                        self_copy.route_lightning_payments(&handle, stream, ln_client).await;
1119
1120                    self_copy.set_gateway_state(GatewayState::Disconnected).await;
1121                    if let Err(err) = payment_stream_task_group.shutdown_join_all(None).await {
1122                        crit!(target: LOG_GATEWAY, err = %err.fmt_compact(), "Lightning payment stream task group shutdown");
1123                    }
1124
1125                    self_copy.unannounce_from_all_federations().await;
1126
1127                    match route_payments_response {
1128                        ReceivePaymentStreamAction::RetryAfterDelay => {
1129                            warn!(target: LOG_GATEWAY, retry_interval = %PAYMENT_STREAM_RETRY_SECONDS, "Disconnected from lightning node");
1130                            sleep(Duration::from_secs(PAYMENT_STREAM_RETRY_SECONDS)).await;
1131                        }
1132                        ReceivePaymentStreamAction::NoRetry => break,
1133                    }
1134                }
1135            },
1136        );
1137    }
1138
1139    /// Handles a stream of incoming payments from the lightning node after
1140    /// ensuring the gateway is properly configured. Awaits until the stream
1141    /// is closed, then returns with the appropriate action to take.
1142    async fn route_lightning_payments<'a>(
1143        &'a self,
1144        handle: &TaskHandle,
1145        mut stream: RouteHtlcStream<'a>,
1146        ln_client: Arc<dyn ILnRpcClient>,
1147    ) -> ReceivePaymentStreamAction {
1148        let LightningInfo::Connected {
1149            public_key: lightning_public_key,
1150            alias: lightning_alias,
1151            network: lightning_network,
1152            block_height: _,
1153            synced_to_chain,
1154        } = ln_client.parsed_node_info().await
1155        else {
1156            warn!(target: LOG_GATEWAY, "Failed to retrieve Lightning info");
1157            return ReceivePaymentStreamAction::RetryAfterDelay;
1158        };
1159
1160        assert!(
1161            self.network == lightning_network,
1162            "Lightning node network does not match Gateway's network. LN: {lightning_network} Gateway: {}",
1163            self.network
1164        );
1165
1166        if synced_to_chain || is_env_var_set(FM_GATEWAY_SKIP_WAIT_FOR_SYNC_ENV) {
1167            info!(target: LOG_GATEWAY, "Gateway is already synced to chain");
1168        } else {
1169            self.set_gateway_state(GatewayState::Syncing).await;
1170            info!(target: LOG_GATEWAY, "Waiting for chain sync");
1171            if let Err(err) = ln_client.wait_for_chain_sync().await {
1172                warn!(target: LOG_GATEWAY, err = %err.fmt_compact(), "Failed to wait for chain sync");
1173                return ReceivePaymentStreamAction::RetryAfterDelay;
1174            }
1175        }
1176
1177        let lightning_context = LightningContext {
1178            lnrpc: LnRpcTracked::new(ln_client, "gateway"),
1179            lightning_public_key,
1180            lightning_alias,
1181            lightning_network,
1182        };
1183        if let GatewayState::ShuttingDown { .. } = self
1184            .set_gateway_state(GatewayState::Running { lightning_context })
1185            .await
1186        {
1187            info!(
1188                target: LOG_GATEWAY,
1189                "Reconnected to the lightning node while shutting down, not accepting payments"
1190            );
1191        } else {
1192            info!(target: LOG_GATEWAY, "Gateway is running");
1193        }
1194
1195        if matches!(self.lightning_mode, LightningMode::Lnd { .. }) {
1196            // Re-register the gateway with all federations after connecting to the
1197            // lightning node
1198            let mut dbtx = self.gateway_db.begin_transaction_nc().await;
1199            let all_federations_configs =
1200                dbtx.load_federation_configs().await.into_iter().collect();
1201            self.register_federations(&all_federations_configs, &self.task_group)
1202                .await;
1203        }
1204
1205        // Runs until the connection to the lightning node breaks or we receive the
1206        // shutdown signal.
1207        let htlc_task_group = self.task_group.make_subgroup();
1208        if handle
1209            .cancel_on_shutdown(async move {
1210                loop {
1211                    let payment_request_or = tokio::select! {
1212                        payment_request_or = stream.next() => {
1213                            payment_request_or
1214                        }
1215                        () = self.is_shutting_down_safely() => {
1216                            break;
1217                        }
1218                    };
1219
1220                    let Some(payment_request) = payment_request_or else {
1221                        warn!(
1222                            target: LOG_GATEWAY,
1223                            "Unexpected response from incoming lightning payment stream. Shutting down payment processor"
1224                        );
1225                        break;
1226                    };
1227
1228                    let state_guard = self.state.read().await;
1229                    if let GatewayState::Running { ref lightning_context } = *state_guard {
1230                        // Spawn a subtask to handle each payment in parallel
1231                        let gateway = self.clone();
1232                        let lightning_context = lightning_context.clone();
1233                        htlc_task_group.spawn_cancellable_silent(
1234                            "handle_lightning_payment",
1235                            async move {
1236                                let start = fedimint_core::time::now();
1237                                let outcome = gateway
1238                                    .handle_lightning_payment(payment_request, &lightning_context)
1239                                    .await;
1240                                metrics::HTLC_HANDLING_DURATION_SECONDS
1241                                    .with_label_values(&[outcome])
1242                                    .observe(
1243                                        fedimint_core::time::now()
1244                                            .duration_since(start)
1245                                            .unwrap_or_default()
1246                                            .as_secs_f64(),
1247                                    );
1248                            },
1249                        );
1250                    } else {
1251                        warn!(
1252                            target: LOG_GATEWAY,
1253                            state = %state_guard,
1254                            "Gateway isn't in a running state, cannot handle incoming payments."
1255                        );
1256                        break;
1257                    }
1258                }
1259            })
1260            .await
1261            .is_ok()
1262        {
1263            warn!(target: LOG_GATEWAY, "Lightning payment stream connection broken. Gateway is disconnected");
1264            ReceivePaymentStreamAction::RetryAfterDelay
1265        } else {
1266            info!(target: LOG_GATEWAY, "Received shutdown signal");
1267            ReceivePaymentStreamAction::NoRetry
1268        }
1269    }
1270
1271    /// Polls the Gateway's state waiting for it to shutdown so the thread
1272    /// processing payment requests can exit.
1273    async fn is_shutting_down_safely(&self) {
1274        loop {
1275            if let GatewayState::ShuttingDown { .. } = self.get_state().await {
1276                return;
1277            }
1278
1279            fedimint_core::task::sleep(Duration::from_secs(1)).await;
1280        }
1281    }
1282
1283    /// Handles an intercepted lightning payment. If the payment is part of an
1284    /// incoming payment to a federation, spawns a state machine and hands the
1285    /// payment off to it. If the payment's last-hop short channel id maps to
1286    /// a known federation but no LNv1 or LNv2 offer matched, cancels (fails
1287    /// back) the HTLC so the sender can retry rather than treating the
1288    /// gateway as a dead route. Otherwise (real-channel forwards), resumes
1289    /// the HTLC so LND can route it as a normal forward. A duplicate delivery
1290    /// of a HOLD invoice that is still being handled is dropped.
1291    ///
1292    /// Returns the outcome label for metrics tracking.
1293    pub async fn handle_lightning_payment(
1294        &self,
1295        payment_request: InterceptPaymentRequest,
1296        lightning_context: &LightningContext,
1297    ) -> &'static str {
1298        info!(
1299            target: LOG_GATEWAY,
1300            lightning_payment = %PrettyInterceptPaymentRequest(&payment_request),
1301            "Intercepting lightning payment",
1302        );
1303
1304        // A payment without an incoming circuit is held by a HOLD invoice, which
1305        // the node can deliver more than once. Only one delivery is handled at a
1306        // time, from here through settling or cancelling the invoice. A
1307        // duplicate is dropped rather than made to wait: whatever the first
1308        // delivery decides resolves the whole invoice, and a duplicate handled
1309        // afterwards could fund an invoice the first has just cancelled. LND,
1310        // for one, replays every accepted invoice when the gateway resubscribes
1311        // after a reconnect. Forwards are not deduplicated: each has
1312        // its own circuit, and a replay after a reconnect may be the only
1313        // delivery still able to resolve it.
1314        let _hold_invoice_guard = if payment_request.incoming_circuit().is_none() {
1315            let Some(guard) = self
1316                .lnv2_hold_invoice_lock_pool
1317                .try_lock(payment_request.payment_hash)
1318            else {
1319                info!(
1320                    target: LOG_GATEWAY,
1321                    payment_hash = %payment_request.payment_hash,
1322                    "Dropping duplicate delivery of a HOLD invoice that is already being handled",
1323                );
1324                return "duplicate";
1325            };
1326            Some(guard)
1327        } else {
1328            None
1329        };
1330
1331        let lnv2_start = fedimint_core::time::now();
1332        let lnv2_result = self
1333            .try_handle_lightning_payment_lnv2(&payment_request, lightning_context)
1334            .await;
1335        let lnv2_outcome = if lnv2_result.is_ok() {
1336            "success"
1337        } else {
1338            "error"
1339        };
1340        metrics::HTLC_LNV2_ATTEMPT_DURATION_SECONDS
1341            .with_label_values(&[lnv2_outcome])
1342            .observe(
1343                fedimint_core::time::now()
1344                    .duration_since(lnv2_start)
1345                    .unwrap_or_default()
1346                    .as_secs_f64(),
1347            );
1348        if lnv2_result.is_ok() {
1349            return "lnv2";
1350        }
1351
1352        // A payment held for a registered LNv2 contract is left to that
1353        // contract's receive, or to the Lightning node's expiry, even if its
1354        // amount does not match: cancelling it would also fail back HTLCs the
1355        // receive may already be settling.
1356        if payment_request.incoming_circuit().is_none()
1357            && let Err(PublicGatewayError::LNv2(err @ LNv2Error::IncomingAmountMismatch { .. })) =
1358                &lnv2_result
1359        {
1360            warn!(
1361                target: LOG_GATEWAY,
1362                payment_hash = %payment_request.payment_hash,
1363                err = %err.fmt_compact(),
1364                "Ignoring payment for a registered LNv2 contract whose amount does not match",
1365            );
1366            return "ignore";
1367        }
1368
1369        let lnv1_start = fedimint_core::time::now();
1370        let lnv1_result = self
1371            .try_handle_lightning_payment_ln_legacy(&payment_request, lightning_context)
1372            .await;
1373        let lnv1_outcome = if lnv1_result.is_ok() {
1374            "success"
1375        } else {
1376            "error"
1377        };
1378        metrics::HTLC_LNV1_ATTEMPT_DURATION_SECONDS
1379            .with_label_values(&[lnv1_outcome])
1380            .observe(
1381                fedimint_core::time::now()
1382                    .duration_since(lnv1_start)
1383                    .unwrap_or_default()
1384                    .as_secs_f64(),
1385            );
1386        if lnv1_result.is_ok() {
1387            return "lnv1";
1388        }
1389
1390        // Neither LNv1 nor LNv2 matched. If the last-hop scid is one of our
1391        // federation virtual scids, cancel so the sender gets a non-permanent
1392        // failure (avoiding `UNKNOWN_NEXT_PEER` blacklisting). If the scid is
1393        // for a real channel, resume so LND forwards normally.
1394        let is_federation_scid = match payment_request.short_channel_id {
1395            Some(scid) => self
1396                .federation_manager
1397                .read()
1398                .await
1399                .get_client_for_index(scid)
1400                .is_some(),
1401            None => false,
1402        };
1403
1404        if is_federation_scid {
1405            // The HTLC targeted a federation we serve but we couldn't claim
1406            // it (no LNv1 offer / no LNv2 contract / receives turned off /
1407            // underfunded gateway / federation timeout / etc.). Surface the
1408            // underlying error variants so operators can diagnose the cause;
1409            // otherwise both `Err` values are dropped on the floor and the
1410            // only visible signal is the metric label `"error"`.
1411            warn!(
1412                target: LOG_GATEWAY,
1413                payment_hash = %payment_request.payment_hash,
1414                short_channel_id = ?payment_request.short_channel_id,
1415                amount_msat = payment_request.amount_msat,
1416                incoming_chan_id = payment_request.incoming_chan_id,
1417                htlc_id = payment_request.htlc_id,
1418                lnv2_err = ?lnv2_result.as_ref().err(),
1419                lnv1_err = ?lnv1_result.as_ref().err(),
1420                "Lightning payment for a served federation could not be accepted: cancelling HTLC",
1421            );
1422            Self::cancel_unmatched_lightning_payment(payment_request, lightning_context).await;
1423            "cancel"
1424        } else {
1425            // Normal route-through traffic: the gateway's LND interceptor
1426            // sees every HTLC, but only federation-scid HTLCs are ours to
1427            // handle. Resume so LND forwards the rest as a regular routing
1428            // node — no warning needed since this is the expected path.
1429            Self::forward_lightning_payment(payment_request, lightning_context).await;
1430            "forward"
1431        }
1432    }
1433
1434    /// Tries to handle a lightning payment using the LNv2 protocol.
1435    /// Returns `Ok` if the payment was handled, `Err` otherwise.
1436    async fn try_handle_lightning_payment_lnv2(
1437        &self,
1438        htlc_request: &InterceptPaymentRequest,
1439        lightning_context: &LightningContext,
1440    ) -> Result<()> {
1441        // If `payment_hash` has been registered as a LNv2 payment, we try to complete
1442        // the payment by getting the preimage from the federation
1443        // using the LNv2 protocol. If the `payment_hash` is not registered,
1444        // this payment is either a legacy Lightning payment or the end destination is
1445        // not a Fedimint.
1446        // Match and fund against the amount actually locked in the incoming
1447        // HTLC, not the sender-controlled onion forward amount, so a forged
1448        // `amt_to_forward` cannot satisfy the registered contract's amount
1449        // check while only a token amount is really locked.
1450        let (contract, client) = self
1451            .get_registered_incoming_contract_and_client_v2(
1452                PaymentImage::Hash(htlc_request.payment_hash),
1453                htlc_request.incoming_amount_msat,
1454            )
1455            .await?;
1456
1457        // An intercepted forward, or an unknown current height, leaves no time
1458        // to fund a fresh contract; see `lnv2_blocks_to_claim_deadline`.
1459        let current_block_height = lightning_context
1460            .lnrpc
1461            .info()
1462            .await
1463            .ok()
1464            .map(|info| info.block_height);
1465        let blocks_to_claim_deadline =
1466            htlc_request.lnv2_blocks_to_claim_deadline(current_block_height);
1467
1468        if let Err(err) = client
1469            .get_first_module::<GatewayClientModuleV2>()
1470            .expect("Must have client module")
1471            .relay_incoming_htlc(
1472                htlc_request.payment_hash,
1473                htlc_request.incoming_chan_id,
1474                htlc_request.htlc_id,
1475                contract,
1476                htlc_request.incoming_amount_msat,
1477                blocks_to_claim_deadline,
1478            )
1479            .await
1480        {
1481            warn!(
1482                target: LOG_GATEWAY,
1483                err = %err.fmt_compact(),
1484                "Error relaying incoming lightning payment"
1485            );
1486
1487            let outcome = InterceptPaymentResponse {
1488                action: PaymentAction::Cancel,
1489                payment_hash: htlc_request.payment_hash,
1490                incoming_chan_id: htlc_request.incoming_chan_id,
1491                htlc_id: htlc_request.htlc_id,
1492            };
1493
1494            if let Err(err) = lightning_context.lnrpc.complete_htlc(outcome).await {
1495                warn!(target: LOG_GATEWAY, err = %err.fmt_compact(), "Error sending HTLC response to lightning node");
1496            }
1497        }
1498
1499        Ok(())
1500    }
1501
1502    /// Tries to handle a lightning payment using the legacy lightning protocol.
1503    /// Returns `Ok` if the payment was handled, `Err` otherwise.
1504    async fn try_handle_lightning_payment_ln_legacy(
1505        &self,
1506        htlc_request: &InterceptPaymentRequest,
1507        lightning_context: &LightningContext,
1508    ) -> Result<()> {
1509        // Check if the payment corresponds to a federation supporting legacy Lightning.
1510        let Some(federation_index) = htlc_request.short_channel_id else {
1511            return Err(PublicGatewayError::LNv1(LNv1Error::IncomingPayment(
1512                "Incoming payment has not last hop short channel id".to_string(),
1513            )));
1514        };
1515
1516        let Some(client) = self
1517            .federation_manager
1518            .read()
1519            .await
1520            .get_client_for_index(federation_index)
1521        else {
1522            return Err(PublicGatewayError::LNv1(LNv1Error::IncomingPayment("Incoming payment has a last hop short channel id that does not map to a known federation".to_string())));
1523        };
1524
1525        // Both LND's `incoming_expiry` and LDK's `claim_deadline` are absolute
1526        // Bitcoin heights. LDK does not currently produce LNv1 forwards (it has
1527        // no federation short-channel id), but using the backend's own best
1528        // height keeps the unit and chain view consistent for every backend.
1529        client
1530            .borrow()
1531            .with(|client| async {
1532                let htlc = Htlc::from(htlc_request.clone());
1533                let lnv1 = client
1534                    .get_first_module::<GatewayClientModule>()
1535                    .map_err(|_| {
1536                        PublicGatewayError::LNv1(LNv1Error::IncomingPayment(
1537                            "Federation does not have LNv1 module".to_string(),
1538                        ))
1539                    })?;
1540                match lnv1
1541                    .gateway_handle_intercepted_htlc(htlc, async {
1542                        Ok(lightning_context.lnrpc.info().await?.block_height)
1543                    })
1544                    .await
1545                {
1546                    Ok(_) => Ok(()),
1547                    Err(e) => Err(PublicGatewayError::LNv1(LNv1Error::IncomingPayment(
1548                        format!("Error intercepting lightning payment {}", e.fmt_compact()),
1549                    ))),
1550                }
1551            })
1552            .await
1553    }
1554
1555    /// Cancels (fails back) a lightning payment whose last-hop scid maps to a
1556    /// known federation but matched no LNv1 or LNv2 offer.
1557    ///
1558    /// Returning `PaymentAction::Forward` here would tell LND to resume the
1559    /// HTLC as a normal forward, but the last-hop short channel id is a
1560    /// virtual scid (no real channel exists), so LND would fail it back with
1561    /// the permanent error `UNKNOWN_NEXT_PEER`. Senders' mission control
1562    /// treats that as a permanent blacklist signal against the gateway,
1563    /// breaking future payments across all federations.
1564    ///
1565    /// `PaymentAction::Cancel` maps to `ResolveHoldForwardAction::Fail`, which
1566    /// fails the HTLC back with a non-permanent reason so the sender can
1567    /// retry instead of blacklisting the gateway.
1568    async fn cancel_unmatched_lightning_payment(
1569        htlc_request: InterceptPaymentRequest,
1570        lightning_context: &LightningContext,
1571    ) {
1572        let outcome = InterceptPaymentResponse {
1573            action: PaymentAction::Cancel,
1574            payment_hash: htlc_request.payment_hash,
1575            incoming_chan_id: htlc_request.incoming_chan_id,
1576            htlc_id: htlc_request.htlc_id,
1577        };
1578
1579        if let Err(err) = lightning_context.lnrpc.complete_htlc(outcome).await {
1580            warn!(target: LOG_GATEWAY, err = %err.fmt_compact(), "Error sending lightning payment response to lightning node");
1581        }
1582    }
1583
1584    /// Forwards a lightning payment to the next hop like a normal lightning
1585    /// node. Used when the intercepted HTLC is not destined for any federation
1586    /// this gateway serves, so LND should route it normally over a real
1587    /// channel.
1588    async fn forward_lightning_payment(
1589        htlc_request: InterceptPaymentRequest,
1590        lightning_context: &LightningContext,
1591    ) {
1592        let outcome = InterceptPaymentResponse {
1593            action: PaymentAction::Forward,
1594            payment_hash: htlc_request.payment_hash,
1595            incoming_chan_id: htlc_request.incoming_chan_id,
1596            htlc_id: htlc_request.htlc_id,
1597        };
1598
1599        if let Err(err) = lightning_context.lnrpc.complete_htlc(outcome).await {
1600            warn!(target: LOG_GATEWAY, err = %err.fmt_compact(), "Error sending lightning payment response to lightning node");
1601        }
1602    }
1603
1604    /// Helper function for atomically changing the Gateway's internal state.
1605    ///
1606    /// Shutting down is one-way. The lightning connection loop keeps running
1607    /// while `handle_shutdown_msg` drains the payments that are still in
1608    /// flight, and a reconnect in that window must not move the gateway back
1609    /// into a state that accepts new payments. A reconnect may still hand over
1610    /// a fresh `LightningContext`, which the drain needs to complete the
1611    /// payments it is waiting for.
1612    /// Returns the state that is in effect afterwards, which is not the
1613    /// requested one if the gateway is shutting down.
1614    async fn set_gateway_state(&self, state: GatewayState) -> GatewayState {
1615        let mut lock = self.state.write().await;
1616
1617        if let GatewayState::ShuttingDown { .. } = *lock {
1618            match state {
1619                GatewayState::Running { lightning_context } => {
1620                    *lock = GatewayState::ShuttingDown { lightning_context };
1621                }
1622                ignored => {
1623                    info!(
1624                        target: LOG_GATEWAY,
1625                        ignored_state = %ignored,
1626                        "Gateway is shutting down, ignoring state change"
1627                    );
1628                }
1629            }
1630        } else {
1631            *lock = state;
1632        }
1633
1634        lock.clone()
1635    }
1636
1637    /// Drives the gateway's state directly, bypassing the lightning connection
1638    /// loop in [`Self::start_gateway`] that owns every real transition.
1639    ///
1640    /// Tests need to observe behaviour in states the builder cannot start them
1641    /// in -- notably "connected later than the federation clients" -- and have
1642    /// no lightning node to get there with. Nothing in production should call
1643    /// this.
1644    #[doc(hidden)]
1645    pub async fn set_gateway_state_out_of_band(&self, state: GatewayState) {
1646        self.set_gateway_state(state).await;
1647    }
1648
1649    /// If the Gateway is connected to the Lightning node, returns the
1650    /// `ClientConfig` for each federation that the Gateway is connected to.
1651    pub async fn handle_get_federation_config(
1652        &self,
1653        federation_id_or: Option<FederationId>,
1654    ) -> AdminResult<GatewayFedConfig> {
1655        if !matches!(self.get_state().await, GatewayState::Running { .. }) {
1656            return Ok(GatewayFedConfig {
1657                federations: BTreeMap::new(),
1658            });
1659        }
1660
1661        let federations = if let Some(federation_id) = federation_id_or {
1662            let mut federations = BTreeMap::new();
1663            federations.insert(
1664                federation_id,
1665                self.federation_manager
1666                    .read()
1667                    .await
1668                    .get_federation_config(federation_id)
1669                    .await?,
1670            );
1671            federations
1672        } else {
1673            self.federation_manager
1674                .read()
1675                .await
1676                .get_all_federation_configs()
1677                .await
1678        };
1679
1680        Ok(GatewayFedConfig { federations })
1681    }
1682
1683    /// Returns a Bitcoin deposit on-chain address for pegging in Bitcoin for a
1684    /// specific connected federation.
1685    pub async fn handle_address_msg(&self, payload: DepositAddressPayload) -> AdminResult<Address> {
1686        let client = self.select_client(payload.federation_id).await?;
1687
1688        if let Ok(wallet_module) = client.value().get_first_module::<WalletClientModule>() {
1689            let address = wallet_module
1690                .allocate_deposit_address_expert_only(())
1691                .await
1692                .map_err(|e| AdminGatewayError::Unexpected(e.into()))?
1693                .address;
1694            Ok(address)
1695        } else if let Ok(wallet_module) = client
1696            .value()
1697            .get_first_module::<fedimint_walletv2_client::WalletClientModule>()
1698        {
1699            wallet_module
1700                .receive(Account::Primary)
1701                .await
1702                .map_err(|e| AdminGatewayError::Unexpected(e.into()))
1703        } else {
1704            Err(AdminGatewayError::Unexpected(anyhow!(
1705                "No wallet module found"
1706            )))
1707        }
1708    }
1709
1710    /// Requests the gateway to pay an outgoing LN invoice on behalf of a
1711    /// Fedimint client. Returns the payment hash's preimage on success.
1712    async fn handle_pay_invoice_msg(
1713        &self,
1714        payload: fedimint_ln_client::pay::PayInvoicePayload,
1715    ) -> Result<Preimage> {
1716        let GatewayState::Running { .. } = self.get_state().await else {
1717            return Err(PublicGatewayError::Lightning(
1718                LightningRpcError::FailedToConnect,
1719            ));
1720        };
1721
1722        debug!(target: LOG_GATEWAY, "Handling pay invoice message");
1723        let client = self.select_client(payload.federation_id).await?;
1724        let contract_id = payload.contract_id;
1725        let gateway_module = &client
1726            .value()
1727            .get_first_module::<GatewayClientModule>()
1728            .map_err(|err| LNv1Error::OutgoingPayment(err.into()))
1729            .map_err(PublicGatewayError::LNv1)?;
1730        let operation_id = gateway_module
1731            .gateway_pay_bolt11_invoice(payload)
1732            .await
1733            .map_err(|err| LNv1Error::OutgoingPayment(err.into()))
1734            .map_err(PublicGatewayError::LNv1)?;
1735        let mut updates = gateway_module
1736            .gateway_subscribe_ln_pay(operation_id)
1737            .await
1738            .map_err(|err| LNv1Error::OutgoingPayment(err.into()))
1739            .map_err(PublicGatewayError::LNv1)?
1740            .into_stream();
1741        while let Some(update) = updates.next().await {
1742            match update {
1743                GatewayExtPayStates::Success { preimage, .. } => {
1744                    debug!(target: LOG_GATEWAY, contract_id = %contract_id, "Successfully paid invoice");
1745                    return Ok(preimage);
1746                }
1747                GatewayExtPayStates::Fail {
1748                    error,
1749                    error_message,
1750                } => {
1751                    return Err(PublicGatewayError::LNv1(LNv1Error::OutgoingContract {
1752                        error: Box::new(error),
1753                        message: format!(
1754                            "{error_message} while paying invoice with contract id {contract_id}"
1755                        ),
1756                    }));
1757                }
1758                GatewayExtPayStates::Canceled { error } => {
1759                    return Err(PublicGatewayError::LNv1(LNv1Error::OutgoingContract {
1760                        error: Box::new(error.clone()),
1761                        message: format!(
1762                            "Cancelled with {error} while paying invoice with contract id {contract_id}"
1763                        ),
1764                    }));
1765                }
1766                GatewayExtPayStates::Created => {
1767                    debug!(target: LOG_GATEWAY, contract_id = %contract_id, "Start pay invoice state machine");
1768                }
1769                other => {
1770                    debug!(target: LOG_GATEWAY, state = ?other, contract_id = %contract_id, "Got state while paying invoice");
1771                }
1772            }
1773        }
1774
1775        Err(PublicGatewayError::LNv1(LNv1Error::OutgoingPayment(
1776            anyhow!("Ran out of state updates while paying invoice"),
1777        )))
1778    }
1779
1780    /// Handles a request for the gateway to backup a connected federation's
1781    /// ecash.
1782    pub async fn handle_backup_msg(
1783        &self,
1784        BackupPayload { federation_id }: BackupPayload,
1785    ) -> AdminResult<()> {
1786        let federation_manager = self.federation_manager.read().await;
1787        let client = federation_manager
1788            .client(&federation_id)
1789            .ok_or(AdminGatewayError::ClientCreationError(anyhow::anyhow!(
1790                format!("Gateway has not connected to {federation_id}")
1791            )))?
1792            .value();
1793        let metadata: BTreeMap<String, String> = BTreeMap::new();
1794        #[allow(deprecated)]
1795        client
1796            .backup_to_federation(fedimint_client::backup::Metadata::from_json_serialized(
1797                metadata,
1798            ))
1799            .await
1800            .map_err(anyhow::Error::from)?;
1801        Ok(())
1802    }
1803
1804    /// Trigger rechecking for deposits on an address
1805    pub async fn handle_recheck_address_msg(
1806        &self,
1807        payload: DepositAddressRecheckPayload,
1808    ) -> AdminResult<()> {
1809        let client = self.select_client(payload.federation_id).await?;
1810
1811        if let Ok(wallet_module) = client.value().get_first_module::<WalletClientModule>() {
1812            wallet_module
1813                .recheck_pegin_address_by_address(payload.address)
1814                .await
1815                .map_err(|e| AdminGatewayError::Unexpected(e.into()))?;
1816            Ok(())
1817        } else if client
1818            .value()
1819            .get_first_module::<fedimint_walletv2_client::WalletClientModule>()
1820            .is_ok()
1821        {
1822            // Walletv2 auto-claims deposits, so this is a no-op
1823            Ok(())
1824        } else {
1825            Err(AdminGatewayError::Unexpected(anyhow!(
1826                "No wallet module found"
1827            )))
1828        }
1829    }
1830
1831    /// Handles a request to receive ecash into the gateway.
1832    pub async fn handle_receive_ecash_msg(
1833        &self,
1834        payload: ReceiveEcashPayload,
1835    ) -> Result<ReceiveEcashResponse> {
1836        // Extract federation_id_prefix from either format
1837        let federation_id_prefix = base32::decode_prefixed::<fedimint_mintv2_client::ECash>(
1838            FEDIMINT_PREFIX,
1839            &payload.notes,
1840        )
1841        .ok()
1842        .and_then(|e| e.mint())
1843        .map(|id| id.to_prefix())
1844        .or_else(|| {
1845            OOBNotes::from_str(&payload.notes)
1846                .ok()
1847                .map(|n| n.federation_id_prefix())
1848        })
1849        .ok_or_else(|| PublicGatewayError::ReceiveEcashError {
1850            failure_reason: "Invalid ecash format: could not parse as ECash or OOBNotes"
1851                .to_string(),
1852        })?;
1853
1854        let client = self
1855            .federation_manager
1856            .read()
1857            .await
1858            .get_client_for_federation_id_prefix(federation_id_prefix)
1859            .ok_or(FederationNotConnected {
1860                federation_id_prefix,
1861            })?;
1862
1863        // Check which module is present and parse accordingly
1864        if let Ok(mint) = client.value().get_first_module::<MintClientModule>() {
1865            let notes = OOBNotes::from_str(&payload.notes).map_err(|e| {
1866                PublicGatewayError::ReceiveEcashError {
1867                    failure_reason: format!(
1868                        "Expected OOBNotes for MintV1 federation: {}",
1869                        e.fmt_compact()
1870                    ),
1871                }
1872            })?;
1873            let amount = notes.total_amount();
1874
1875            let operation_id = mint.reissue_external_notes(notes, ()).await.map_err(|e| {
1876                PublicGatewayError::ReceiveEcashError {
1877                    failure_reason: e.fmt_compact().to_string(),
1878                }
1879            })?;
1880
1881            let mut updates = mint
1882                .subscribe_reissue_external_notes(operation_id)
1883                .await
1884                .map_err(|e| PublicGatewayError::ReceiveEcashError {
1885                    failure_reason: format!(
1886                        "Could not subscribe to reissue operation: {}",
1887                        e.fmt_compact()
1888                    ),
1889                })?
1890                .into_stream();
1891
1892            // Only `Done` and `Failed` are terminal for this stream. Ending on
1893            // `Created` or `Issuing` means the outputs were never finalized, so
1894            // their blind signatures were never verified, and reporting the notes'
1895            // claimed amount would credit e-cash the gateway does not hold.
1896            let mut reissued = false;
1897            while let Some(update) = updates.next().await {
1898                match update {
1899                    ReissueExternalNotesState::Failed(failure_reason) => {
1900                        return Err(PublicGatewayError::ReceiveEcashError { failure_reason });
1901                    }
1902                    ReissueExternalNotesState::Done => reissued = true,
1903                    ReissueExternalNotesState::Created | ReissueExternalNotesState::Issuing => {}
1904                }
1905            }
1906
1907            if !reissued {
1908                return Err(PublicGatewayError::ReceiveEcashError {
1909                    failure_reason: "Reissue operation ended before the notes were reissued"
1910                        .to_string(),
1911                });
1912            }
1913
1914            Ok(ReceiveEcashResponse { amount })
1915        } else if let Ok(mint) = client
1916            .value()
1917            .get_primary_module_for_unit::<MintV2ClientModule>(
1918                fedimint_core::module::AmountUnit::BITCOIN,
1919            )
1920        {
1921            let ecash: fedimint_mintv2_client::ECash =
1922                base32::decode_prefixed(FEDIMINT_PREFIX, &payload.notes).map_err(|e| {
1923                    PublicGatewayError::ReceiveEcashError {
1924                        failure_reason: format!("Expected ECash for MintV2 federation: {e}"),
1925                    }
1926                })?;
1927            let amount = ecash.amount();
1928
1929            let operation_id = mint
1930                .receive(Account::Primary, ecash, serde_json::Value::Null)
1931                .await
1932                .map_err(|e| PublicGatewayError::ReceiveEcashError {
1933                    failure_reason: e.fmt_compact().to_string(),
1934                })?;
1935
1936            let final_state = mint
1937                .await_final_receive_operation_state(operation_id)
1938                .await
1939                .map_err(|e| PublicGatewayError::ReceiveEcashError {
1940                    failure_reason: e.fmt_compact().to_string(),
1941                })?;
1942            match final_state {
1943                fedimint_mintv2_client::FinalReceiveOperationState::Success => {}
1944                fedimint_mintv2_client::FinalReceiveOperationState::Rejected => {
1945                    return Err(PublicGatewayError::ReceiveEcashError {
1946                        failure_reason: "ECash receive was rejected".to_string(),
1947                    });
1948                }
1949            }
1950
1951            Ok(ReceiveEcashResponse { amount })
1952        } else {
1953            Err(PublicGatewayError::ReceiveEcashError {
1954                failure_reason: "No mint module found".to_string(),
1955            })
1956        }
1957    }
1958
1959    /// Retrieves an invoice by the payment hash if it exists, otherwise returns
1960    /// `None`.
1961    pub async fn handle_get_invoice_msg(
1962        &self,
1963        payload: GetInvoiceRequest,
1964    ) -> AdminResult<Option<GetInvoiceResponse>> {
1965        let lightning_context = self.get_lightning_context().await?;
1966        let invoice = lightning_context.lnrpc.get_invoice(payload).await?;
1967        Ok(invoice)
1968    }
1969
1970    /// Withdraws ecash from a federation and pegs-out to the Lightning node's
1971    /// onchain wallet
1972    pub async fn handle_withdraw_to_onchain_msg(
1973        &self,
1974        payload: WithdrawToOnchainPayload,
1975    ) -> AdminResult<WithdrawResponse> {
1976        let address = self.handle_get_ln_onchain_address_msg().await?;
1977        let withdraw = WithdrawPayload {
1978            address: address.into_unchecked(),
1979            federation_id: payload.federation_id,
1980            amount: payload.amount,
1981            quoted_fees: None,
1982        };
1983        self.handle_withdraw_msg(withdraw).await
1984    }
1985
1986    /// Deposits the specified amount from the gateway's onchain wallet into the
1987    /// Federation's ecash wallet
1988    pub async fn handle_pegin_from_onchain_msg(
1989        &self,
1990        payload: PeginFromOnchainPayload,
1991    ) -> AdminResult<Txid> {
1992        let deposit = DepositAddressPayload {
1993            federation_id: payload.federation_id,
1994        };
1995        let address = self.handle_address_msg(deposit).await?;
1996        let send_onchain = SendOnchainRequest {
1997            address: address.into_unchecked(),
1998            amount: payload.amount,
1999            fee_rate_sats_per_vbyte: payload.fee_rate_sats_per_vbyte,
2000        };
2001        let txid = self.handle_send_onchain_msg(send_onchain).await?;
2002
2003        Ok(txid)
2004    }
2005
2006    /// Registers the gateway with each specified federation.
2007    ///
2008    /// Does nothing once the gateway is shutting down: the lightning connection
2009    /// loop keeps reconnecting while `handle_shutdown_msg` drains the payments
2010    /// that are still in flight, and re-announcing there would advertise a
2011    /// route that is about to disappear, undoing the
2012    /// `unannounce_from_all_federations` the shutdown just performed.
2013    async fn register_federations(
2014        &self,
2015        federations: &BTreeMap<FederationId, FederationConfig>,
2016        register_task_group: &TaskGroup,
2017    ) {
2018        if let GatewayState::ShuttingDown { .. } = self.get_state().await {
2019            info!(
2020                target: LOG_GATEWAY,
2021                "Gateway is shutting down, skipping federation registration"
2022            );
2023            return;
2024        }
2025
2026        if let Ok(lightning_context) = self.get_lightning_context().await {
2027            let route_hints = lightning_context
2028                .lnrpc
2029                .parsed_route_hints(self.num_route_hints)
2030                .await;
2031            if route_hints.is_empty() {
2032                warn!(target: LOG_GATEWAY, "Gateway did not retrieve any route hints, may reduce receive success rate.");
2033            }
2034
2035            for (federation_id, federation_config) in federations {
2036                // A fee that predates the fee limits may be too large to announce. Skip
2037                // that federation rather than failing the whole registration pass: this
2038                // runs on the root task group at startup, so an error here would keep
2039                // the gateway from booting at all.
2040                let routing_fees = match RoutingFees::try_from(federation_config.lightning_fee) {
2041                    Ok(routing_fees) => routing_fees,
2042                    Err(err) => {
2043                        warn!(
2044                            target: LOG_GATEWAY,
2045                            %federation_id,
2046                            err = %err.fmt_compact(),
2047                            "Skipping registration, the configured lightning fee cannot be announced. Set a smaller fee with `set_fees`."
2048                        );
2049                        continue;
2050                    }
2051                };
2052
2053                let fed_manager = self.federation_manager.read().await;
2054                if let Some(client) = fed_manager.client(federation_id) {
2055                    let federation_id = *federation_id;
2056                    let client_arc = client.clone().into_value();
2057                    let route_hints = route_hints.clone();
2058                    let lightning_context = lightning_context.clone();
2059                    let registration_health = self.registration_health.clone();
2060                    let registrations = self
2061                        .registrations
2062                        .clone()
2063                        .into_iter()
2064                        .map(|(protocol, registration)| {
2065                            let attempt =
2066                                registration_health.begin_lnv1_attempt(federation_id, protocol);
2067                            (registration, attempt)
2068                        })
2069                        .collect::<Vec<_>>();
2070
2071                    register_task_group.spawn_cancellable_silent(
2072                        "register federation",
2073                        async move {
2074                            let Ok(gateway_client) =
2075                                client_arc.get_first_module::<GatewayClientModule>()
2076                            else {
2077                                return;
2078                            };
2079
2080                            for (registration, attempt) in registrations {
2081                                let succeeded = gateway_client
2082                                    .try_register_with_federation(
2083                                        route_hints.clone(),
2084                                        GW_ANNOUNCEMENT_TTL,
2085                                        routing_fees,
2086                                        lightning_context.clone(),
2087                                        registration.endpoint_url,
2088                                        registration.keypair,
2089                                    )
2090                                    .await;
2091                                registration_health
2092                                    .complete_attempt(
2093                                        attempt,
2094                                        succeeded,
2095                                        fedimint_core::time::now(),
2096                                        fedimint_core::runtime::Instant::now(),
2097                                    )
2098                                    .await;
2099                            }
2100                        },
2101                    );
2102                }
2103            }
2104        }
2105    }
2106
2107    /// Retrieves a `ClientHandleArc` from the Gateway's in memory structures
2108    /// that keep track of available clients, given a `federation_id`.
2109    pub async fn select_client(
2110        &self,
2111        federation_id: FederationId,
2112    ) -> std::result::Result<Spanned<fedimint_client::ClientHandleArc>, FederationNotConnected>
2113    {
2114        self.federation_manager
2115            .read()
2116            .await
2117            .client(&federation_id)
2118            .cloned()
2119            .ok_or(FederationNotConnected {
2120                federation_id_prefix: federation_id.to_prefix(),
2121            })
2122    }
2123
2124    async fn load_mnemonic(gateway_db: &Database) -> Option<Mnemonic> {
2125        let secret = Client::load_decodable_client_secret::<Vec<u8>>(gateway_db)
2126            .await
2127            .ok()?;
2128        Mnemonic::from_entropy(&secret).ok()
2129    }
2130
2131    /// Reads the connected federation client configs from the Gateway's
2132    /// database and reconstructs the clients necessary for interacting with
2133    /// connection federations.
2134    async fn load_clients(&self) -> AdminResult<()> {
2135        if let GatewayState::NotConfigured { .. } = self.get_state().await {
2136            return Ok(());
2137        }
2138
2139        let mut federation_manager = self.federation_manager.write().await;
2140
2141        let configs = {
2142            let mut dbtx = self.gateway_db.begin_transaction_nc().await;
2143            dbtx.load_federation_configs().await
2144        };
2145
2146        if let Some(max_federation_index) = configs.values().map(|cfg| cfg.federation_index).max() {
2147            federation_manager.set_next_index(max_federation_index + 1);
2148        }
2149
2150        let mnemonic = Self::load_mnemonic(&self.gateway_db)
2151            .await
2152            .expect("mnemonic should be set");
2153
2154        for (federation_id, config) in configs {
2155            let federation_index = config.federation_index;
2156            match Box::pin(Spanned::try_new(
2157                info_span!(target: LOG_GATEWAY, "client", federation_id  = %federation_id.clone()),
2158                self.client_builder
2159                    .build(config, Arc::new(self.clone()), &mnemonic),
2160            ))
2161            .await
2162            {
2163                Ok(client) => {
2164                    federation_manager.add_client(federation_index, client);
2165                }
2166                _ => {
2167                    warn!(target: LOG_GATEWAY, federation_id = %federation_id, "Failed to load client");
2168                }
2169            }
2170        }
2171
2172        Ok(())
2173    }
2174
2175    /// Legacy mechanism for registering the Gateway with connected federations.
2176    /// This will spawn a task that will re-register the Gateway with
2177    /// connected federations every 8.5 mins. Only registers the Gateway if it
2178    /// has successfully connected to the Lightning node, so that it can
2179    /// include route hints in the registration.
2180    fn register_clients_timer(&self) {
2181        // Only spawn background registration thread if gateway is LND
2182        if matches!(self.lightning_mode, LightningMode::Lnd { .. }) {
2183            info!(target: LOG_GATEWAY, "Spawning register task...");
2184            let gateway = self.clone();
2185            let register_task_group = self.task_group.make_subgroup();
2186            self.task_group.spawn_cancellable("register clients", async move {
2187                loop {
2188                    let gateway_state = gateway.get_state().await;
2189                    if let GatewayState::Running { .. } = &gateway_state {
2190                        let mut dbtx = gateway.gateway_db.begin_transaction_nc().await;
2191                        let all_federations_configs = dbtx.load_federation_configs().await.into_iter().collect();
2192                        gateway.register_federations(&all_federations_configs, &register_task_group).await;
2193                    } else {
2194                        // We need to retry more often if the gateway is not in the Running state
2195                        const NOT_RUNNING_RETRY: Duration = Duration::from_secs(10);
2196                        warn!(target: LOG_GATEWAY, gateway_state = %gateway_state, retry_interval = ?NOT_RUNNING_RETRY, "Will not register federation yet because gateway still not in Running state");
2197                        sleep(NOT_RUNNING_RETRY).await;
2198                        continue;
2199                    }
2200
2201                    // Allow a 15% buffer of the TTL before the re-registering gateway
2202                    // with the federations.
2203                    sleep(GW_ANNOUNCEMENT_TTL.mul_f32(0.85)).await;
2204                }
2205            });
2206        }
2207    }
2208
2209    /// Verifies that the federation has at least one lightning module (LNv1 or
2210    /// LNv2) and that the network matches the gateway's network.
2211    async fn check_federation_network(
2212        client: &ClientHandleArc,
2213        network: Network,
2214    ) -> AdminResult<()> {
2215        let federation_id = client.federation_id();
2216        let config = client.config().await;
2217
2218        let lnv1_cfg = config
2219            .modules
2220            .values()
2221            .find(|m| LightningCommonInit::KIND == m.kind);
2222
2223        let lnv2_cfg = config
2224            .modules
2225            .values()
2226            .find(|m| fedimint_lnv2_common::LightningCommonInit::KIND == m.kind);
2227
2228        // Ensure the federation has at least one lightning module
2229        if lnv1_cfg.is_none() && lnv2_cfg.is_none() {
2230            return Err(AdminGatewayError::ClientCreationError(anyhow!(
2231                "Federation {federation_id} does not have any lightning module (LNv1 or LNv2)"
2232            )));
2233        }
2234
2235        // Verify the LNv1 network if present
2236        if let Some(cfg) = lnv1_cfg {
2237            let ln_cfg: &LightningClientConfig = cfg.cast().map_err(anyhow::Error::from)?;
2238
2239            if ln_cfg.network.0 != network {
2240                crit!(
2241                    target: LOG_GATEWAY,
2242                    federation_id = %federation_id,
2243                    network = %network,
2244                    "Incorrect LNv1 network for federation",
2245                );
2246                return Err(AdminGatewayError::ClientCreationError(anyhow!(format!(
2247                    "Unsupported LNv1 network {}",
2248                    ln_cfg.network
2249                ))));
2250            }
2251        }
2252
2253        // Verify the LNv2 network if present
2254        if let Some(cfg) = lnv2_cfg {
2255            let ln_cfg: &fedimint_lnv2_common::config::LightningClientConfig =
2256                cfg.cast().map_err(anyhow::Error::from)?;
2257
2258            if ln_cfg.network != network {
2259                crit!(
2260                    target: LOG_GATEWAY,
2261                    federation_id = %federation_id,
2262                    network = %network,
2263                    "Incorrect LNv2 network for federation",
2264                );
2265                return Err(AdminGatewayError::ClientCreationError(anyhow!(format!(
2266                    "Unsupported LNv2 network {}",
2267                    ln_cfg.network
2268                ))));
2269            }
2270        }
2271
2272        Ok(())
2273    }
2274
2275    /// Checks the Gateway's current state and returns the proper
2276    /// `LightningContext` if it is available.
2277    ///
2278    /// The error is synthesised from the gateway's own state: no RPC is
2279    /// attempted, so `Err` means "this process does not currently hold a
2280    /// session with the lightning node", never "the lightning node was asked
2281    /// and answered no". Callers that would turn a failure here into a
2282    /// decision about a payment must use `await_lightning_context`
2283    /// instead.
2284    pub async fn get_lightning_context(
2285        &self,
2286    ) -> std::result::Result<LightningContext, LightningRpcError> {
2287        match self.get_state().await {
2288            GatewayState::Running { lightning_context }
2289            | GatewayState::ShuttingDown { lightning_context } => Ok(lightning_context),
2290            _ => Err(LightningRpcError::FailedToConnect),
2291        }
2292    }
2293
2294    /// Waits until the gateway holds a `LightningContext` and returns it.
2295    ///
2296    /// The lightning node is the only oracle for whether an HTLC of ours is in
2297    /// flight, so code deciding the fate of a payment must actually ask it.
2298    /// [`Self::get_lightning_context`] cannot stand in for that: its `Err` is
2299    /// produced locally, and the gateway spends part of every startup without
2300    /// a context. [`Self::run`] awaits `load_clients` before `start_gateway`,
2301    /// and building a client starts its executor, so payment state machines
2302    /// persisted across a restart re-enter while the state is still
2303    /// `Disconnected`. Reading that as a payment failure cancels an outgoing
2304    /// contract whose HTLC the previous process may already have settled,
2305    /// leaving the gateway out of pocket for a payment it did make.
2306    ///
2307    /// Waiting is the conservative side of that trade. It ends when the
2308    /// gateway connects, or when the caller is dropped: every caller runs
2309    /// inside a client state machine transition or a webserver request, both
2310    /// of which are cancelled when the gateway shuts down. It does not strand
2311    /// the payer either, since the outgoing contract's timelock refunds them
2312    /// without the gateway's cooperation, whereas a cancellation is final (see
2313    /// `LightningInput` processing in `fedimint-ln-server`).
2314    async fn await_lightning_context(&self) -> LightningContext {
2315        loop {
2316            match self.get_lightning_context().await {
2317                Ok(lightning_context) => return lightning_context,
2318                Err(err) => {
2319                    let state = self.get_state().await;
2320
2321                    warn!(
2322                        target: LOG_GATEWAY,
2323                        err = %err.fmt_compact(),
2324                        %state,
2325                        retry_interval_secs = LIGHTNING_CONTEXT_RETRY_INTERVAL.as_secs(),
2326                        "Not connected to the lightning node, waiting before asking it again",
2327                    );
2328
2329                    sleep(LIGHTNING_CONTEXT_RETRY_INTERVAL).await;
2330                }
2331            }
2332        }
2333    }
2334
2335    /// Iterates through all of the federations the gateway is registered with
2336    /// and requests to remove the registration record.
2337    pub async fn unannounce_from_all_federations(&self) {
2338        if matches!(self.lightning_mode, LightningMode::Lnd { .. }) {
2339            for registration in self.registrations.values() {
2340                self.federation_manager
2341                    .read()
2342                    .await
2343                    .unannounce_from_all_federations(registration.keypair)
2344                    .await;
2345            }
2346        }
2347    }
2348
2349    async fn create_lightning_client(
2350        &self,
2351        runtime: Arc<tokio::runtime::Runtime>,
2352        mnemonic_source: MnemonicSource,
2353    ) -> Box<dyn ILnRpcClient> {
2354        match self.lightning_mode.clone() {
2355            LightningMode::Lnd {
2356                lnd_rpc_addr,
2357                lnd_tls_cert,
2358                lnd_macaroon,
2359                lnd_time_pref,
2360                lnd_payment_timeout_secs,
2361            } => {
2362                // The LND backend uses this to ignore HOLD invoices on the
2363                // shared LND node that aren't federation-bound. Returns true
2364                // iff there is a registered LNv2 incoming contract for the
2365                // given payment hash.
2366                let gateway_db = self.gateway_db.clone();
2367                let lnv2_filter: Lnv2HoldInvoiceFilter = Arc::new(move |hash| {
2368                    let gateway_db = gateway_db.clone();
2369                    Box::pin(async move {
2370                        gateway_db
2371                            .begin_transaction_nc()
2372                            .await
2373                            .load_registered_incoming_contract(PaymentImage::Hash(hash))
2374                            .await
2375                            .is_some()
2376                    })
2377                });
2378
2379                Box::new(GatewayLndClient::new(
2380                    lnd_rpc_addr,
2381                    lnd_tls_cert,
2382                    lnd_macaroon,
2383                    lnd_time_pref,
2384                    lnd_payment_timeout_secs,
2385                    None,
2386                    lnv2_filter,
2387                ))
2388            }
2389            LightningMode::Ldk {
2390                lightning_port,
2391                alias,
2392            } => {
2393                let mnemonic = Self::load_mnemonic(&self.gateway_db)
2394                    .await
2395                    .expect("mnemonic should be set");
2396                // Retrieving the fees inside of LDK can sometimes fail/time out. To prevent
2397                // crashing the gateway, we wait a bit and just try
2398                // to re-create the client. The gateway cannot proceed until this succeeds.
2399                retry("create LDK Node", fibonacci_max_one_hour(), || async {
2400                    ldk::GatewayLdkClient::new(
2401                        &self.client_builder.data_dir().join(LDK_NODE_DB_FOLDER),
2402                        self.chain_source.clone(),
2403                        self.network,
2404                        lightning_port,
2405                        alias.clone(),
2406                        mnemonic.clone(),
2407                        mnemonic_source,
2408                        runtime.clone(),
2409                    )
2410                    .map(Box::new)
2411                    // `retry` logs each failure with `{:#}`, which prints the
2412                    // cause chain only for `anyhow::Error`.
2413                    .map_err(anyhow::Error::from)
2414                })
2415                .await
2416                .expect("Could not create LDK Node")
2417            }
2418        }
2419    }
2420}
2421
2422#[async_trait]
2423impl IAdminGateway for Gateway {
2424    type Error = AdminGatewayError;
2425
2426    /// Returns information about the Gateway back to the client when requested
2427    /// via the webserver.
2428    async fn handle_get_info(&self) -> AdminResult<GatewayInfo> {
2429        let GatewayState::Running { lightning_context } = self.get_state().await else {
2430            return Ok(GatewayInfo {
2431                federations: vec![],
2432                federation_fake_scids: None,
2433                version_hash: fedimint_build_code_version_env!().to_string(),
2434                gateway_state: self.state.read().await.to_string(),
2435                lightning_info: LightningInfo::NotConnected,
2436                lightning_mode: self.lightning_mode.clone(),
2437                registrations: self
2438                    .registrations
2439                    .iter()
2440                    .map(|(k, v)| (k.clone(), (v.endpoint_url.clone(), v.keypair.public_key())))
2441                    .collect(),
2442            });
2443        };
2444
2445        let dbtx = self.gateway_db.begin_transaction_nc().await;
2446        let federations = self
2447            .federation_manager
2448            .read()
2449            .await
2450            .federation_info_all_federations(dbtx)
2451            .await;
2452
2453        let channels: BTreeMap<u64, FederationId> = federations
2454            .iter()
2455            .map(|federation_info| {
2456                (
2457                    federation_info.config.federation_index,
2458                    federation_info.federation_id,
2459                )
2460            })
2461            .collect();
2462
2463        let lightning_info = lightning_context.lnrpc.parsed_node_info().await;
2464
2465        Ok(GatewayInfo {
2466            federations,
2467            federation_fake_scids: Some(channels),
2468            version_hash: fedimint_build_code_version_env!().to_string(),
2469            gateway_state: self.state.read().await.to_string(),
2470            lightning_info,
2471            lightning_mode: self.lightning_mode.clone(),
2472            registrations: self
2473                .registrations
2474                .iter()
2475                .map(|(k, v)| (k.clone(), (v.endpoint_url.clone(), v.keypair.public_key())))
2476                .collect(),
2477        })
2478    }
2479
2480    /// Returns a list of Lightning network channels from the Gateway's
2481    /// Lightning node.
2482    async fn handle_list_channels_msg(
2483        &self,
2484    ) -> AdminResult<Vec<fedimint_gateway_common::ChannelInfo>> {
2485        let context = self.get_lightning_context().await?;
2486        let response = context.lnrpc.list_channels().await?;
2487        Ok(response.channels)
2488    }
2489
2490    /// Computes the 24 hour payment summary statistics for this gateway.
2491    /// Combines the LNv1 and LNv2 stats together.
2492    async fn handle_payment_summary_msg(
2493        &self,
2494        PaymentSummaryPayload {
2495            start_millis,
2496            end_millis,
2497        }: PaymentSummaryPayload,
2498    ) -> AdminResult<PaymentSummaryResponse> {
2499        let federation_manager = self.federation_manager.read().await;
2500        let fed_configs = federation_manager.get_all_federation_configs().await;
2501        let federation_ids = fed_configs.keys().collect::<Vec<_>>();
2502        let start = UNIX_EPOCH + Duration::from_millis(start_millis);
2503        let end = UNIX_EPOCH + Duration::from_millis(end_millis);
2504
2505        if end < start {
2506            return Err(AdminGatewayError::Unexpected(anyhow!("Invalid time range")));
2507        }
2508
2509        let mut outgoing = StructuredPaymentEvents::default();
2510        let mut incoming = StructuredPaymentEvents::default();
2511        for fed_id in federation_ids {
2512            let client = federation_manager
2513                .client(fed_id)
2514                .expect("No client available")
2515                .value();
2516            let all_events = &get_events_for_duration(client, start, end).await;
2517
2518            let (mut lnv1_outgoing, mut lnv1_incoming) = compute_lnv1_stats(all_events);
2519            let (mut lnv2_outgoing, mut lnv2_incoming) = compute_lnv2_stats(all_events);
2520            outgoing.combine(&mut lnv1_outgoing);
2521            incoming.combine(&mut lnv1_incoming);
2522            outgoing.combine(&mut lnv2_outgoing);
2523            incoming.combine(&mut lnv2_incoming);
2524        }
2525
2526        Ok(PaymentSummaryResponse {
2527            outgoing: PaymentStats::compute(&outgoing),
2528            incoming: PaymentStats::compute(&incoming),
2529        })
2530    }
2531
2532    /// Handle a request to have the Gateway leave a federation. The Gateway
2533    /// will request the federation to remove the registration record and
2534    /// the gateway will remove the configuration needed to construct the
2535    /// federation client.
2536    async fn handle_leave_federation(
2537        &self,
2538        payload: LeaveFedPayload,
2539    ) -> AdminResult<FederationInfo> {
2540        // Lock the federation manager before starting the db transaction to reduce the
2541        // chance of db write conflicts.
2542        let mut federation_manager = self.federation_manager.write().await;
2543        let mut dbtx = self.gateway_db.begin_transaction().await;
2544
2545        let federation_info = federation_manager
2546            .leave_federation(
2547                payload.federation_id,
2548                &mut dbtx.to_ref_nc(),
2549                self.registrations.values().collect(),
2550            )
2551            .await?;
2552
2553        dbtx.remove_federation_config(payload.federation_id).await;
2554        dbtx.commit_tx().await;
2555        self.registration_health
2556            .clear_federation(payload.federation_id)
2557            .await;
2558        Ok(federation_info)
2559    }
2560
2561    /// Handles a connection request to join a new federation. The gateway will
2562    /// download the federation's client configuration, construct a new
2563    /// client, registers, the gateway with the federation, and persists the
2564    /// necessary config to reconstruct the client when restarting the gateway.
2565    async fn handle_connect_federation(
2566        &self,
2567        payload: ConnectFedPayload,
2568    ) -> AdminResult<FederationInfo> {
2569        let GatewayState::Running { lightning_context } = self.get_state().await else {
2570            return Err(AdminGatewayError::Lightning(
2571                LightningRpcError::FailedToConnect,
2572            ));
2573        };
2574
2575        let invite_code = InviteCode::from_str(&payload.invite_code).map_err(|e| {
2576            AdminGatewayError::ClientCreationError(anyhow!(format!(
2577                "Invalid federation member string {e:?}"
2578            )))
2579        })?;
2580
2581        let federation_id = invite_code.federation_id();
2582
2583        let mut federation_manager = self.federation_manager.write().await;
2584
2585        // Check if this federation has already been registered
2586        if federation_manager.has_federation(federation_id) {
2587            return Err(AdminGatewayError::ClientCreationError(anyhow!(
2588                "Federation has already been registered"
2589            )));
2590        }
2591
2592        // The gateway deterministically assigns a unique identifier (u64) to each
2593        // federation connected.
2594        let federation_index = federation_manager.pop_next_index()?;
2595
2596        let federation_config = FederationConfig {
2597            invite_code,
2598            federation_index,
2599            lightning_fee: self.default_routing_fees,
2600            transaction_fee: self.default_transaction_fees,
2601            payment_policies: BTreeSet::new(),
2602            // Note: deprecated, unused
2603            _connector: ConnectorType::Tcp,
2604        };
2605
2606        // The default fees are validated at startup, so this only fails if the gateway
2607        // is running with fees that predate that check. Refuse to join a federation
2608        // whose fee could not be announced rather than persisting its config.
2609        let routing_fees = RoutingFees::try_from(federation_config.lightning_fee)
2610            .map_err(|err| AdminGatewayError::GatewayConfigurationError(err.to_string()))?;
2611
2612        let mnemonic = Self::load_mnemonic(&self.gateway_db)
2613            .await
2614            .expect("mnemonic should be set");
2615        let recover = payload.recover.unwrap_or(false);
2616        if recover {
2617            self.client_builder
2618                .recover(federation_config.clone(), Arc::new(self.clone()), &mnemonic)
2619                .await?;
2620        }
2621
2622        let client = self
2623            .client_builder
2624            .build(federation_config.clone(), Arc::new(self.clone()), &mnemonic)
2625            .await?;
2626
2627        if recover {
2628            client.wait_for_all_active_state_machines().await;
2629        }
2630
2631        // Instead of using `FederationManager::federation_info`, we manually create
2632        // federation info here because short channel id is not yet persisted.
2633        let federation_info = FederationInfo {
2634            federation_id,
2635            federation_name: federation_manager.federation_name(&client).await,
2636            balance_msat: client
2637                .get_balance_for_btc(Account::Primary)
2638                .await
2639                .unwrap_or_else(|err| {
2640                    warn!(
2641                        target: LOG_GATEWAY,
2642                        err = %err.fmt_compact(),
2643                        %federation_id,
2644                        "Balance not immediately available after joining/recovering."
2645                    );
2646                    Amount::default()
2647                }),
2648            config: federation_config.clone(),
2649            last_backup_time: None,
2650        };
2651
2652        Self::check_federation_network(&client, self.network).await?;
2653        if matches!(self.lightning_mode, LightningMode::Lnd { .. })
2654            && let Ok(lnv1) = client.get_first_module::<GatewayClientModule>()
2655        {
2656            for (protocol, registration) in &self.registrations {
2657                let attempt = self
2658                    .registration_health
2659                    .begin_lnv1_attempt(federation_id, protocol.clone());
2660                let succeeded = lnv1
2661                    .try_register_with_federation(
2662                        // Route hints will be updated in the background
2663                        Vec::new(),
2664                        GW_ANNOUNCEMENT_TTL,
2665                        routing_fees,
2666                        lightning_context.clone(),
2667                        registration.endpoint_url.clone(),
2668                        registration.keypair,
2669                    )
2670                    .await;
2671                self.registration_health
2672                    .complete_attempt(
2673                        attempt,
2674                        succeeded,
2675                        fedimint_core::time::now(),
2676                        fedimint_core::runtime::Instant::now(),
2677                    )
2678                    .await;
2679            }
2680        }
2681
2682        // no need to enter span earlier, because connect-fed has a span
2683        federation_manager.add_client(
2684            federation_index,
2685            Spanned::new(
2686                info_span!(target: LOG_GATEWAY, "client", federation_id=%federation_id.clone()),
2687                async { client },
2688            )
2689            .await,
2690        );
2691
2692        let mut dbtx = self.gateway_db.begin_transaction().await;
2693        dbtx.save_federation_config(&federation_config).await;
2694        dbtx.save_federation_backup_record(federation_id, None)
2695            .await;
2696        dbtx.commit_tx().await;
2697        debug!(
2698            target: LOG_GATEWAY,
2699            federation_id = %federation_id,
2700            federation_index = %federation_index,
2701            "Federation connected"
2702        );
2703
2704        Ok(federation_info)
2705    }
2706
2707    /// Handles a request to change the lightning or transaction fees for all
2708    /// federations or a federation specified by the `FederationId`.
2709    async fn handle_set_fees_msg(
2710        &self,
2711        SetFeesPayload {
2712            federation_id,
2713            lightning_base,
2714            lightning_parts_per_million,
2715            transaction_base,
2716            transaction_parts_per_million,
2717        }: SetFeesPayload,
2718    ) -> AdminResult<()> {
2719        let mut dbtx = self.gateway_db.begin_transaction().await;
2720        let mut fed_configs = if let Some(fed_id) = federation_id {
2721            dbtx.load_federation_configs()
2722                .await
2723                .into_iter()
2724                .filter(|(id, _)| *id == fed_id)
2725                .collect::<BTreeMap<_, _>>()
2726        } else {
2727            dbtx.load_federation_configs().await
2728        };
2729
2730        // Silently succeeding on an unknown federation would let a mistyped id
2731        // pass for fees that were never changed.
2732        if let Some(fed_id) = federation_id
2733            && fed_configs.is_empty()
2734        {
2735            return Err(FederationNotConnected {
2736                federation_id_prefix: fed_id.to_prefix(),
2737            }
2738            .into());
2739        }
2740
2741        let federation_manager = self.federation_manager.read().await;
2742
2743        for (federation_id, config) in &mut fed_configs {
2744            let mut lightning_fee = config.lightning_fee;
2745            if let Some(lightning_base) = lightning_base {
2746                lightning_fee.base = lightning_base;
2747            }
2748
2749            if let Some(lightning_ppm) = lightning_parts_per_million {
2750                lightning_fee.parts_per_million = lightning_ppm;
2751            }
2752
2753            let mut transaction_fee = config.transaction_fee;
2754            if let Some(transaction_base) = transaction_base {
2755                transaction_fee.base = transaction_base;
2756            }
2757
2758            if let Some(transaction_ppm) = transaction_parts_per_million {
2759                transaction_fee.parts_per_million = transaction_ppm;
2760            }
2761
2762            // Changing the fees of a federation the gateway is not connected to is
2763            // rejected, as it was before the fee limits applied to every federation.
2764            federation_manager
2765                .client(federation_id)
2766                .ok_or(FederationNotConnected {
2767                    federation_id_prefix: federation_id.to_prefix(),
2768                })?;
2769
2770            // The limits are enforced for every federation, not just the ones running
2771            // LNv2. An unchecked fee is persisted verbatim and is converted into
2772            // `RoutingFees` on every LNv1 payment and on every registration, including
2773            // the one at startup, so a fee that does not fit into the `u32` components
2774            // of `RoutingFees` would leave the gateway unable to boot.
2775            let send_fees = lightning_fee.checked_add(transaction_fee).ok_or_else(|| {
2776                AdminGatewayError::GatewayConfigurationError(format!(
2777                    "Total Send fees overflowed, they may not exceed {}",
2778                    PaymentFee::SEND_FEE_LIMIT
2779                ))
2780            })?;
2781
2782            // Check if the lightning fee + transaction fee is higher than the send limit
2783            if !send_fees.is_within(&PaymentFee::SEND_FEE_LIMIT) {
2784                return Err(AdminGatewayError::GatewayConfigurationError(format!(
2785                    "Total Send fees exceeded {}",
2786                    PaymentFee::SEND_FEE_LIMIT
2787                )));
2788            }
2789
2790            // Check if the transaction fee is higher than the receive limit
2791            if !transaction_fee.is_within(&PaymentFee::RECEIVE_FEE_LIMIT) {
2792                return Err(AdminGatewayError::GatewayConfigurationError(format!(
2793                    "Transaction fees exceeded RECEIVE LIMIT {}",
2794                    PaymentFee::RECEIVE_FEE_LIMIT
2795                )));
2796            }
2797
2798            config.lightning_fee = lightning_fee;
2799            config.transaction_fee = transaction_fee;
2800            dbtx.save_federation_config(config).await;
2801        }
2802
2803        dbtx.commit_tx().await;
2804
2805        if matches!(self.lightning_mode, LightningMode::Lnd { .. }) {
2806            let register_task_group = TaskGroup::new();
2807
2808            self.register_federations(&fed_configs, &register_task_group)
2809                .await;
2810        }
2811
2812        Ok(())
2813    }
2814
2815    /// Handles a request to change which payments the gateway performs on
2816    /// behalf of the clients of all federations or of the federation specified
2817    /// by the `FederationId`. Like `set_fees`, only the settings present in
2818    /// the payload change.
2819    async fn handle_set_payment_policy_msg(
2820        &self,
2821        SetPaymentPolicyPayload {
2822            federation_id,
2823            receive_enabled,
2824        }: SetPaymentPolicyPayload,
2825    ) -> AdminResult<()> {
2826        // Taken before the policy is read anywhere else: every payment admitted
2827        // under the old policy funds before this returns, and none is admitted
2828        // afterwards.
2829        let _policy_change = self.payment_policy_lock.write().await;
2830
2831        let mut dbtx = self.gateway_db.begin_transaction().await;
2832        let mut fed_configs = if let Some(fed_id) = federation_id {
2833            dbtx.load_federation_configs()
2834                .await
2835                .into_iter()
2836                .filter(|(id, _)| *id == fed_id)
2837                .collect::<BTreeMap<_, _>>()
2838        } else {
2839            dbtx.load_federation_configs().await
2840        };
2841
2842        // Silently succeeding on an unknown federation would let a mistyped id
2843        // pass for a switch that was never flipped.
2844        if let Some(fed_id) = federation_id
2845            && fed_configs.is_empty()
2846        {
2847            return Err(FederationNotConnected {
2848                federation_id_prefix: fed_id.to_prefix(),
2849            }
2850            .into());
2851        }
2852
2853        let federation_manager = self.federation_manager.read().await;
2854
2855        for (federation_id, config) in &mut fed_configs {
2856            federation_manager
2857                .client(federation_id)
2858                .ok_or(FederationNotConnected {
2859                    federation_id_prefix: federation_id.to_prefix(),
2860                })?;
2861
2862            if let Some(receive_enabled) = receive_enabled {
2863                if receive_enabled {
2864                    config
2865                        .payment_policies
2866                        .remove(&PaymentPolicy::ReceivesDisabled);
2867                } else {
2868                    config
2869                        .payment_policies
2870                        .insert(PaymentPolicy::ReceivesDisabled);
2871                }
2872            }
2873
2874            info!(
2875                target: LOG_GATEWAY,
2876                %federation_id,
2877                payment_policies = ?config.payment_policies,
2878                "Updated federation payment policy"
2879            );
2880
2881            dbtx.save_federation_config(config).await;
2882        }
2883
2884        dbtx.commit_tx().await;
2885
2886        Ok(())
2887    }
2888
2889    /// Handles an authenticated request for the gateway's mnemonic. This also
2890    /// returns a vector of federations that are not using the mnemonic
2891    /// backup strategy.
2892    async fn handle_mnemonic_msg(&self) -> AdminResult<MnemonicResponse> {
2893        let mnemonic = Self::load_mnemonic(&self.gateway_db)
2894            .await
2895            .expect("mnemonic should be set");
2896        let words = mnemonic
2897            .words()
2898            .map(std::string::ToString::to_string)
2899            .collect::<Vec<_>>();
2900        let all_federations = self
2901            .federation_manager
2902            .read()
2903            .await
2904            .get_all_federation_configs()
2905            .await
2906            .keys()
2907            .copied()
2908            .collect::<BTreeSet<_>>();
2909        let legacy_federations = self.client_builder.legacy_federations(all_federations);
2910        let mnemonic_response = MnemonicResponse {
2911            mnemonic: words,
2912            legacy_federations,
2913        };
2914        Ok(mnemonic_response)
2915    }
2916
2917    /// Instructs the Gateway's Lightning node to open a channel to a peer
2918    /// specified by `pubkey`.
2919    async fn handle_open_channel_msg(&self, payload: OpenChannelRequest) -> AdminResult<Txid> {
2920        info!(target: LOG_GATEWAY, pubkey = %payload.pubkey, host = %payload.host, amount = %payload.channel_size_sats, "Opening Lightning channel...");
2921        let context = self.get_lightning_context().await?;
2922        let res = context.lnrpc.open_channel(payload).await?;
2923        info!(target: LOG_GATEWAY, txid = %res.funding_txid, "Initiated channel open");
2924        Txid::from_str(&res.funding_txid).map_err(|e| {
2925            AdminGatewayError::Lightning(LightningRpcError::InvalidMetadata {
2926                failure_reason: format!("Received invalid channel funding txid string {e}"),
2927            })
2928        })
2929    }
2930
2931    /// Instructs the Gateway's Lightning node to connect to a peer specified by
2932    /// `pubkey`.
2933    async fn handle_connect_peer_msg(&self, payload: ConnectPeerRequest) -> AdminResult<()> {
2934        info!(
2935            target: LOG_GATEWAY,
2936            pubkey = %payload.node_address.pubkey,
2937            host = %payload.node_address.host_with_port(),
2938            "Connecting to Lightning peer..."
2939        );
2940        let context = self.get_lightning_context().await?;
2941        context.lnrpc.connect_peer(payload).await?;
2942        info!(target: LOG_GATEWAY, "Connected to Lightning peer");
2943        Ok(())
2944    }
2945
2946    /// Instructs the Gateway's Lightning node to close all channels with a peer
2947    /// specified by `pubkey`.
2948    async fn handle_close_channels_with_peer_msg(
2949        &self,
2950        payload: CloseChannelsWithPeerRequest,
2951    ) -> AdminResult<CloseChannelsWithPeerResponse> {
2952        info!(target: LOG_GATEWAY, close_channel_request = %payload, "Closing lightning channel...");
2953        let context = self.get_lightning_context().await?;
2954        let response = context
2955            .lnrpc
2956            .close_channels_with_peer(payload.clone())
2957            .await?;
2958        info!(target: LOG_GATEWAY, close_channel_request = %payload, "Initiated channel closure");
2959        Ok(response)
2960    }
2961
2962    /// Updates the local-side routing fees (base + ppm) on a single channel
2963    /// identified by funding outpoint.
2964    async fn handle_set_channel_fees_msg(&self, payload: SetChannelFeesRequest) -> AdminResult<()> {
2965        info!(
2966            target: LOG_GATEWAY,
2967            funding_outpoint = %payload.funding_outpoint,
2968            base_fee_msat = payload.base_fee_msat,
2969            parts_per_million = payload.parts_per_million,
2970            "Updating channel fees..."
2971        );
2972        let context = self.get_lightning_context().await?;
2973        context.lnrpc.set_channel_fees(payload).await?;
2974        Ok(())
2975    }
2976
2977    /// Returns the ecash, lightning, and onchain balances for the gateway and
2978    /// the gateway's lightning node.
2979    async fn handle_get_balances_msg(&self) -> AdminResult<GatewayBalances> {
2980        let dbtx = self.gateway_db.begin_transaction_nc().await;
2981        let federation_infos = self
2982            .federation_manager
2983            .read()
2984            .await
2985            .federation_info_all_federations(dbtx)
2986            .await;
2987
2988        let ecash_balances: Vec<FederationBalanceInfo> = federation_infos
2989            .iter()
2990            .map(|federation_info| FederationBalanceInfo {
2991                federation_id: federation_info.federation_id,
2992                ecash_balance_msats: Amount {
2993                    msats: federation_info.balance_msat.msats,
2994                },
2995            })
2996            .collect();
2997
2998        let context = self.get_lightning_context().await?;
2999        let lightning_node_balances = context.lnrpc.get_balances().await?;
3000
3001        Ok(GatewayBalances {
3002            onchain_balance_sats: lightning_node_balances.onchain_balance_sats,
3003            spendable_onchain_balance_sats: Some(
3004                lightning_node_balances.spendable_onchain_balance_sats,
3005            ),
3006            lightning_balance_msats: lightning_node_balances.lightning_balance_msats,
3007            ecash_balances,
3008            inbound_lightning_liquidity_msats: lightning_node_balances
3009                .inbound_lightning_liquidity_msats,
3010        })
3011    }
3012
3013    /// Send funds from the gateway's lightning node on-chain wallet.
3014    async fn handle_send_onchain_msg(&self, payload: SendOnchainRequest) -> AdminResult<Txid> {
3015        let context = self.get_lightning_context().await?;
3016        let response = context.lnrpc.send_onchain(payload.clone()).await?;
3017        let txid =
3018            Txid::from_str(&response.txid).map_err(|e| AdminGatewayError::WithdrawError {
3019                failure_reason: format!("Failed to parse withdrawal TXID: {e}"),
3020            })?;
3021        info!(onchain_request = %payload, txid = %txid, "Sent onchain transaction");
3022        Ok(txid)
3023    }
3024
3025    /// Generates an onchain address to fund the gateway's lightning node.
3026    async fn handle_get_ln_onchain_address_msg(&self) -> AdminResult<Address> {
3027        let context = self.get_lightning_context().await?;
3028        let response = context.lnrpc.get_ln_onchain_address().await?;
3029
3030        let address = Address::from_str(&response.address).map_err(|e| {
3031            AdminGatewayError::Lightning(LightningRpcError::InvalidMetadata {
3032                failure_reason: e.to_string(),
3033            })
3034        })?;
3035
3036        address.require_network(self.network).map_err(|e| {
3037            AdminGatewayError::Lightning(LightningRpcError::InvalidMetadata {
3038                failure_reason: e.to_string(),
3039            })
3040        })
3041    }
3042
3043    async fn handle_deposit_address_msg(
3044        &self,
3045        payload: DepositAddressPayload,
3046    ) -> AdminResult<Address> {
3047        self.handle_address_msg(payload).await
3048    }
3049
3050    async fn handle_receive_ecash_msg(
3051        &self,
3052        payload: ReceiveEcashPayload,
3053    ) -> AdminResult<ReceiveEcashResponse> {
3054        Self::handle_receive_ecash_msg(self, payload)
3055            .await
3056            .map_err(|e| AdminGatewayError::Unexpected(anyhow::anyhow!("{e}")))
3057    }
3058
3059    /// Creates an invoice that is directly payable to the gateway's lightning
3060    /// node.
3061    async fn handle_create_invoice_for_operator_msg(
3062        &self,
3063        payload: CreateInvoiceForOperatorPayload,
3064    ) -> AdminResult<Bolt11Invoice> {
3065        let GatewayState::Running { lightning_context } = self.get_state().await else {
3066            return Err(AdminGatewayError::Lightning(
3067                LightningRpcError::FailedToConnect,
3068            ));
3069        };
3070
3071        Bolt11Invoice::from_str(
3072            &lightning_context
3073                .lnrpc
3074                .create_invoice(CreateInvoiceRequest {
3075                    payment_hash: None, /* Empty payment hash indicates an invoice payable
3076                                         * directly to the gateway. */
3077                    amount_msat: payload.amount_msats,
3078                    expiry_secs: payload.expiry_secs.unwrap_or(3600),
3079                    description: payload.description.map(InvoiceDescription::Direct),
3080                })
3081                .await?
3082                .invoice,
3083        )
3084        .map_err(|e| {
3085            AdminGatewayError::Lightning(LightningRpcError::InvalidMetadata {
3086                failure_reason: e.to_string(),
3087            })
3088        })
3089    }
3090
3091    /// Requests the gateway to pay an outgoing LN invoice using its own funds.
3092    /// Returns the payment hash's preimage on success.
3093    async fn handle_pay_invoice_for_operator_msg(
3094        &self,
3095        payload: PayInvoiceForOperatorPayload,
3096    ) -> AdminResult<Preimage> {
3097        // Those are the ldk defaults
3098        const BASE_FEE: u64 = 50;
3099        const FEE_DENOMINATOR: u64 = 100;
3100        const MAX_DELAY: u64 = 1008;
3101
3102        let GatewayState::Running { lightning_context } = self.get_state().await else {
3103            return Err(AdminGatewayError::Lightning(
3104                LightningRpcError::FailedToConnect,
3105            ));
3106        };
3107
3108        let max_fee = BASE_FEE
3109            + payload
3110                .invoice
3111                .amount_milli_satoshis()
3112                .context("Invoice is missing amount")?
3113                .saturating_div(FEE_DENOMINATOR);
3114
3115        let res = lightning_context
3116            .lnrpc
3117            .pay(payload.invoice, MAX_DELAY, Amount::from_msats(max_fee))
3118            .await?;
3119        Ok(res.preimage)
3120    }
3121
3122    /// Lists the transactions that the lightning node has made.
3123    async fn handle_list_transactions_msg(
3124        &self,
3125        payload: ListTransactionsPayload,
3126    ) -> AdminResult<ListTransactionsResponse> {
3127        let lightning_context = self.get_lightning_context().await?;
3128        let response = lightning_context
3129            .lnrpc
3130            .list_transactions(payload.start_secs, payload.end_secs)
3131            .await?;
3132        Ok(response)
3133    }
3134
3135    // Handles a request the spend the gateway's ecash for a given federation.
3136    async fn handle_spend_ecash_msg(
3137        &self,
3138        payload: SpendEcashPayload,
3139    ) -> AdminResult<SpendEcashResponse> {
3140        let client = self
3141            .select_client(payload.federation_id)
3142            .await?
3143            .into_value();
3144
3145        if let Ok(mint_module) = client.get_first_module::<MintClientModule>() {
3146            let notes = mint_module
3147                .send_oob_notes(payload.amount, ())
3148                .await
3149                .map_err(|e| AdminGatewayError::Unexpected(e.into()))?;
3150            debug!(target: LOG_GATEWAY, ?notes, "Spend ecash notes");
3151            Ok(SpendEcashResponse {
3152                notes: notes.to_string(),
3153            })
3154        } else if let Ok(mint_module) = client.get_primary_module_for_unit::<MintV2ClientModule>(
3155            fedimint_core::module::AmountUnit::BITCOIN,
3156        ) {
3157            let (_, ecash) = mint_module
3158                .send(
3159                    Account::Primary,
3160                    payload.amount,
3161                    serde_json::Value::Null,
3162                    true,
3163                )
3164                .await
3165                .map_err(|e| AdminGatewayError::Unexpected(e.into()))?;
3166
3167            Ok(SpendEcashResponse {
3168                notes: base32::encode_prefixed(FEDIMINT_PREFIX, &ecash),
3169            })
3170        } else {
3171            Err(AdminGatewayError::Unexpected(anyhow::anyhow!(
3172                "No mint module available"
3173            )))
3174        }
3175    }
3176
3177    /// Instructs the gateway to shutdown, but only after all incoming payments
3178    /// have been handled.
3179    async fn handle_shutdown_msg(&self, task_group: TaskGroup) -> AdminResult<()> {
3180        // Take the write lock on the state so that no additional payments are
3181        // processed. `ShuttingDown` is terminal, so the state cannot move back to
3182        // `Running` once this returns.
3183        let was_running = {
3184            let mut state_guard = self.state.write().await;
3185            if let GatewayState::Running { lightning_context } = state_guard.clone() {
3186                *state_guard = GatewayState::ShuttingDown { lightning_context };
3187                true
3188            } else {
3189                false
3190            }
3191        };
3192
3193        // The guard has to be released before waiting. Finishing an incoming payment
3194        // that already bought the preimage from the federation goes through
3195        // `complete_htlc`, which loops on `get_lightning_context` and would block on
3196        // the write guard forever. `/stop` would never return, the HTLC would expire,
3197        // and the gateway would be left having spent ecash for a payment its sender
3198        // gets refunded. `get_lightning_context` accepts `ShuttingDown`, so the
3199        // in-flight payments can complete while the gateway drains.
3200        if was_running {
3201            self.federation_manager
3202                .read()
3203                .await
3204                .wait_for_incoming_payments()
3205                .await?;
3206        }
3207
3208        let tg = task_group.clone();
3209        tg.spawn("Kill Gateway", |_task_handle| async {
3210            if let Err(err) = task_group.shutdown_join_all(Duration::from_mins(3)).await {
3211                warn!(target: LOG_GATEWAY, err = %err.fmt_compact(), "Error shutting down gateway");
3212            }
3213        });
3214        Ok(())
3215    }
3216
3217    fn get_task_group(&self) -> TaskGroup {
3218        self.task_group.clone()
3219    }
3220
3221    /// Returns a Bitcoin TXID from a peg-out transaction for a specific
3222    /// connected federation.
3223    async fn handle_withdraw_msg(&self, payload: WithdrawPayload) -> AdminResult<WithdrawResponse> {
3224        let WithdrawPayload {
3225            amount,
3226            address,
3227            federation_id,
3228            quoted_fees,
3229        } = payload;
3230
3231        let address_network = get_network_for_address(&address);
3232        let gateway_network = self.network;
3233        let Ok(address) = address.require_network(gateway_network) else {
3234            return Err(AdminGatewayError::WithdrawError {
3235                failure_reason: format!(
3236                    "Gateway is running on network {gateway_network}, but provided withdraw address is for network {address_network}"
3237                ),
3238            });
3239        };
3240
3241        let client = self.select_client(federation_id).await?;
3242
3243        if let Ok(wallet_module) = client
3244            .value()
3245            .get_first_module::<fedimint_walletv2_client::WalletClientModule>()
3246        {
3247            // The UI round-trips the walletv2 flat fee through
3248            // `PegOutFees::from_amount`, so `amount()` recovers it exactly.
3249            let quoted_fee = quoted_fees.map(|fees| fees.amount());
3250            return withdraw_v2(client.value(), &wallet_module, &address, amount, quoted_fee).await;
3251        }
3252
3253        let wallet_module = client
3254            .value()
3255            .get_first_module::<WalletClientModule>()
3256            .map_err(anyhow::Error::from)?;
3257
3258        // If fees are provided (from UI preview flow), use them directly
3259        // Otherwise fetch fees (CLI backwards compatibility)
3260        let (withdraw_amount, fees) = match quoted_fees {
3261            // UI flow: user confirmed these exact values, just use them
3262            Some(fees) => {
3263                let amt = match amount {
3264                    BitcoinAmountOrAll::Amount(a) => a,
3265                    BitcoinAmountOrAll::All => {
3266                        // UI always resolves "all" to specific amount in preview - reject if not
3267                        return Err(AdminGatewayError::WithdrawError {
3268                            failure_reason:
3269                                "Cannot use 'all' with quoted fees - amount must be resolved first"
3270                                    .to_string(),
3271                        });
3272                    }
3273                };
3274                (amt, fees)
3275            }
3276            // CLI flow: fetch fees (existing behavior for backwards compatibility)
3277            None => match amount {
3278                // The on-chain fee is only part of the cost of withdrawing
3279                // everything: funding the peg-out output also incurs the
3280                // federation's per-note fees. The returned fees are quoted at
3281                // the returned amount, so they must be used together.
3282                BitcoinAmountOrAll::All => {
3283                    let balance = client
3284                        .value()
3285                        .get_balance_for_btc(Account::Primary)
3286                        .await
3287                        .map_err(|err| {
3288                            AdminGatewayError::Unexpected(anyhow!(
3289                                "Balance not available: {}",
3290                                err.fmt_compact()
3291                            ))
3292                        })?;
3293
3294                    wallet_module
3295                        .max_withdrawable_amount(&address, balance)
3296                        .await
3297                        .map_err(|err| AdminGatewayError::WithdrawError {
3298                            failure_reason: format!(
3299                                "Insufficient funds. Balance: {balance}: {}",
3300                                err.fmt_compact()
3301                            ),
3302                        })?
3303                }
3304                BitcoinAmountOrAll::Amount(amount) => (
3305                    amount,
3306                    wallet_module
3307                        .get_withdraw_fees(&address, amount)
3308                        .await
3309                        .map_err(|e| AdminGatewayError::Unexpected(e.into()))?,
3310                ),
3311            },
3312        };
3313
3314        let operation_id = wallet_module
3315            .withdraw(&address, withdraw_amount, fees, ())
3316            .await
3317            .map_err(|e| AdminGatewayError::Unexpected(e.into()))?;
3318        let mut updates = wallet_module
3319            .subscribe_withdraw_updates(operation_id)
3320            .await
3321            .map_err(|e| AdminGatewayError::Unexpected(e.into()))?
3322            .into_stream();
3323
3324        while let Some(update) = updates.next().await {
3325            match update {
3326                WithdrawState::Succeeded(txid) => {
3327                    info!(target: LOG_GATEWAY, amount = %withdraw_amount, address = %address, "Sent funds");
3328                    return Ok(WithdrawResponse { txid, fees });
3329                }
3330                WithdrawState::Failed(e) => {
3331                    return Err(AdminGatewayError::WithdrawError { failure_reason: e });
3332                }
3333                WithdrawState::Created => {}
3334            }
3335        }
3336
3337        Err(AdminGatewayError::WithdrawError {
3338            failure_reason: "Ran out of state updates while withdrawing".to_string(),
3339        })
3340    }
3341
3342    /// Returns a preview of the withdrawal fees without executing the
3343    /// withdrawal. Used by the UI for two-step withdrawal confirmation.
3344    async fn handle_withdraw_preview_msg(
3345        &self,
3346        payload: WithdrawPreviewPayload,
3347    ) -> AdminResult<WithdrawPreviewResponse> {
3348        // Deserialized amounts can bypass BitcoinAmountOrAll::from_str.
3349        // Reject them before converting to millisatoshis or querying either wallet.
3350        if let BitcoinAmountOrAll::Amount(amount) = payload.amount
3351            && amount > bitcoin::Amount::MAX_MONEY
3352        {
3353            return Err(AdminGatewayError::WithdrawError {
3354                failure_reason: "Withdrawal amount exceeds maximum Bitcoin supply".to_string(),
3355            });
3356        }
3357
3358        let gateway_network = self.network;
3359        let address_checked = payload
3360            .address
3361            .clone()
3362            .require_network(gateway_network)
3363            .map_err(|_| AdminGatewayError::WithdrawError {
3364                failure_reason: "Address network mismatch".to_string(),
3365            })?;
3366
3367        let client = self.select_client(payload.federation_id).await?;
3368
3369        let WithdrawDetails {
3370            amount,
3371            mint_fees,
3372            peg_out_fees,
3373            flat_peg_out_fee,
3374        } = match payload.amount {
3375            BitcoinAmountOrAll::All => {
3376                calculate_max_withdrawable(client.value(), &address_checked).await?
3377            }
3378            BitcoinAmountOrAll::Amount(btc_amount) => {
3379                if let Ok(wallet_module) = client.value().get_first_module::<WalletClientModule>() {
3380                    WithdrawDetails {
3381                        amount: btc_amount.into(),
3382                        mint_fees: None,
3383                        peg_out_fees: wallet_module
3384                            .get_withdraw_fees(&address_checked, btc_amount)
3385                            .await
3386                            .map_err(|e| AdminGatewayError::Unexpected(e.into()))?,
3387                        flat_peg_out_fee: false,
3388                    }
3389                } else if let Ok(wallet_module) = client
3390                    .value()
3391                    .get_first_module::<fedimint_walletv2_client::WalletClientModule>(
3392                ) {
3393                    let fee = wallet_module.send_fee().await.map_err(|e| {
3394                        AdminGatewayError::WithdrawError {
3395                            failure_reason: e.fmt_compact().to_string(),
3396                        }
3397                    })?;
3398                    // The wallet output carries the payment plus the on-chain
3399                    // fee; funding it costs the federation fees quoted here.
3400                    let output_amount = btc_amount.checked_add(fee).ok_or_else(|| {
3401                        AdminGatewayError::WithdrawError {
3402                            failure_reason: "Withdrawal amount overflow".to_string(),
3403                        }
3404                    })?;
3405                    let federation_fees = wallet_module
3406                        .send_fee_quote(Account::Primary, output_amount)
3407                        .await
3408                        .map_err(|e| AdminGatewayError::WithdrawError {
3409                            failure_reason: e.fmt_compact().to_string(),
3410                        })?
3411                        .total()
3412                        .get_bitcoin();
3413                    WithdrawDetails {
3414                        amount: btc_amount.into(),
3415                        mint_fees: Some(federation_fees),
3416                        peg_out_fees: PegOutFees::from_amount(fee),
3417                        flat_peg_out_fee: true,
3418                    }
3419                } else {
3420                    return Err(AdminGatewayError::Unexpected(anyhow!(
3421                        "No wallet module found"
3422                    )));
3423                }
3424            }
3425        };
3426
3427        let total_cost = amount
3428            .checked_add(peg_out_fees.amount().into())
3429            .and_then(|a| a.checked_add(mint_fees.unwrap_or(Amount::ZERO)))
3430            .ok_or_else(|| AdminGatewayError::Unexpected(anyhow!("Total cost overflow")))?;
3431
3432        Ok(WithdrawPreviewResponse {
3433            withdraw_amount: amount,
3434            address: payload.address.assume_checked().to_string(),
3435            peg_out_fees,
3436            total_cost,
3437            mint_fees,
3438            flat_peg_out_fee,
3439        })
3440    }
3441
3442    /// Queries the client log for payment events and returns to the user.
3443    /// Returns a paginated list of gateway payment-related events, ordered from
3444    /// newest to oldest.
3445    ///
3446    /// If `event_kinds` is empty, only events matching `ALL_GATEWAY_EVENTS`
3447    /// are returned — this is **not** equivalent to "all events". Other
3448    /// internal events (e.g. `tx-created`, `NoteCreated`) share the same event
3449    /// log and consume IDs, so returned event IDs may be non-contiguous.
3450    ///
3451    /// Pagination works backwards from `end_position` (or the log tip if
3452    /// `None`), returning at most `pagination_size` matching events.
3453    async fn handle_payment_log_msg(
3454        &self,
3455        PaymentLogPayload {
3456            end_position,
3457            pagination_size,
3458            federation_id,
3459            event_kinds,
3460        }: PaymentLogPayload,
3461    ) -> AdminResult<PaymentLogResponse> {
3462        const BATCH_SIZE: u64 = 10_000;
3463        let federation_manager = self.federation_manager.read().await;
3464        let client = federation_manager
3465            .client(&federation_id)
3466            .ok_or(FederationNotConnected {
3467                federation_id_prefix: federation_id.to_prefix(),
3468            })?
3469            .value();
3470
3471        // An empty `event_kinds` defaults to gateway payment-related events, not
3472        // "all events". This means returned event IDs may be non-contiguous since
3473        // other internal events share the same ID space.
3474        let event_kinds = if event_kinds.is_empty() {
3475            ALL_GATEWAY_EVENTS.to_vec()
3476        } else {
3477            event_kinds
3478        };
3479
3480        let end_position = if let Some(position) = end_position {
3481            position
3482        } else {
3483            let mut dbtx = client.db().begin_transaction_nc().await;
3484            dbtx.get_next_event_log_id().await
3485        };
3486
3487        let mut start_position = end_position.saturating_sub(BATCH_SIZE);
3488
3489        let mut payment_log = Vec::new();
3490
3491        while payment_log.len() < pagination_size {
3492            let batch = client.get_event_log(Some(start_position), BATCH_SIZE).await;
3493            let mut filtered_batch = batch
3494                .into_iter()
3495                .filter(|e| e.id() <= end_position && event_kinds.contains(&e.as_raw().kind))
3496                .collect::<Vec<_>>();
3497            filtered_batch.reverse();
3498            payment_log.extend(filtered_batch);
3499
3500            // Compute the start position for the next batch query
3501            start_position = start_position.saturating_sub(BATCH_SIZE);
3502
3503            if start_position == EventLogId::LOG_START {
3504                break;
3505            }
3506        }
3507
3508        // Truncate the payment log to the expected pagination size
3509        payment_log.truncate(pagination_size);
3510
3511        Ok(PaymentLogResponse(payment_log))
3512    }
3513
3514    /// Set the gateway's root mnemonic by generating a new one or using the
3515    /// words provided in `SetMnemonicPayload`.
3516    async fn handle_set_mnemonic_msg(&self, payload: SetMnemonicPayload) -> AdminResult<()> {
3517        // The state lock must be held from the `NotConfigured` check until the
3518        // transition to `Disconnected`, otherwise a concurrent call could pass
3519        // the check, lose the race for the seed write, and leave the gateway
3520        // stuck in `NotConfigured` with a seed already stored
3521        let mut state_guard = self.state.write().await;
3522
3523        // Verify the state is NotConfigured
3524        let GatewayState::NotConfigured { mnemonic_sender } = state_guard.clone() else {
3525            return Err(AdminGatewayError::MnemonicError(anyhow!(
3526                "Gateway is not is NotConfigured state"
3527            )));
3528        };
3529
3530        let (mnemonic, mnemonic_source) = if let Some(words) = payload.words {
3531            info!(target: LOG_GATEWAY, "Using user provided mnemonic");
3532            let mnemonic = Mnemonic::parse_in_normalized(Language::English, words.as_str())
3533                .map_err(|e| {
3534                    AdminGatewayError::MnemonicError(anyhow!(format!(
3535                        "Seed phrase provided in environment was invalid {e:?}"
3536                    )))
3537                })?;
3538            (mnemonic, MnemonicSource::Existing)
3539        } else {
3540            debug!(target: LOG_GATEWAY, "Generating mnemonic and writing entropy to client storage");
3541            (
3542                Bip39RootSecretStrategy::<12>::random(&mut OsRng),
3543                MnemonicSource::Generated,
3544            )
3545        };
3546
3547        Client::store_encodable_client_secret(&self.gateway_db, mnemonic.to_entropy())
3548            .await
3549            .map_err(|err| AdminGatewayError::MnemonicError(err.into()))?;
3550
3551        *state_guard = GatewayState::Disconnected;
3552        drop(state_guard);
3553
3554        // Alert the gateway background threads that the mnemonic has been set
3555        let _ = mnemonic_sender.send(mnemonic_source);
3556
3557        Ok(())
3558    }
3559
3560    /// Creates a BOLT12 offer using the gateway's lightning node
3561    async fn handle_create_offer_for_operator_msg(
3562        &self,
3563        payload: CreateOfferPayload,
3564    ) -> AdminResult<CreateOfferResponse> {
3565        let lightning_context = self.get_lightning_context().await?;
3566        let offer = lightning_context.lnrpc.create_offer(
3567            payload.amount,
3568            payload.description,
3569            payload.expiry_secs,
3570            payload.quantity,
3571        )?;
3572        Ok(CreateOfferResponse { offer })
3573    }
3574
3575    /// Pays a BOLT12 offer using the gateway's lightning node
3576    async fn handle_pay_offer_for_operator_msg(
3577        &self,
3578        payload: PayOfferPayload,
3579    ) -> AdminResult<PayOfferResponse> {
3580        let lightning_context = self.get_lightning_context().await?;
3581        let preimage = lightning_context
3582            .lnrpc
3583            .pay_offer(
3584                payload.offer,
3585                payload.quantity,
3586                payload.amount,
3587                payload.payer_note,
3588            )
3589            .await?;
3590        Ok(PayOfferResponse {
3591            preimage: preimage.to_string(),
3592        })
3593    }
3594
3595    /// Returns a `BTreeMap` that is keyed by the `FederationId` and contains
3596    /// all the invite codes (with peer names) for the federation.
3597    async fn handle_export_invite_codes(
3598        &self,
3599    ) -> BTreeMap<FederationId, BTreeMap<PeerId, (String, InviteCode)>> {
3600        let fed_manager = self.federation_manager.read().await;
3601        fed_manager.all_invite_codes().await
3602    }
3603
3604    /// Returns `TieredCounts` which describes the breakdown of notes in the
3605    /// gateway's wallet for the given `FederationId`
3606    async fn handle_get_note_summary_msg(
3607        &self,
3608        federation_id: &FederationId,
3609    ) -> AdminResult<TieredCounts> {
3610        let fed_manager = self.federation_manager.read().await;
3611        fed_manager.get_note_summary(federation_id).await
3612    }
3613
3614    fn get_password_hash(&self) -> String {
3615        self.bcrypt_password_hash.clone()
3616    }
3617
3618    fn gatewayd_version(&self) -> String {
3619        let gatewayd_version = env!("CARGO_PKG_VERSION");
3620        gatewayd_version.to_string()
3621    }
3622
3623    async fn get_chain_source(&self) -> (ChainSource, Network) {
3624        (self.chain_source.clone(), self.network)
3625    }
3626
3627    fn lightning_mode(&self) -> LightningMode {
3628        self.lightning_mode.clone()
3629    }
3630
3631    async fn is_configured(&self) -> bool {
3632        !matches!(self.get_state().await, GatewayState::NotConfigured { .. })
3633    }
3634}
3635
3636// LNv2 Gateway implementation
3637impl Gateway {
3638    /// Retrieves the `PublicKey` of the Gateway module for a given federation
3639    /// for LNv2. This is NOT the same as the `gateway_id`, it is different
3640    /// per-connected federation.
3641    async fn public_key_v2(&self, federation_id: &FederationId) -> Option<PublicKey> {
3642        self.federation_manager
3643            .read()
3644            .await
3645            .client(federation_id)
3646            .and_then(|client| {
3647                // A federation only has to offer one of the two lightning modules, so a
3648                // client we serve over LNv1 may well have no LNv2 module at all.
3649                client
3650                    .value()
3651                    .get_first_module::<GatewayClientModuleV2>()
3652                    .ok()
3653                    .map(|module| module.keypair.public_key())
3654            })
3655    }
3656
3657    /// Whether the gateway currently accepts incoming payments on behalf of
3658    /// the clients of `federation_id`, as set with `set_payment_policy`. A
3659    /// federation without a stored config is treated as accepting them, so the
3660    /// check never turns a missing record into a refused payment.
3661    async fn receive_enabled(&self, federation_id: FederationId) -> bool {
3662        self.gateway_db
3663            .begin_transaction_nc()
3664            .await
3665            .load_federation_config(federation_id)
3666            .await
3667            .is_none_or(|config| config.receive_enabled())
3668    }
3669
3670    /// Admits a fresh incoming payment when the receive policy allows it,
3671    /// returning a guard that holds off a policy change until the caller has
3672    /// funded the payment.
3673    async fn admit_fresh_receive(&self, federation_id: FederationId) -> Option<PaymentPolicyGuard> {
3674        // The policy is read under the guard, so it cannot change between this
3675        // read and the funding the caller performs while holding it.
3676        let guard = self.payment_policy_lock.clone().read_owned().await;
3677
3678        self.receive_enabled(federation_id)
3679            .await
3680            .then(|| PaymentPolicyGuard::new(guard))
3681    }
3682
3683    /// Returns payment information that LNv2 clients can use to instruct this
3684    /// Gateway to pay an invoice or receive a payment.
3685    pub async fn routing_info_v2(
3686        &self,
3687        federation_id: &FederationId,
3688    ) -> Result<Option<RoutingInfo>> {
3689        let context = self.get_lightning_context().await?;
3690
3691        let mut dbtx = self.gateway_db.begin_transaction_nc().await;
3692        let fed_config = dbtx.load_federation_config(*federation_id).await.ok_or(
3693            PublicGatewayError::FederationNotConnected(FederationNotConnected {
3694                federation_id_prefix: federation_id.to_prefix(),
3695            }),
3696        )?;
3697
3698        let lightning_fee = fed_config.lightning_fee;
3699        let transaction_fee = fed_config.transaction_fee;
3700        let receive_enabled = fed_config.receive_enabled();
3701
3702        // This route is public and unauthenticated, so the sum of two fees stored
3703        // before the fee limits applied must not be able to panic here.
3704        let send_fee_default = lightning_fee.checked_add(transaction_fee).ok_or_else(|| {
3705            PublicGatewayError::Unexpected(anyhow!(
3706                "The configured fees of federation {federation_id} cannot be added"
3707            ))
3708        })?;
3709
3710        Ok(self
3711            .public_key_v2(federation_id)
3712            .await
3713            .map(|module_public_key| RoutingInfo {
3714                lightning_public_key: context.lightning_public_key,
3715                lightning_alias: Some(context.lightning_alias.clone()),
3716                module_public_key,
3717                send_fee_default,
3718                // The base fee ensures that the gateway does not loose sats sending the payment due
3719                // to fees paid on the transaction claiming the outgoing contract or
3720                // subsequent transactions spending the newly issued ecash
3721                send_fee_minimum: transaction_fee,
3722                expiration_delta_default: 1440,
3723                expiration_delta_minimum: EXPIRATION_DELTA_MINIMUM_V2,
3724                // The base fee ensures that the gateway does not loose sats receiving the payment
3725                // due to fees paid on the transaction funding the incoming contract
3726                receive_fee: transaction_fee,
3727                receive_enabled,
3728            }))
3729    }
3730
3731    /// Instructs this gateway to pay a Lightning network invoice via the LNv2
3732    /// protocol.
3733    pub async fn send_payment_v2(
3734        &self,
3735        payload: SendPaymentPayload,
3736    ) -> Result<std::result::Result<[u8; 32], Signature>> {
3737        let client = self.select_client(payload.federation_id).await?;
3738        // A federation only has to offer one of the two lightning modules, so a
3739        // client we serve over LNv1 may well have no LNv2 module at all.
3740        let module = client
3741            .value()
3742            .get_first_module::<GatewayClientModuleV2>()
3743            .map_err(|err| PublicGatewayError::LNv2(LNv2Error::OutgoingPayment(err.into())))?;
3744
3745        module
3746            .send_payment(payload)
3747            .await
3748            .map_err(|err| LNv2Error::OutgoingPayment(err.into()))
3749            .map_err(PublicGatewayError::LNv2)
3750    }
3751
3752    /// For the LNv2 protocol, this will create an invoice by fetching it from
3753    /// the connected Lightning node, then save the payment hash so that
3754    /// incoming lightning payments can be matched as a receive attempt to a
3755    /// specific federation.
3756    pub async fn create_bolt11_invoice_v2(
3757        &self,
3758        payload: CreateBolt11InvoicePayload,
3759    ) -> Result<Bolt11Invoice> {
3760        // Unauthenticated invoice creation consumes resources on the Lightning
3761        // node and burns CPU on contract verification, so the request rate is
3762        // limited before any other work is done.
3763        if !self.invoice_rate_limiter.try_acquire() {
3764            return Err(PublicGatewayError::RateLimited);
3765        }
3766
3767        // Verifying the contract is two pairings; keep them off the async workers.
3768        let contract = payload.contract.clone();
3769
3770        if !fedimint_core::runtime::spawn_blocking(move || contract.verify()).await {
3771            return Err(PublicGatewayError::LNv2(LNv2Error::IncomingPayment(
3772                "The contract is invalid".to_string(),
3773            )));
3774        }
3775
3776        let payment_info = self.routing_info_v2(&payload.federation_id).await?.ok_or(
3777            LNv2Error::IncomingPayment(format!(
3778                "Federation {} does not exist",
3779                payload.federation_id
3780            )),
3781        )?;
3782
3783        if !payment_info.receive_enabled {
3784            return Err(PublicGatewayError::ReceiveDisabled {
3785                federation_id_prefix: payload.federation_id.to_prefix(),
3786            });
3787        }
3788
3789        if payload.contract.commitment.refund_pk != payment_info.module_public_key {
3790            return Err(PublicGatewayError::LNv2(LNv2Error::IncomingPayment(
3791                "The incoming contract is keyed to another gateway".to_string(),
3792            )));
3793        }
3794
3795        let contract_amount = payment_info.receive_fee.subtract_from(payload.amount.msats);
3796
3797        if contract_amount == Amount::ZERO {
3798            return Err(PublicGatewayError::LNv2(LNv2Error::IncomingPayment(
3799                "Zero amount incoming contracts are not supported".to_string(),
3800            )));
3801        }
3802
3803        if contract_amount != payload.contract.commitment.amount {
3804            return Err(PublicGatewayError::LNv2(LNv2Error::IncomingPayment(
3805                "The contract amount does not pay the correct amount of fees".to_string(),
3806            )));
3807        }
3808
3809        if payload.contract.commitment.expiration_or_fee <= duration_since_epoch().as_secs() {
3810            return Err(PublicGatewayError::LNv2(LNv2Error::IncomingPayment(
3811                "The contract has already expired".to_string(),
3812            )));
3813        }
3814
3815        if payload.expiry_secs > MAX_INVOICE_EXPIRY_SECS {
3816            return Err(PublicGatewayError::LNv2(LNv2Error::IncomingPayment(
3817                "The invoice expiry exceeds the maximum of one day".to_string(),
3818            )));
3819        }
3820
3821        let payment_hash = match payload.contract.commitment.payment_image {
3822            PaymentImage::Hash(payment_hash) => payment_hash,
3823            PaymentImage::Point(..) => {
3824                return Err(PublicGatewayError::LNv2(LNv2Error::IncomingPayment(
3825                    "PaymentImage is not a payment hash".to_string(),
3826                )));
3827            }
3828        };
3829
3830        // Reserve the payment hash in the database before requesting the
3831        // invoice so a replayed payment hash is rejected without creating any
3832        // state on the Lightning node, and so the contract is guaranteed to be
3833        // registered by the time the invoice is payable.
3834        let mut dbtx = self.gateway_db.begin_transaction().await;
3835
3836        let invoice_expires_at_secs = duration_since_epoch()
3837            .as_secs()
3838            .saturating_add(u64::from(payload.expiry_secs));
3839
3840        if dbtx
3841            .save_registered_incoming_contract(
3842                payload.federation_id,
3843                payload.amount,
3844                invoice_expires_at_secs,
3845                payload.contract,
3846            )
3847            .await
3848            .is_some()
3849        {
3850            return Err(PublicGatewayError::LNv2(LNv2Error::IncomingPayment(
3851                "PaymentHash is already registered".to_string(),
3852            )));
3853        }
3854
3855        dbtx.commit_tx_result().await.map_err(|_| {
3856            PublicGatewayError::LNv2(LNv2Error::IncomingPayment(
3857                "Payment hash is already registered".to_string(),
3858            ))
3859        })?;
3860
3861        match self
3862            .create_invoice_via_lnrpc_v2(
3863                payment_hash,
3864                payload.amount,
3865                payload.description.clone(),
3866                payload.expiry_secs,
3867            )
3868            .await
3869        {
3870            Ok(invoice) => Ok(invoice),
3871            Err(err) => {
3872                // Release the reservation so the payment hash is not burned by
3873                // a transient Lightning node failure.
3874                let mut dbtx = self.gateway_db.begin_transaction().await;
3875                dbtx.delete_registered_incoming_contract(PaymentImage::Hash(payment_hash))
3876                    .await;
3877                if let Err(db_err) = dbtx.commit_tx_result().await {
3878                    warn!(
3879                        target: LOG_GATEWAY,
3880                        err = %db_err.fmt_compact(),
3881                        %payment_hash,
3882                        "Failed to release incoming contract reservation after Lightning error"
3883                    );
3884                }
3885
3886                Err(err.into())
3887            }
3888        }
3889    }
3890
3891    /// Retrieves a BOLT11 invoice from the connected Lightning node with a
3892    /// specific `payment_hash`.
3893    pub async fn create_invoice_via_lnrpc_v2(
3894        &self,
3895        payment_hash: sha256::Hash,
3896        amount: Amount,
3897        description: Bolt11InvoiceDescription,
3898        expiry_time: u32,
3899    ) -> std::result::Result<Bolt11Invoice, LightningRpcError> {
3900        let lnrpc = self.get_lightning_context().await?.lnrpc;
3901
3902        let response = match description {
3903            Bolt11InvoiceDescription::Direct(description) => {
3904                lnrpc
3905                    .create_invoice(CreateInvoiceRequest {
3906                        payment_hash: Some(payment_hash),
3907                        amount_msat: amount.msats,
3908                        expiry_secs: expiry_time,
3909                        description: Some(InvoiceDescription::Direct(description)),
3910                    })
3911                    .await?
3912            }
3913            Bolt11InvoiceDescription::Hash(hash) => {
3914                lnrpc
3915                    .create_invoice(CreateInvoiceRequest {
3916                        payment_hash: Some(payment_hash),
3917                        amount_msat: amount.msats,
3918                        expiry_secs: expiry_time,
3919                        description: Some(InvoiceDescription::Hash(hash)),
3920                    })
3921                    .await?
3922            }
3923        };
3924
3925        Bolt11Invoice::from_str(&response.invoice).map_err(|e| {
3926            LightningRpcError::FailedToGetInvoice {
3927                failure_reason: e.to_string(),
3928            }
3929        })
3930    }
3931
3932    pub async fn verify_bolt11_preimage_v2(
3933        &self,
3934        payment_hash: sha256::Hash,
3935        wait: bool,
3936    ) -> std::result::Result<VerifyResponse, String> {
3937        let registered_contract = self
3938            .gateway_db
3939            .begin_transaction_nc()
3940            .await
3941            .load_registered_incoming_contract(PaymentImage::Hash(payment_hash))
3942            .await
3943            .ok_or("Unknown payment hash".to_string())?;
3944
3945        let client = self
3946            .select_client(registered_contract.federation_id)
3947            .await
3948            .map_err(|_| "Not connected to federation".to_string())?
3949            .into_value();
3950
3951        let operation_id = OperationId::from_encodable(&registered_contract.contract);
3952
3953        if !(wait || client.operation_exists(operation_id).await) {
3954            return Ok(VerifyResponse::pending());
3955        }
3956
3957        let module = client
3958            .get_first_module::<GatewayClientModuleV2>()
3959            .expect("Must have client module");
3960
3961        let Ok(state) = timeout(VERIFY_WAIT_TIMEOUT, module.await_receive(operation_id)).await
3962        else {
3963            return Ok(VerifyResponse::pending());
3964        };
3965
3966        let preimage = match state {
3967            FinalReceiveState::Success(preimage) => Ok(preimage),
3968            FinalReceiveState::Failure => Err("Payment has failed".to_string()),
3969            FinalReceiveState::Refunded => Err("Payment has been refunded".to_string()),
3970            FinalReceiveState::Rejected => Err("Payment has been rejected".to_string()),
3971        }?;
3972
3973        Ok(VerifyResponse::settled(preimage))
3974    }
3975
3976    /// Retrieves the persisted `CreateInvoicePayload` from the database
3977    /// specified by the `payment_hash` and the `ClientHandleArc` specified
3978    /// by the payload's `federation_id`.
3979    pub async fn get_registered_incoming_contract_and_client_v2(
3980        &self,
3981        payment_image: PaymentImage,
3982        amount_msats: u64,
3983    ) -> Result<(IncomingContract, ClientHandleArc)> {
3984        let registered_incoming_contract = self
3985            .gateway_db
3986            .begin_transaction_nc()
3987            .await
3988            .load_registered_incoming_contract(payment_image)
3989            .await
3990            .ok_or(PublicGatewayError::LNv2(LNv2Error::IncomingPayment(
3991                "No corresponding decryption contract available".to_string(),
3992            )))?;
3993
3994        if registered_incoming_contract.incoming_amount_msats != amount_msats {
3995            return Err(PublicGatewayError::LNv2(
3996                LNv2Error::IncomingAmountMismatch {
3997                    registered_msats: registered_incoming_contract.incoming_amount_msats,
3998                    payment_msats: amount_msats,
3999                },
4000            ));
4001        }
4002
4003        let client = self
4004            .select_client(registered_incoming_contract.federation_id)
4005            .await?
4006            .into_value();
4007
4008        Ok((registered_incoming_contract.contract, client))
4009    }
4010
4011    /// Completes (settles or cancels) an intercepted HTLC, retrying transient
4012    /// failures until Lightning reports a terminal outcome.
4013    ///
4014    /// Serves [`IGatewayClientV1::complete_htlc`] and
4015    /// [`IGatewayClientV2::complete_htlc`]: by now the incoming contract is
4016    /// funded, so giving up on a transient failure would strand it. Only
4017    /// [`LightningRpcError::HtlcCompletionRejected`], a permanent state, is
4018    /// returned to the caller.
4019    async fn await_complete_htlc(
4020        &self,
4021        htlc: InterceptPaymentResponse,
4022    ) -> std::result::Result<(), LightningRpcError> {
4023        loop {
4024            let lightning_context = self.await_lightning_context().await;
4025
4026            match lightning_context.lnrpc.complete_htlc(htlc.clone()).await {
4027                Ok(()) => return Ok(()),
4028                Err(err @ LightningRpcError::HtlcCompletionRejected { .. }) => {
4029                    warn!(
4030                        target: LOG_GATEWAY,
4031                        err = %err.fmt_compact(),
4032                        "Lightning cannot reach the requested terminal HTLC outcome",
4033                    );
4034                    return Err(err);
4035                }
4036                Err(err) => {
4037                    warn!(
4038                        target: LOG_GATEWAY,
4039                        err = %err.fmt_compact(),
4040                        "Failure trying to complete HTLC, retrying",
4041                    );
4042                }
4043            }
4044
4045            sleep(LIGHTNING_CONTEXT_RETRY_INTERVAL).await;
4046        }
4047    }
4048
4049    /// Answers whether the connected Lightning node has any record of an
4050    /// outbound payment for `payment_hash`, retrying transient lookup
4051    /// failures until the node itself can answer.
4052    ///
4053    /// Serves [`IGatewayClientV1::outbound_payment_exists`] and
4054    /// [`IGatewayClientV2::outbound_payment_exists`]: a wrong `false` lets a
4055    /// resumed state machine cancel a contract whose payment is still in
4056    /// flight, so no answer is synthesised from a failure.
4057    async fn await_outbound_payment_exists(&self, payment_hash: sha256::Hash) -> bool {
4058        loop {
4059            let lightning_context = self.await_lightning_context().await;
4060
4061            match lightning_context
4062                .lnrpc
4063                .outbound_payment_exists(payment_hash)
4064                .await
4065            {
4066                Ok(exists) => return exists,
4067                Err(err) => {
4068                    warn!(
4069                        target: LOG_GATEWAY,
4070                        err = %err.fmt_compact(),
4071                        %payment_hash,
4072                        "Failed to check for a dispatched payment, retrying",
4073                    );
4074                }
4075            }
4076
4077            sleep(LIGHTNING_CONTEXT_RETRY_INTERVAL).await;
4078        }
4079    }
4080}
4081
4082#[async_trait]
4083impl IGatewayClientV2 for Gateway {
4084    async fn complete_htlc(
4085        &self,
4086        htlc_response: InterceptPaymentResponse,
4087    ) -> std::result::Result<(), LightningRpcError> {
4088        self.await_complete_htlc(htlc_response).await
4089    }
4090
4091    async fn is_direct_swap(
4092        &self,
4093        invoice: &Bolt11Invoice,
4094    ) -> std::result::Result<Option<(IncomingContract, ClientHandleArc)>, GatewayClientV2Error>
4095    {
4096        // Deciding this from a locally synthesised "not connected" would route a
4097        // direct swap onto the lightning network, or -- once the send state
4098        // machine turns the error into a cancellation -- forfeit a contract we
4099        // may already be committed to. Ask once we can actually answer.
4100        let lightning_context = self.await_lightning_context().await;
4101        if lightning_context.lightning_public_key == invoice.get_payee_pub_key() {
4102            let (contract, client) = self
4103                .get_registered_incoming_contract_and_client_v2(
4104                    PaymentImage::Hash(*invoice.payment_hash()),
4105                    invoice
4106                        .amount_milli_satoshis()
4107                        .expect("The amount invoice has been previously checked"),
4108                )
4109                .await
4110                .map_err(GatewayClientV2Error::new)?;
4111            Ok(Some((contract, client)))
4112        } else {
4113            Ok(None)
4114        }
4115    }
4116
4117    async fn pay(
4118        &self,
4119        invoice: Bolt11Invoice,
4120        max_delay: u64,
4121        max_fee: Amount,
4122    ) -> std::result::Result<[u8; 32], LightningRpcError> {
4123        // The send state machine forfeits the outgoing contract on any error from
4124        // here, so only the lightning node gets to say this payment failed.
4125        let lightning_context = self.await_lightning_context().await;
4126        lightning_context
4127            .lnrpc
4128            .pay(invoice, max_delay, max_fee)
4129            .await
4130            .map(|response| response.preimage.0)
4131    }
4132
4133    async fn outbound_payment_exists(&self, payment_hash: sha256::Hash) -> bool {
4134        self.await_outbound_payment_exists(payment_hash).await
4135    }
4136
4137    async fn begin_fresh_receive(
4138        &self,
4139        federation_id: &FederationId,
4140    ) -> Option<PaymentPolicyGuard> {
4141        self.admit_fresh_receive(*federation_id).await
4142    }
4143
4144    async fn min_contract_amount(
4145        &self,
4146        federation_id: &FederationId,
4147        amount: u64,
4148    ) -> std::result::Result<Amount, GatewayClientV2Error> {
4149        Ok(self
4150            .routing_info_v2(federation_id)
4151            .await
4152            .map_err(GatewayClientV2Error::new)?
4153            .ok_or_else(|| GatewayClientV2Error::new("Routing Info not available"))?
4154            .send_fee_minimum
4155            .add_to(amount))
4156    }
4157
4158    async fn is_lnv1_invoice(&self, invoice: &Bolt11Invoice) -> Option<Spanned<ClientHandleArc>> {
4159        let rhints = invoice.route_hints();
4160        let hop = rhints.first().and_then(|rh| rh.0.last())?;
4161
4162        // Answering `None` because we happen to be between lightning connections
4163        // sends a swap that never needed the lightning network out over it.
4164        let lightning_context = self.await_lightning_context().await;
4165        if hop.src_node_id != lightning_context.lightning_public_key {
4166            return None;
4167        }
4168
4169        self.federation_manager
4170            .read()
4171            .await
4172            .get_client_for_index(hop.short_channel_id)
4173    }
4174
4175    async fn relay_lnv1_swap(
4176        &self,
4177        client: &ClientHandleArc,
4178        invoice: &Bolt11Invoice,
4179        allow_fresh_dispatch: bool,
4180    ) -> std::result::Result<Option<FinalReceiveState>, GatewayClientV2Error> {
4181        let swap_params =
4182            SwapParameters {
4183                payment_hash: *invoice.payment_hash(),
4184                amount_msat: Amount::from_msats(invoice.amount_milli_satoshis().ok_or_else(
4185                    || GatewayClientV2Error::new("Amountless invoice not supported"),
4186                )?),
4187            };
4188        // Nothing has been paid out yet, so failing here only cancels the send.
4189        let lnv1 = client
4190            .get_first_module::<GatewayClientModule>()
4191            .map_err(|_| GatewayClientV2Error::new("Federation does not have an LNv1 module"))?;
4192        let Some(operation_id) = lnv1
4193            .gateway_handle_direct_swap(swap_params, allow_fresh_dispatch)
4194            .await
4195            .map_err(GatewayClientV2Error::new)?
4196        else {
4197            return Ok(None);
4198        };
4199        let mut stream = lnv1
4200            .gateway_subscribe_ln_receive(operation_id)
4201            .await
4202            .map_err(GatewayClientV2Error::new)?
4203            .into_stream();
4204        let mut final_state = FinalReceiveState::Failure;
4205        while let Some(update) = stream.next().await {
4206            match update {
4207                GatewayExtReceiveStates::Funding => {}
4208                GatewayExtReceiveStates::FundingFailed { error: _ } => {
4209                    final_state = FinalReceiveState::Rejected;
4210                }
4211                GatewayExtReceiveStates::Preimage(preimage) => {
4212                    final_state = FinalReceiveState::Success(preimage.0);
4213                }
4214                GatewayExtReceiveStates::RefundError {
4215                    error_message: _,
4216                    error: _,
4217                } => {
4218                    final_state = FinalReceiveState::Failure;
4219                }
4220                GatewayExtReceiveStates::RefundSuccess {
4221                    out_points: _,
4222                    error: _,
4223                } => {
4224                    final_state = FinalReceiveState::Refunded;
4225                }
4226            }
4227        }
4228
4229        Ok(Some(final_state))
4230    }
4231
4232    async fn claim_payment_image(
4233        &self,
4234        payment_image: &PaymentImage,
4235        operation_id: OperationId,
4236    ) -> bool {
4237        // `autocommit` retries on write-write conflicts, so concurrent claims for
4238        // the same payment image are serialized: exactly one records itself as the
4239        // claimer, the rest observe it and forfeit.
4240        self.gateway_db
4241            .autocommit(
4242                |dbtx, _| {
4243                    let payment_image = payment_image.clone();
4244                    Box::pin(async move {
4245                        let claimer = dbtx
4246                            .claim_outgoing_payment_image(payment_image, operation_id)
4247                            .await;
4248                        Ok::<_, std::convert::Infallible>(claimer == operation_id)
4249                    })
4250                },
4251                None,
4252            )
4253            .await
4254            .expect("Retries until the transaction commits")
4255    }
4256
4257    async fn is_lightning_connected(&self) -> bool {
4258        self.get_lightning_context().await.is_ok()
4259    }
4260
4261    async fn await_lightning_connected(&self) {
4262        self.await_lightning_context().await;
4263    }
4264}
4265
4266#[async_trait]
4267impl IGatewayClientV1 for Gateway {
4268    async fn claim_payment_image(
4269        &self,
4270        payment_image: &PaymentImage,
4271        operation_id: OperationId,
4272    ) -> bool {
4273        IGatewayClientV2::claim_payment_image(self, payment_image, operation_id).await
4274    }
4275
4276    async fn verify_preimage_authentication(
4277        &self,
4278        payment_hash: sha256::Hash,
4279        preimage_auth: sha256::Hash,
4280        contract: OutgoingContractAccount,
4281    ) -> std::result::Result<(), OutgoingPaymentError> {
4282        let mut dbtx = self.gateway_db.begin_transaction().await;
4283        if let Some(secret_hash) = dbtx.load_preimage_authentication(payment_hash).await {
4284            if !PreimageAuth::new(secret_hash).verifies(preimage_auth) {
4285                return Err(OutgoingPaymentError {
4286                    error_type: OutgoingPaymentErrorType::InvalidInvoicePreimage,
4287                    contract_id: contract.contract.contract_id(),
4288                    contract: Some(contract),
4289                });
4290            }
4291        } else {
4292            // Committing the `preimage_auth` to the database can fail if two users try to
4293            // pay the same invoice at the same time.
4294            dbtx.save_new_preimage_authentication(payment_hash, preimage_auth)
4295                .await;
4296            return dbtx
4297                .commit_tx_result()
4298                .await
4299                .map_err(|_| OutgoingPaymentError {
4300                    error_type: OutgoingPaymentErrorType::InvoiceAlreadyPaid,
4301                    contract_id: contract.contract.contract_id(),
4302                    contract: Some(contract),
4303                });
4304        }
4305
4306        Ok(())
4307    }
4308
4309    async fn verify_pruned_invoice(
4310        &self,
4311        payment_data: PaymentData,
4312    ) -> std::result::Result<(), GatewayClientV1Error> {
4313        if matches!(payment_data, PaymentData::PrunedInvoice { .. }) {
4314            let lightning_context = self
4315                .get_lightning_context()
4316                .await
4317                .map_err(GatewayClientV1Error::new)?;
4318
4319            if !lightning_context.lnrpc.supports_private_payments() {
4320                return Err(GatewayClientV1Error::new(
4321                    "Private payments are not supported by the lightning node",
4322                ));
4323            }
4324        }
4325
4326        Ok(())
4327    }
4328
4329    async fn begin_fresh_receive(&self, federation_id: FederationId) -> Option<PaymentPolicyGuard> {
4330        self.admit_fresh_receive(federation_id).await
4331    }
4332
4333    async fn get_routing_fees(&self, federation_id: FederationId) -> Option<RoutingFees> {
4334        let mut gateway_dbtx = self.gateway_db.begin_transaction_nc().await;
4335        let lightning_fee = gateway_dbtx
4336            .load_federation_config(federation_id)
4337            .await?
4338            .lightning_fee;
4339
4340        // A fee stored before the fee limits applied may not be announceable. The
4341        // caller treats `None` as a federation configuration error, which is
4342        // preferable to panicking in the middle of a payment.
4343        RoutingFees::try_from(lightning_fee)
4344            .inspect_err(|err| {
4345                warn!(
4346                    target: LOG_GATEWAY,
4347                    %federation_id,
4348                    err = %err.fmt_compact(),
4349                    "Configured lightning fee cannot be used. Set a smaller fee with `set_fees`."
4350                );
4351            })
4352            .ok()
4353    }
4354
4355    async fn get_client(&self, federation_id: &FederationId) -> Option<Spanned<ClientHandleArc>> {
4356        self.federation_manager
4357            .read()
4358            .await
4359            .client(federation_id)
4360            .cloned()
4361    }
4362
4363    async fn get_client_for_invoice(
4364        &self,
4365        payment_data: PaymentData,
4366    ) -> Option<Spanned<ClientHandleArc>> {
4367        let rhints = payment_data.route_hints();
4368        let hop = rhints.first().and_then(|rh| rh.0.last())?;
4369
4370        // Answering `None` because we happen to be between lightning connections
4371        // sends a swap that never needed the lightning network out over it.
4372        let lightning_context = self.await_lightning_context().await;
4373        if hop.src_node_id != lightning_context.lightning_public_key {
4374            return None;
4375        }
4376
4377        self.federation_manager
4378            .read()
4379            .await
4380            .get_client_for_index(hop.short_channel_id)
4381    }
4382
4383    async fn pay(
4384        &self,
4385        payment_data: PaymentData,
4386        max_delay: u64,
4387        max_fee: Amount,
4388    ) -> std::result::Result<PayInvoiceResponse, LightningRpcError> {
4389        // `GatewayPayInvoice` cancels the outgoing contract on any error from
4390        // here, so only the lightning node gets to say this payment failed.
4391        let lightning_context = self.await_lightning_context().await;
4392
4393        match payment_data {
4394            PaymentData::Invoice(invoice) => {
4395                lightning_context
4396                    .lnrpc
4397                    .pay(invoice, max_delay, max_fee)
4398                    .await
4399            }
4400            PaymentData::PrunedInvoice(invoice) => {
4401                lightning_context
4402                    .lnrpc
4403                    .pay_private(invoice, max_delay, max_fee)
4404                    .await
4405            }
4406        }
4407    }
4408
4409    async fn outbound_payment_exists(&self, payment_hash: sha256::Hash) -> bool {
4410        self.await_outbound_payment_exists(payment_hash).await
4411    }
4412
4413    async fn complete_htlc(
4414        &self,
4415        htlc: InterceptPaymentResponse,
4416    ) -> std::result::Result<(), LightningRpcError> {
4417        self.await_complete_htlc(htlc).await
4418    }
4419
4420    async fn is_lnv2_direct_swap(
4421        &self,
4422        payment_hash: sha256::Hash,
4423        amount: Amount,
4424    ) -> std::result::Result<
4425        Option<(
4426            fedimint_lnv2_common::contracts::IncomingContract,
4427            ClientHandleArc,
4428        )>,
4429        GatewayClientV1Error,
4430    > {
4431        let (contract, client) = self
4432            .get_registered_incoming_contract_and_client_v2(
4433                PaymentImage::Hash(payment_hash),
4434                amount.msats,
4435            )
4436            .await
4437            .map_err(GatewayClientV1Error::new)?;
4438        Ok(Some((contract, client)))
4439    }
4440}