Skip to main content

fedimint_lnv2_common/
gateway_api.rs

1use std::str::FromStr;
2
3use bitcoin::secp256k1::PublicKey;
4use bitcoin::secp256k1::schnorr::Signature;
5use fedimint_connectors::error::ServerError;
6use fedimint_core::config::FederationId;
7use fedimint_core::encoding::{Decodable, Encodable};
8use fedimint_core::util::SafeUrl;
9use fedimint_core::{Amount, OutPoint, apply, async_trait_maybe_send};
10use fedimint_ln_common::client::GatewayApi;
11use lightning_invoice::{Bolt11Invoice, RoutingFees};
12use reqwest::Method;
13use serde::{Deserialize, Serialize};
14use thiserror::Error;
15
16use crate::contracts::{IncomingContract, OutgoingContract};
17use crate::endpoint_constants::{
18    CREATE_BOLT11_INVOICE_ENDPOINT, ROUTING_INFO_ENDPOINT, SEND_PAYMENT_ENDPOINT,
19};
20use crate::{Bolt11InvoiceDescription, LightningInvoice};
21
22#[apply(async_trait_maybe_send!)]
23pub trait GatewayConnection: std::fmt::Debug {
24    async fn routing_info(
25        &self,
26        gateway_api: SafeUrl,
27        federation_id: &FederationId,
28    ) -> Result<Option<RoutingInfo>, ServerError>;
29
30    async fn bolt11_invoice(
31        &self,
32        gateway_api: SafeUrl,
33        federation_id: FederationId,
34        contract: IncomingContract,
35        amount: Amount,
36        description: Bolt11InvoiceDescription,
37        expiry_secs: u32,
38    ) -> Result<Bolt11Invoice, ServerError>;
39
40    async fn send_payment(
41        &self,
42        gateway_api: SafeUrl,
43        federation_id: FederationId,
44        outpoint: OutPoint,
45        contract: OutgoingContract,
46        invoice: LightningInvoice,
47        auth: Signature,
48    ) -> Result<Result<[u8; 32], Signature>, ServerError>;
49}
50
51#[derive(Debug, Clone)]
52pub struct RealGatewayConnection {
53    pub api: GatewayApi,
54}
55
56#[apply(async_trait_maybe_send!)]
57impl GatewayConnection for RealGatewayConnection {
58    async fn routing_info(
59        &self,
60        gateway_api: SafeUrl,
61        federation_id: &FederationId,
62    ) -> Result<Option<RoutingInfo>, ServerError> {
63        self.api
64            .request(
65                &gateway_api,
66                Method::POST,
67                ROUTING_INFO_ENDPOINT,
68                Some(federation_id),
69            )
70            .await
71    }
72
73    async fn bolt11_invoice(
74        &self,
75        gateway_api: SafeUrl,
76        federation_id: FederationId,
77        contract: IncomingContract,
78        amount: Amount,
79        description: Bolt11InvoiceDescription,
80        expiry_secs: u32,
81    ) -> Result<Bolt11Invoice, ServerError> {
82        self.api
83            .request(
84                &gateway_api,
85                Method::POST,
86                CREATE_BOLT11_INVOICE_ENDPOINT,
87                Some(CreateBolt11InvoicePayload {
88                    federation_id,
89                    contract,
90                    amount,
91                    description,
92                    expiry_secs,
93                }),
94            )
95            .await
96    }
97
98    async fn send_payment(
99        &self,
100        gateway_api: SafeUrl,
101        federation_id: FederationId,
102        outpoint: OutPoint,
103        contract: OutgoingContract,
104        invoice: LightningInvoice,
105        auth: Signature,
106    ) -> Result<Result<[u8; 32], Signature>, ServerError> {
107        self.api
108            .request(
109                &gateway_api,
110                Method::POST,
111                SEND_PAYMENT_ENDPOINT,
112                Some(SendPaymentPayload {
113                    federation_id,
114                    outpoint,
115                    contract,
116                    invoice,
117                    auth,
118                }),
119            )
120            .await
121    }
122}
123
124#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
125pub struct CreateBolt11InvoicePayload {
126    pub federation_id: FederationId,
127    pub contract: IncomingContract,
128    pub amount: Amount,
129    pub description: Bolt11InvoiceDescription,
130    pub expiry_secs: u32,
131}
132
133#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]
134pub struct SendPaymentPayload {
135    pub federation_id: FederationId,
136    pub outpoint: OutPoint,
137    pub contract: OutgoingContract,
138    pub invoice: LightningInvoice,
139    pub auth: Signature,
140}
141
142#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]
143pub struct RoutingInfo {
144    /// The public key of the gateways lightning node. Since this key signs the
145    /// gateways invoices the senders client uses it to differentiate between a
146    /// direct swap between fedimints and a lightning swap.
147    pub lightning_public_key: PublicKey,
148    /// The human-readable alias of the gateway's lightning node, if available.
149    ///
150    /// This field is optional for backwards-compatibility with older gateways
151    /// that do not yet provide an alias in their `routing_info` responses.
152    #[serde(default, skip_serializing_if = "Option::is_none")]
153    pub lightning_alias: Option<String>,
154    /// The public key of the gateways client module. This key is used to claim
155    /// or cancel outgoing contracts and refund incoming contracts.
156    pub module_public_key: PublicKey,
157    /// This is the fee the gateway charges for an outgoing payment. The senders
158    /// client will use this fee in case of a direct swap.
159    pub send_fee_minimum: PaymentFee,
160    /// This is the default total fee the gateway recommends for an outgoing
161    /// payment in case of a lightning swap. It accounts for the additional fee
162    /// required to reliably route this payment over lightning.
163    pub send_fee_default: PaymentFee,
164    /// This is the minimum expiration delta in block the gateway requires for
165    /// an outgoing payment. The senders client will use this expiration delta
166    /// in case of a direct swap.
167    pub expiration_delta_minimum: u64,
168    /// This is the default total expiration the gateway recommends for an
169    /// outgoing payment in case of a lightning swap. It accounts for the
170    /// additional expiration delta required to successfully route this payment
171    /// over lightning.
172    pub expiration_delta_default: u64,
173    /// This is the fee the gateway charges for an incoming payment.
174    pub receive_fee: PaymentFee,
175}
176
177impl RoutingInfo {
178    pub fn send_parameters(&self, invoice: &Bolt11Invoice) -> (PaymentFee, u64) {
179        if invoice.recover_payee_pub_key() == self.lightning_public_key {
180            (self.send_fee_minimum, self.expiration_delta_minimum)
181        } else {
182            (self.send_fee_default, self.expiration_delta_default)
183        }
184    }
185}
186
187#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize, Encodable, Decodable, Copy)]
188pub struct PaymentFee {
189    pub base: Amount,
190    pub parts_per_million: u64,
191}
192
193impl PaymentFee {
194    /// This is the maximum send fee of one and a half percent plus one hundred
195    /// satoshis a correct gateway may recommend as a default. It accounts for
196    /// the fee required to reliably route this payment over lightning.
197    pub const SEND_FEE_LIMIT: PaymentFee = PaymentFee {
198        base: Amount::from_sats(100),
199        parts_per_million: 15_000,
200    };
201
202    /// This is the fee the gateway uses to cover transaction fees with the
203    /// federation.
204    pub const TRANSACTION_FEE_DEFAULT: PaymentFee = PaymentFee {
205        base: Amount::from_sats(2),
206        parts_per_million: 3000,
207    };
208
209    /// This is the maximum receive fee of half of one percent plus fifty
210    /// satoshis a correct gateway may recommend as a default.
211    pub const RECEIVE_FEE_LIMIT: PaymentFee = PaymentFee {
212        base: Amount::from_sats(50),
213        parts_per_million: 5_000,
214    };
215
216    /// Returns `true` if this fee is within `limit` in both components.
217    ///
218    /// `absolute_fee` is monotonically increasing in `base` and in
219    /// `parts_per_million`, so a fee is bounded by the limit only when neither
220    /// component exceeds it. This is intentionally a named method rather than a
221    /// derived `PartialOrd`, which orders the fields lexicographically and
222    /// therefore stops at `base` whenever the two bases differ.
223    pub fn is_within(&self, limit: &PaymentFee) -> bool {
224        self.base <= limit.base && self.parts_per_million <= limit.parts_per_million
225    }
226
227    /// Adds two fees, returning `None` if either component overflows.
228    ///
229    /// Fees reach this method straight from operator input, so the addition
230    /// has to happen before the limit checks can run. A panicking `Add` would
231    /// therefore be reachable with a fee that the limits are meant to reject.
232    pub fn checked_add(self, rhs: Self) -> Option<PaymentFee> {
233        Some(PaymentFee {
234            base: self.base.checked_add(rhs.base)?,
235            parts_per_million: self.parts_per_million.checked_add(rhs.parts_per_million)?,
236        })
237    }
238
239    pub fn add_to(&self, msats: u64) -> Amount {
240        Amount::from_msats(msats.saturating_add(self.absolute_fee(msats)))
241    }
242
243    pub fn subtract_from(&self, msats: u64) -> Amount {
244        Amount::from_msats(msats.saturating_sub(self.absolute_fee(msats)))
245    }
246
247    pub fn fee(&self, msats: u64) -> Amount {
248        Amount::from_msats(self.absolute_fee(msats))
249    }
250
251    fn absolute_fee(&self, msats: u64) -> u64 {
252        // The base fee is bounded well below `u64::MAX` for any fee that passed
253        // the limit checks, but a fee decoded from an older database has not
254        // necessarily passed them, so saturate rather than panic.
255        msats
256            .saturating_mul(self.parts_per_million)
257            .saturating_div(1_000_000)
258            .saturating_add(self.base.msats)
259    }
260}
261
262/// A [`PaymentFee`] that does not fit into the `u32` components of
263/// [`RoutingFees`] and therefore cannot be announced to lightning clients.
264#[derive(Debug, Error)]
265#[error("Payment fee {0} exceeds the range of RoutingFees")]
266pub struct FeeOutOfRangeError(PaymentFee);
267
268impl From<RoutingFees> for PaymentFee {
269    fn from(value: RoutingFees) -> Self {
270        PaymentFee {
271            base: Amount::from_msats(u64::from(value.base_msat)),
272            parts_per_million: u64::from(value.proportional_millionths),
273        }
274    }
275}
276
277impl TryFrom<PaymentFee> for RoutingFees {
278    type Error = FeeOutOfRangeError;
279
280    fn try_from(value: PaymentFee) -> Result<Self, Self::Error> {
281        Ok(RoutingFees {
282            base_msat: u32::try_from(value.base.msats).map_err(|_| FeeOutOfRangeError(value))?,
283            proportional_millionths: u32::try_from(value.parts_per_million)
284                .map_err(|_| FeeOutOfRangeError(value))?,
285        })
286    }
287}
288
289impl std::fmt::Display for PaymentFee {
290    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
291        write!(f, "{},{}", self.base, self.parts_per_million)
292    }
293}
294
295impl FromStr for PaymentFee {
296    type Err = anyhow::Error;
297
298    fn from_str(s: &str) -> Result<Self, Self::Err> {
299        let mut parts = s.split(',');
300        let base_str = parts
301            .next()
302            .ok_or(anyhow::anyhow!("Failed to parse base fee"))?;
303        let ppm_str = parts.next().ok_or(anyhow::anyhow!("Failed to parse ppm"))?;
304
305        // Ensure no extra parts
306        if parts.next().is_some() {
307            return Err(anyhow::anyhow!(
308                "Failed to parse fees. Expected format <base>,<ppm>"
309            ));
310        }
311
312        let base = Amount::from_str(base_str)?;
313        let parts_per_million = ppm_str.parse::<u64>()?;
314
315        Ok(PaymentFee {
316            base,
317            parts_per_million,
318        })
319    }
320}
321
322#[cfg(test)]
323mod tests {
324    use fedimint_core::Amount;
325    use lightning_invoice::RoutingFees;
326
327    use super::PaymentFee;
328
329    /// A lower `base` must not let an over-limit `parts_per_million` through,
330    /// which is what the lexicographic ordering used to allow.
331    #[test]
332    fn is_within_enforces_both_components() {
333        // base under the limit, ppm over it, on the send side.
334        let over_ppm = PaymentFee {
335            base: Amount::from_sats(0),
336            parts_per_million: 1_000_000,
337        };
338        assert!(!over_ppm.is_within(&PaymentFee::SEND_FEE_LIMIT));
339
340        let over_ppm = PaymentFee {
341            base: Amount::from_sats(0),
342            parts_per_million: 5_000_000,
343        };
344        assert!(!over_ppm.is_within(&PaymentFee::SEND_FEE_LIMIT));
345
346        // Same on the receive side, which has the lower cap of the two.
347        let over_ppm = PaymentFee {
348            base: Amount::from_sats(0),
349            parts_per_million: 500_000,
350        };
351        assert!(!over_ppm.is_within(&PaymentFee::RECEIVE_FEE_LIMIT));
352
353        // The reverse case, which the ordering already rejected.
354        let over_base = PaymentFee {
355            base: Amount::from_sats(101),
356            parts_per_million: 0,
357        };
358        assert!(!over_base.is_within(&PaymentFee::SEND_FEE_LIMIT));
359
360        // Exactly at the limit is accepted.
361        assert!(PaymentFee::SEND_FEE_LIMIT.is_within(&PaymentFee::SEND_FEE_LIMIT));
362
363        // Strictly within on both components is accepted.
364        let ok = PaymentFee {
365            base: Amount::from_sats(50),
366            parts_per_million: 10_000,
367        };
368        assert!(ok.is_within(&PaymentFee::SEND_FEE_LIMIT));
369    }
370
371    /// Adding two operator-supplied fees must not panic on overflow, in either
372    /// component.
373    #[test]
374    fn checked_add_reports_overflow_instead_of_panicking() {
375        let max_base = PaymentFee {
376            base: Amount::from_msats(u64::MAX),
377            parts_per_million: 0,
378        };
379        let one_msat = PaymentFee {
380            base: Amount::from_msats(1),
381            parts_per_million: 0,
382        };
383        assert!(max_base.checked_add(one_msat).is_none());
384
385        let max_ppm = PaymentFee {
386            base: Amount::ZERO,
387            parts_per_million: u64::MAX,
388        };
389        let one_ppm = PaymentFee {
390            base: Amount::ZERO,
391            parts_per_million: 1,
392        };
393        assert!(max_ppm.checked_add(one_ppm).is_none());
394
395        assert_eq!(
396            PaymentFee::TRANSACTION_FEE_DEFAULT
397                .checked_add(PaymentFee::TRANSACTION_FEE_DEFAULT)
398                .expect("Two default fees fit"),
399            PaymentFee {
400                base: Amount::from_sats(4),
401                parts_per_million: 6_000,
402            }
403        );
404    }
405
406    /// A fee that outgrew the `u32`s of `RoutingFees` must surface as an error
407    /// rather than a panic: the conversion runs on every lightning payment and
408    /// on federation registration at startup, so a panic here boot-loops the
409    /// gateway.
410    #[test]
411    fn routing_fees_conversion_rejects_out_of_range_fees() {
412        let over_base = PaymentFee {
413            base: Amount::from_msats(u64::from(u32::MAX) + 1),
414            parts_per_million: 0,
415        };
416        assert!(RoutingFees::try_from(over_base).is_err());
417
418        let over_ppm = PaymentFee {
419            base: Amount::ZERO,
420            parts_per_million: u64::from(u32::MAX) + 1,
421        };
422        assert!(RoutingFees::try_from(over_ppm).is_err());
423
424        let fees = RoutingFees::try_from(PaymentFee::SEND_FEE_LIMIT)
425            .expect("The send fee limit is within range");
426        assert_eq!(fees.base_msat, 100_000);
427        assert_eq!(fees.proportional_millionths, 15_000);
428    }
429
430    /// Any fee that `set_fees` accepts is small enough for the fee arithmetic
431    /// to stay exact, and an out-of-range fee left in an old database must
432    /// saturate instead of panicking.
433    #[test]
434    fn absolute_fee_saturates_instead_of_panicking() {
435        let huge = PaymentFee {
436            base: Amount::from_msats(u64::MAX),
437            parts_per_million: u64::MAX,
438        };
439        assert_eq!(huge.fee(u64::MAX), Amount::from_msats(u64::MAX));
440
441        assert_eq!(
442            PaymentFee::TRANSACTION_FEE_DEFAULT.fee(1_000_000),
443            Amount::from_msats(2_000 + 3_000)
444        );
445    }
446}