Skip to main content

fedimint_gateway_common/
lib.rs

1use std::collections::{BTreeMap, BTreeSet};
2use std::fmt;
3use std::str::FromStr;
4use std::time::{Duration, SystemTime};
5
6use bitcoin::address::NetworkUnchecked;
7use bitcoin::hashes::sha256;
8use bitcoin::secp256k1::PublicKey;
9use bitcoin::{Address, Network, OutPoint};
10use clap::Subcommand;
11use envs::{
12    FM_LDK_ALIAS_ENV, FM_LND_MACAROON_ENV, FM_LND_PAYMENT_TIMEOUT_SECS_ENV, FM_LND_RPC_ADDR_ENV,
13    FM_LND_TIME_PREF_ENV, FM_LND_TLS_CERT_ENV, FM_PORT_LDK,
14};
15use fedimint_core::config::{FederationId, JsonClientConfig};
16use fedimint_core::encoding::{Decodable, Encodable};
17use fedimint_core::invite_code::InviteCode;
18use fedimint_core::util::{SafeUrl, get_average, get_median};
19use fedimint_core::{Amount, BitcoinAmountOrAll, secp256k1};
20use fedimint_eventlog::{EventKind, EventLogId, PersistedLogEntry, StructuredPaymentEvents};
21use fedimint_lnv2_common::gateway_api::PaymentFee;
22use fedimint_wallet_client::PegOutFees;
23use lightning::ln::msgs::SocketAddress;
24use lightning_invoice::Bolt11Invoice;
25use serde::de::Error as _;
26use serde::{Deserialize, Deserializer, Serialize, Serializer};
27
28pub mod envs;
29pub mod federation_status;
30
31pub use federation_status::*;
32
33pub const V1_API_ENDPOINT: &str = "v1";
34
35pub const ADDRESS_ENDPOINT: &str = "/address";
36pub const ADDRESS_RECHECK_ENDPOINT: &str = "/address_recheck";
37pub const BACKUP_ENDPOINT: &str = "/backup";
38pub const CONFIGURATION_ENDPOINT: &str = "/config";
39pub const CONNECT_FED_ENDPOINT: &str = "/connect_fed";
40pub const CREATE_BOLT11_INVOICE_FOR_OPERATOR_ENDPOINT: &str = "/create_bolt11_invoice_for_operator";
41pub const CREATE_BOLT12_OFFER_FOR_OPERATOR_ENDPOINT: &str = "/create_bolt12_offer_for_operator";
42pub const FEDERATION_STATUS_ENDPOINT: &str = "/federation_status";
43pub const GATEWAY_INFO_ENDPOINT: &str = "/info";
44pub const INVITE_CODES_ENDPOINT: &str = "/invite_codes";
45pub const GET_BALANCES_ENDPOINT: &str = "/balances";
46pub const GET_INVOICE_ENDPOINT: &str = "/get_invoice";
47pub const GET_LN_ONCHAIN_ADDRESS_ENDPOINT: &str = "/get_ln_onchain_address";
48pub const LEAVE_FED_ENDPOINT: &str = "/leave_fed";
49pub const LIST_CHANNELS_ENDPOINT: &str = "/list_channels";
50pub const LIST_TRANSACTIONS_ENDPOINT: &str = "/list_transactions";
51pub const MNEMONIC_ENDPOINT: &str = "/mnemonic";
52pub const CONNECT_PEER_ENDPOINT: &str = "/connect_peer";
53pub const OPEN_CHANNEL_ENDPOINT: &str = "/open_channel";
54pub const OPEN_CHANNEL_WITH_PUSH_ENDPOINT: &str = "/open_channel_with_push";
55pub const CLOSE_CHANNELS_WITH_PEER_ENDPOINT: &str = "/close_channels_with_peer";
56pub const PAY_INVOICE_FOR_OPERATOR_ENDPOINT: &str = "/pay_invoice_for_operator";
57pub const PAY_OFFER_FOR_OPERATOR_ENDPOINT: &str = "/pay_offer_for_operator";
58pub const PAYMENT_LOG_ENDPOINT: &str = "/payment_log";
59pub const PAYMENT_SUMMARY_ENDPOINT: &str = "/payment_summary";
60pub const PEGIN_FROM_ONCHAIN_ENDPOINT: &str = "/pegin_from_onchain";
61pub const RECEIVE_ECASH_ENDPOINT: &str = "/receive_ecash";
62pub const SET_CHANNEL_FEES_ENDPOINT: &str = "/set_channel_fees";
63pub const SET_FEES_ENDPOINT: &str = "/set_fees";
64pub const SET_PAYMENT_POLICY_ENDPOINT: &str = "/set_payment_policy";
65pub const STOP_ENDPOINT: &str = "/stop";
66pub const SEND_ONCHAIN_ENDPOINT: &str = "/send_onchain";
67pub const SPEND_ECASH_ENDPOINT: &str = "/spend_ecash";
68pub const WITHDRAW_ENDPOINT: &str = "/withdraw";
69pub const WITHDRAW_TO_ONCHAIN_ENDPOINT: &str = "/withdraw_to_onchain";
70
71pub const DEFAULT_LIGHTNING_PORT: u16 = 9735;
72
73#[derive(Debug, Serialize, Deserialize, Clone)]
74pub struct ConnectFedPayload {
75    pub invite_code: String,
76    pub use_tor: Option<bool>,
77    pub recover: Option<bool>,
78}
79
80#[derive(Debug, Serialize, Deserialize, Clone)]
81pub struct LeaveFedPayload {
82    pub federation_id: FederationId,
83}
84
85#[derive(Debug, Serialize, Deserialize)]
86pub struct InfoPayload;
87
88#[derive(Debug, Serialize, Deserialize)]
89pub struct BackupPayload {
90    pub federation_id: FederationId,
91}
92
93#[derive(Debug, Serialize, Deserialize, Clone)]
94pub struct ConfigPayload {
95    pub federation_id: Option<FederationId>,
96}
97
98#[derive(Debug, Serialize, Deserialize, Clone)]
99pub struct DepositAddressPayload {
100    pub federation_id: FederationId,
101}
102
103#[derive(Debug, Serialize, Deserialize, Clone)]
104pub struct PeginFromOnchainPayload {
105    pub federation_id: FederationId,
106    pub amount: BitcoinAmountOrAll,
107    pub fee_rate_sats_per_vbyte: u64,
108}
109
110#[derive(Debug, Serialize, Deserialize, Clone)]
111pub struct DepositAddressRecheckPayload {
112    pub address: Address<NetworkUnchecked>,
113    pub federation_id: FederationId,
114}
115
116#[derive(Debug, Serialize, Deserialize, Clone)]
117pub struct WithdrawPayload {
118    pub federation_id: FederationId,
119    pub amount: BitcoinAmountOrAll,
120    pub address: Address<NetworkUnchecked>,
121    /// When provided (from UI preview flow), uses these quoted fees.
122    /// When None, fetches current fees from the wallet.
123    #[serde(default)]
124    pub quoted_fees: Option<PegOutFees>,
125}
126
127#[derive(Debug, Serialize, Deserialize, Clone)]
128pub struct WithdrawToOnchainPayload {
129    pub federation_id: FederationId,
130    pub amount: BitcoinAmountOrAll,
131}
132
133#[derive(Debug, Serialize, Deserialize, Clone)]
134pub struct WithdrawResponse {
135    pub txid: bitcoin::Txid,
136    pub fees: PegOutFees,
137}
138
139#[derive(Debug, Serialize, Deserialize, Clone)]
140pub struct WithdrawPreviewPayload {
141    pub federation_id: FederationId,
142    pub amount: BitcoinAmountOrAll,
143    pub address: Address<NetworkUnchecked>,
144}
145
146#[derive(Debug, Serialize, Deserialize, Clone)]
147pub struct WithdrawPreviewResponse {
148    pub withdraw_amount: Amount,
149    pub address: String,
150    pub peg_out_fees: PegOutFees,
151    pub total_cost: Amount,
152    /// Estimated federation fees (wallet output fee, mint input and change
153    /// fees, dust) on top of `peg_out_fees`. Always set when withdrawing all,
154    /// and for partial withdrawals on walletv2 federations.
155    #[serde(default)]
156    pub mint_fees: Option<Amount>,
157    /// True when `peg_out_fees` is a flat on-chain fee (walletv2) built via
158    /// `PegOutFees::from_amount`, so its fee rate and weight are not real.
159    #[serde(default)]
160    pub flat_peg_out_fee: bool,
161}
162
163/// Deprecated, unused, doesn't do anything
164///
165/// Only here for backward-compat reasons.
166#[allow(deprecated)]
167#[derive(Debug, Clone, Eq, PartialEq, Encodable, Decodable, Serialize, Deserialize)]
168pub enum ConnectorType {
169    Tcp,
170    Tor,
171}
172
173#[derive(Debug, Clone, Eq, PartialEq, Encodable, Decodable, Serialize, Deserialize)]
174pub struct FederationConfig {
175    pub invite_code: InviteCode,
176    // Unique integer identifier per-federation that is assigned when the gateways joins a
177    // federation.
178    #[serde(alias = "mint_channel_id")]
179    pub federation_index: u64,
180    pub lightning_fee: PaymentFee,
181    pub transaction_fee: PaymentFee,
182    /// Restrictions on the payments the gateway performs on behalf of this
183    /// federation's clients. Empty means every kind of payment is performed.
184    /// Changed with `set_payment_policy`.
185    ///
186    /// Gateways that predate this field do not send it and perform every kind
187    /// of payment, so it defaults to no restrictions when absent.
188    #[serde(default)]
189    pub payment_policies: BTreeSet<PaymentPolicy>,
190    #[allow(deprecated)] // only here for decoding backward-compat
191    pub _connector: ConnectorType,
192}
193
194impl FederationConfig {
195    /// Whether the gateway accepts incoming Lightning payments on behalf of
196    /// this federation's clients.
197    pub fn receive_enabled(&self) -> bool {
198        !self
199            .payment_policies
200            .contains(&PaymentPolicy::ReceivesDisabled)
201    }
202}
203
204/// A restriction on the payments the gateway performs on behalf of a
205/// federation's clients.
206#[derive(
207    Debug,
208    Clone,
209    Copy,
210    Eq,
211    PartialEq,
212    Ord,
213    PartialOrd,
214    Hash,
215    Encodable,
216    Decodable,
217    Serialize,
218    Deserialize,
219)]
220pub enum PaymentPolicy {
221    /// Do not accept incoming payments: refuse to create invoices, fail back
222    /// the payments of invoices that were already issued, and refuse swaps
223    /// into the federation.
224    ReceivesDisabled,
225}
226
227/// Held while the gateway funds a fresh incoming payment, so its payment
228/// policy cannot change between the check that admitted the payment and the
229/// operation that funds it.
230///
231/// Turning a policy off waits for every guard outstanding at that moment, so a
232/// payment admitted before the change always funds, and none is admitted after
233/// the change returns.
234#[derive(Debug)]
235pub struct PaymentPolicyGuard(#[allow(dead_code)] tokio::sync::OwnedRwLockReadGuard<()>);
236
237impl PaymentPolicyGuard {
238    pub fn new(guard: tokio::sync::OwnedRwLockReadGuard<()>) -> Self {
239        Self(guard)
240    }
241}
242
243/// Information about one of the feds we are connected to
244#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
245pub struct FederationInfo {
246    pub federation_id: FederationId,
247    pub federation_name: Option<String>,
248    pub balance_msat: Amount,
249    pub config: FederationConfig,
250    pub last_backup_time: Option<SystemTime>,
251}
252
253#[derive(Debug, Serialize, Deserialize, PartialEq)]
254pub struct GatewayInfo {
255    pub version_hash: String,
256    pub federations: Vec<FederationInfo>,
257    /// Mapping from short channel id to the federation id that it belongs to.
258    // TODO: Remove this alias once it no longer breaks backwards compatibility.
259    #[serde(alias = "channels")]
260    pub federation_fake_scids: Option<BTreeMap<u64, FederationId>>,
261    pub gateway_state: String,
262    pub lightning_info: LightningInfo,
263    pub lightning_mode: LightningMode,
264    pub registrations: BTreeMap<RegisteredProtocol, (SafeUrl, secp256k1::PublicKey)>,
265}
266
267#[derive(Debug, Serialize, Deserialize, PartialEq)]
268pub struct GatewayFedConfig {
269    pub federations: BTreeMap<FederationId, JsonClientConfig>,
270}
271
272#[derive(Debug, Serialize, Deserialize, Clone)]
273pub struct SetFeesPayload {
274    pub federation_id: Option<FederationId>,
275    pub lightning_base: Option<Amount>,
276    pub lightning_parts_per_million: Option<u64>,
277    pub transaction_base: Option<Amount>,
278    pub transaction_parts_per_million: Option<u64>,
279}
280
281/// Changes which payments the gateway performs on behalf of a federation's
282/// clients. Like `SetFeesPayload`, every setting is optional and only the ones
283/// present change, so further kinds of payments can be added later.
284#[derive(Debug, Serialize, Deserialize, Clone)]
285pub struct SetPaymentPolicyPayload {
286    /// The federation to change, or every connected federation when absent
287    pub federation_id: Option<FederationId>,
288    /// Whether to accept incoming Lightning payments for the federation's
289    /// clients. Turning this off refuses new invoices and fails back the
290    /// payments of invoices that were already issued.
291    pub receive_enabled: Option<bool>,
292}
293
294#[derive(Debug, Serialize, Deserialize, Clone)]
295pub struct CreateInvoiceForOperatorPayload {
296    pub amount_msats: u64,
297    pub expiry_secs: Option<u32>,
298    pub description: Option<String>,
299}
300
301#[derive(Debug, Serialize, Deserialize, Clone)]
302pub struct PayInvoiceForOperatorPayload {
303    pub invoice: Bolt11Invoice,
304}
305
306#[derive(Debug, Serialize, Deserialize, Clone)]
307pub struct SpendEcashPayload {
308    /// Federation id of the e-cash to spend
309    pub federation_id: FederationId,
310    /// The amount of e-cash to spend
311    pub amount: Amount,
312}
313
314#[derive(Debug, Serialize, Deserialize, Clone)]
315pub struct SpendEcashResponse {
316    /// OOBNotes.to_string() for v1, base32::encode_prefixed() for v2
317    pub notes: String,
318}
319
320#[derive(Debug, Serialize, Deserialize, Clone)]
321pub struct ReceiveEcashPayload {
322    /// Can be OOBNotes (v1) or ECash (v2)
323    pub notes: String,
324}
325
326#[derive(Debug, Serialize, Deserialize, Clone)]
327pub struct ReceiveEcashResponse {
328    pub amount: Amount,
329}
330
331#[derive(serde::Serialize, serde::Deserialize, Clone)]
332pub struct GatewayBalances {
333    pub onchain_balance_sats: u64,
334    /// The part of `onchain_balance_sats` that the gateway can send on-chain
335    /// now. The fee of a send also comes out of it, so it is not the largest
336    /// amount a recipient can receive. `None` from gateways that do not
337    /// report it.
338    #[serde(default)]
339    pub spendable_onchain_balance_sats: Option<u64>,
340    pub lightning_balance_msats: u64,
341    pub ecash_balances: Vec<FederationBalanceInfo>,
342    pub inbound_lightning_liquidity_msats: u64,
343}
344
345#[derive(serde::Serialize, serde::Deserialize, Clone)]
346pub struct FederationBalanceInfo {
347    pub federation_id: FederationId,
348    pub ecash_balance_msats: Amount,
349}
350
351#[derive(Debug, Serialize, Deserialize, Clone)]
352pub struct MnemonicResponse {
353    pub mnemonic: Vec<String>,
354
355    // Legacy federations are federations that the gateway joined prior to v0.5.0
356    // and do not derive their secrets from the gateway's mnemonic. They also use
357    // a separate database from the gateway's db.
358    pub legacy_federations: Vec<FederationId>,
359}
360
361#[derive(Debug, Serialize, Deserialize, Clone)]
362pub struct PaymentLogPayload {
363    // The position in the log to stop querying. No events will be returned from after
364    // this `EventLogId`. If it is `None`, the last `EventLogId` is used.
365    pub end_position: Option<EventLogId>,
366
367    // The number of events to return
368    pub pagination_size: usize,
369
370    pub federation_id: FederationId,
371
372    /// Filter to only return events of these kinds. If empty, defaults to
373    /// `ALL_GATEWAY_EVENTS` (gateway payment-related events only, not all
374    /// events in the log).
375    ///
376    /// Note: returned event IDs may be non-contiguous because other internal
377    /// events (e.g. `tx-created`, `NoteCreated`) share the same ID space but
378    /// are filtered out.
379    pub event_kinds: Vec<EventKind>,
380}
381
382#[derive(Debug, Serialize, Deserialize, Clone)]
383pub struct PaymentLogResponse(pub Vec<PersistedLogEntry>);
384
385#[derive(Debug, Serialize, Deserialize, Clone)]
386pub struct PaymentSummaryResponse {
387    pub outgoing: PaymentStats,
388    pub incoming: PaymentStats,
389}
390
391#[derive(Debug, Serialize, Deserialize, Clone)]
392pub struct PaymentStats {
393    pub average_latency: Option<Duration>,
394    pub median_latency: Option<Duration>,
395    pub total_fees: Amount,
396    pub total_success: usize,
397    pub total_failure: usize,
398}
399
400impl PaymentStats {
401    /// Computes the payment statistics for the given structured payment events.
402    pub fn compute(events: &StructuredPaymentEvents) -> Self {
403        PaymentStats {
404            average_latency: get_average(&events.latencies_usecs).map(Duration::from_micros),
405            median_latency: get_median(&events.latencies_usecs).map(Duration::from_micros),
406            total_fees: Amount::from_msats(events.fees.iter().map(|a| a.msats).sum()),
407            total_success: events.latencies_usecs.len(),
408            total_failure: events.latencies_failure.len(),
409        }
410    }
411}
412
413#[derive(Debug, Serialize, Deserialize, Clone)]
414pub struct PaymentSummaryPayload {
415    pub start_millis: u64,
416    pub end_millis: u64,
417}
418
419#[derive(Serialize, Deserialize, Debug, Clone)]
420pub struct ChannelInfo {
421    pub remote_pubkey: secp256k1::PublicKey,
422    pub channel_size_sats: u64,
423    pub outbound_liquidity_sats: u64,
424    pub inbound_liquidity_sats: u64,
425    pub is_active: bool,
426    pub funding_outpoint: Option<OutPoint>,
427    pub remote_node_alias: Option<String>,
428    #[serde(default)]
429    pub remote_address: Option<String>,
430    /// The local-side base routing fee (msat) currently advertised for this
431    /// channel. `None` if the backend could not report a fee policy.
432    #[serde(default)]
433    pub base_fee_msat: Option<u64>,
434    /// The local-side proportional routing fee (parts per million) currently
435    /// advertised for this channel. `None` if the backend could not report a
436    /// fee policy.
437    #[serde(default)]
438    pub parts_per_million: Option<u64>,
439}
440
441#[derive(Debug, Serialize, Deserialize, Clone)]
442pub struct OpenChannelRequest {
443    pub pubkey: secp256k1::PublicKey,
444    pub host: String,
445    pub channel_size_sats: u64,
446    pub push_amount_sats: u64,
447    /// Feerate (sat/vB) for the channel-opening on-chain transaction. If
448    /// `None`, the Lightning backend picks a feerate. Not honored by all
449    /// backends (e.g. LDK manages its own fee estimation).
450    #[serde(default, deserialize_with = "empty_string_as_none")]
451    pub fee_rate_sats_per_vbyte: Option<u64>,
452    /// Base routing fee (msat) advertised for the opened channel. If `None`,
453    /// the backend's default policy is used.
454    #[serde(default, deserialize_with = "empty_string_as_none")]
455    pub base_fee_msat: Option<u64>,
456    /// Proportional routing fee (parts per million) advertised for the opened
457    /// channel. If `None`, the backend's default policy is used.
458    #[serde(default, deserialize_with = "empty_string_as_none")]
459    pub parts_per_million: Option<u64>,
460}
461
462#[derive(Debug, Serialize, Deserialize, Clone)]
463pub struct ConnectPeerRequest {
464    pub node_address: NodeAddress,
465}
466
467#[derive(Debug, Clone, PartialEq, Eq)]
468pub struct NodeAddress {
469    pub pubkey: secp256k1::PublicKey,
470    pub address: SocketAddress,
471}
472
473impl NodeAddress {
474    pub fn host_with_port(&self) -> String {
475        self.address.to_string()
476    }
477}
478
479impl FromStr for NodeAddress {
480    type Err = String;
481
482    fn from_str(input: &str) -> Result<Self, Self::Err> {
483        let (pubkey, address) = input
484            .trim()
485            .split_once('@')
486            .ok_or_else(|| "Expected node address in pubkey@host[:port] format".to_string())?;
487        let pubkey = pubkey
488            .parse()
489            .map_err(|err| format!("Invalid peer public key: {err}"))?;
490        let address = address.trim();
491        if address.is_empty() {
492            return Err("Peer host must not be empty".to_string());
493        }
494        let address = if has_explicit_port(address) {
495            address.to_string()
496        } else {
497            format!("{address}:{DEFAULT_LIGHTNING_PORT}")
498        };
499        let address = SocketAddress::from_str(&address)
500            .map_err(|err| format!("Invalid peer address: {err}"))?;
501
502        Ok(NodeAddress { pubkey, address })
503    }
504}
505
506impl fmt::Display for NodeAddress {
507    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
508        let address = self.address.to_string();
509        if address.ends_with(&format!(":{DEFAULT_LIGHTNING_PORT}")) {
510            write!(
511                f,
512                "{}@{}",
513                self.pubkey,
514                &address[..address.len() - format!(":{DEFAULT_LIGHTNING_PORT}").len()]
515            )
516        } else {
517            write!(f, "{}@{}", self.pubkey, address)
518        }
519    }
520}
521
522fn has_explicit_port(address: &str) -> bool {
523    if address.starts_with('[') {
524        return address.contains("]:");
525    }
526
527    address.contains(':')
528}
529
530impl Serialize for NodeAddress {
531    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
532    where
533        S: Serializer,
534    {
535        serializer.serialize_str(&self.to_string())
536    }
537}
538
539impl<'de> Deserialize<'de> for NodeAddress {
540    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
541    where
542        D: Deserializer<'de>,
543    {
544        String::deserialize(deserializer)?
545            .parse()
546            .map_err(D::Error::custom)
547    }
548}
549
550#[derive(Debug, Serialize, Deserialize, Clone)]
551pub struct SetChannelFeesRequest {
552    /// Funding outpoint identifying the channel whose advertised routing fees
553    /// should be updated.
554    pub funding_outpoint: OutPoint,
555    /// New base routing fee in millisatoshis.
556    pub base_fee_msat: u64,
557    /// New proportional routing fee in parts per million.
558    pub parts_per_million: u64,
559}
560
561/// Helper for serde: deserializes missing values and empty form strings as
562/// `None`. Lets the same struct be used for JSON payloads and HTMX form
563/// submissions where numeric inputs may be left blank.
564fn empty_string_as_none<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
565where
566    D: serde::Deserializer<'de>,
567    T: std::str::FromStr + Deserialize<'de>,
568    T::Err: std::fmt::Display,
569{
570    #[derive(Deserialize)]
571    #[serde(untagged)]
572    enum StringOrT<T> {
573        String(String),
574        T(T),
575    }
576
577    match Option::<StringOrT<T>>::deserialize(deserializer)? {
578        None => Ok(None),
579        Some(StringOrT::T(value)) => Ok(Some(value)),
580        Some(StringOrT::String(s)) if s.trim().is_empty() => Ok(None),
581        Some(StringOrT::String(s)) => s
582            .trim()
583            .parse::<T>()
584            .map(Some)
585            .map_err(serde::de::Error::custom),
586    }
587}
588
589#[derive(Debug, Serialize, Deserialize, Clone)]
590pub struct SendOnchainRequest {
591    pub address: Address<NetworkUnchecked>,
592    pub amount: BitcoinAmountOrAll,
593    pub fee_rate_sats_per_vbyte: u64,
594}
595
596impl fmt::Display for SendOnchainRequest {
597    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
598        write!(
599            f,
600            "SendOnchainRequest {{ address: {}, amount: {}, fee_rate_sats_per_vbyte: {} }}",
601            self.address.assume_checked_ref(),
602            self.amount,
603            self.fee_rate_sats_per_vbyte
604        )
605    }
606}
607
608#[derive(Debug, Serialize, Deserialize, Clone)]
609pub struct CloseChannelsWithPeerRequest {
610    pub pubkey: secp256k1::PublicKey,
611    #[serde(default)]
612    pub force: bool,
613    pub sats_per_vbyte: Option<u64>,
614}
615
616impl fmt::Display for CloseChannelsWithPeerRequest {
617    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
618        write!(
619            f,
620            "CloseChannelsWithPeerRequest {{ pubkey: {}, force: {}, sats_per_vbyte: {} }}",
621            self.pubkey,
622            self.force,
623            match self.sats_per_vbyte {
624                Some(sats) => sats.to_string(),
625                None => "None".to_string(),
626            }
627        )
628    }
629}
630
631#[derive(Debug, Serialize, Deserialize, Clone)]
632pub struct CloseChannelsWithPeerResponse {
633    pub num_channels_closed: u32,
634}
635
636#[derive(Debug, Serialize, Deserialize, Clone)]
637pub struct GetInvoiceRequest {
638    pub payment_hash: sha256::Hash,
639}
640
641#[derive(Debug, Serialize, Deserialize, Clone)]
642pub struct GetInvoiceResponse {
643    pub preimage: Option<String>,
644    pub payment_hash: Option<sha256::Hash>,
645    pub amount: Amount,
646    pub created_at: SystemTime,
647    pub status: PaymentStatus,
648}
649
650#[derive(Debug, Serialize, Deserialize, Clone)]
651pub struct ListTransactionsPayload {
652    pub start_secs: u64,
653    pub end_secs: u64,
654}
655
656#[derive(Debug, Serialize, Deserialize, Clone)]
657pub struct ListTransactionsResponse {
658    pub transactions: Vec<PaymentDetails>,
659}
660
661#[derive(Debug, Serialize, Deserialize, Clone)]
662pub struct PaymentDetails {
663    pub payment_hash: Option<sha256::Hash>,
664    pub preimage: Option<String>,
665    pub payment_kind: PaymentKind,
666    pub amount: Amount,
667    pub direction: PaymentDirection,
668    pub status: PaymentStatus,
669    pub timestamp_secs: u64,
670}
671
672#[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq)]
673pub enum PaymentKind {
674    Bolt11,
675    Bolt12Offer,
676    Bolt12Refund,
677    Onchain,
678}
679
680#[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq)]
681pub enum PaymentDirection {
682    Outbound,
683    Inbound,
684}
685
686#[derive(Debug, Serialize, Deserialize, Clone)]
687pub struct CreateOfferPayload {
688    pub amount: Option<Amount>,
689    pub description: Option<String>,
690    pub expiry_secs: Option<u32>,
691    pub quantity: Option<u64>,
692}
693
694#[derive(Debug, Serialize, Deserialize, Clone)]
695pub struct CreateOfferResponse {
696    pub offer: String,
697}
698
699#[derive(Debug, Serialize, Deserialize, Clone)]
700pub struct PayOfferPayload {
701    pub offer: String,
702    pub amount: Option<Amount>,
703    pub quantity: Option<u64>,
704    pub payer_note: Option<String>,
705}
706
707#[derive(Debug, Serialize, Deserialize, Clone)]
708pub struct PayOfferResponse {
709    pub preimage: String,
710}
711
712#[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq)]
713pub enum PaymentStatus {
714    Pending,
715    Succeeded,
716    Failed,
717}
718
719/// Default value for LND's `SendPaymentRequest::time_pref`. LND interprets this
720/// as a value in [`LND_TIME_PREF_MIN`, `LND_TIME_PREF_MAX`], where -1 optimizes
721/// purely for fees and 1 optimizes purely for reliability. We default to 0.5 to
722/// favor reliability while still considering fees.
723pub const LND_DEFAULT_TIME_PREF: f64 = 0.5;
724pub const LND_TIME_PREF_MIN: f64 = -1.0;
725pub const LND_TIME_PREF_MAX: f64 = 1.0;
726
727fn parse_lnd_time_pref(s: &str) -> Result<f64, String> {
728    let parsed: f64 = s.parse().map_err(|e| format!("invalid f64: {e}"))?;
729    if !parsed.is_finite() || !(LND_TIME_PREF_MIN..=LND_TIME_PREF_MAX).contains(&parsed) {
730        return Err(format!(
731            "must be a finite value in [{LND_TIME_PREF_MIN}, {LND_TIME_PREF_MAX}]"
732        ));
733    }
734    Ok(parsed)
735}
736
737/// Default value for LND's `SendPaymentRequest::timeout_seconds`, i.e. how long
738/// LND keeps trying to route an outgoing payment before giving up. This does
739/// not cancel an HTLC that is already in flight; it bounds pathfinding/retry.
740pub const LND_DEFAULT_PAYMENT_TIMEOUT_SECS: i32 = 180;
741pub const LND_PAYMENT_TIMEOUT_SECS_MIN: i32 = 1;
742pub const LND_PAYMENT_TIMEOUT_SECS_MAX: i32 = 600;
743
744fn parse_lnd_payment_timeout_secs(s: &str) -> Result<i32, String> {
745    let parsed: i32 = s.parse().map_err(|e| format!("invalid i32: {e}"))?;
746    if !(LND_PAYMENT_TIMEOUT_SECS_MIN..=LND_PAYMENT_TIMEOUT_SECS_MAX).contains(&parsed) {
747        return Err(format!(
748            "must be an integer in [{LND_PAYMENT_TIMEOUT_SECS_MIN}, {LND_PAYMENT_TIMEOUT_SECS_MAX}]"
749        ));
750    }
751    Ok(parsed)
752}
753
754#[derive(Debug, Clone, Subcommand, Serialize, Deserialize, PartialEq)]
755pub enum LightningMode {
756    #[clap(name = "lnd")]
757    Lnd {
758        /// LND RPC address
759        #[arg(long = "lnd-rpc-host", env = FM_LND_RPC_ADDR_ENV)]
760        lnd_rpc_addr: String,
761
762        /// LND TLS cert file path
763        #[arg(long = "lnd-tls-cert", env = FM_LND_TLS_CERT_ENV)]
764        lnd_tls_cert: String,
765
766        /// LND macaroon file path
767        #[arg(long = "lnd-macaroon", env = FM_LND_MACAROON_ENV)]
768        lnd_macaroon: String,
769
770        /// `time_pref` passed to LND `SendPaymentRequest`. -1.0 optimizes
771        /// purely for fees, 1.0 optimizes purely for reliability.
772        #[arg(
773            long = "lnd-time-pref",
774            env = FM_LND_TIME_PREF_ENV,
775            default_value_t = LND_DEFAULT_TIME_PREF,
776            value_parser = parse_lnd_time_pref,
777        )]
778        lnd_time_pref: f64,
779
780        /// How long (in seconds) LND keeps trying to route an outgoing payment
781        /// before giving up. Passed as `timeout_seconds` to LND
782        /// `SendPaymentRequest`. Must be in [1, 600].
783        #[arg(
784            long = "lnd-payment-timeout",
785            env = FM_LND_PAYMENT_TIMEOUT_SECS_ENV,
786            default_value_t = LND_DEFAULT_PAYMENT_TIMEOUT_SECS,
787            value_parser = parse_lnd_payment_timeout_secs,
788        )]
789        lnd_payment_timeout_secs: i32,
790    },
791    #[clap(name = "ldk")]
792    Ldk {
793        /// LDK lightning server port
794        #[arg(long = "ldk-lightning-port", env = FM_PORT_LDK)]
795        lightning_port: u16,
796
797        /// LDK's Alias
798        #[arg(long = "ldk-alias", env = FM_LDK_ALIAS_ENV)]
799        alias: String,
800    },
801}
802
803#[derive(Clone)]
804pub enum ChainSource {
805    Bitcoind {
806        username: String,
807        password: String,
808        server_url: SafeUrl,
809    },
810    Esplora {
811        server_url: SafeUrl,
812    },
813}
814
815impl fmt::Display for ChainSource {
816    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
817        match self {
818            ChainSource::Bitcoind {
819                username: _,
820                password: _,
821                server_url,
822            } => {
823                write!(f, "Bitcoind source with URL: {server_url}")
824            }
825            ChainSource::Esplora { server_url } => {
826                write!(f, "Esplora source with URL: {server_url}")
827            }
828        }
829    }
830}
831
832#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
833#[serde(rename_all = "snake_case")]
834pub enum LightningInfo {
835    Connected {
836        public_key: PublicKey,
837        alias: String,
838        network: Network,
839        block_height: u64,
840        synced_to_chain: bool,
841    },
842    NotConnected,
843}
844
845#[derive(
846    Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Encodable, Decodable, Serialize, Deserialize,
847)]
848#[serde(rename_all = "snake_case")]
849pub enum RegisteredProtocol {
850    Http,
851    Iroh,
852}
853
854#[derive(Debug, Serialize, Deserialize, Clone)]
855pub struct SetMnemonicPayload {
856    pub words: Option<String>,
857}
858
859#[cfg(test)]
860mod tests;