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 pub lightning_public_key: PublicKey,
148 #[serde(default, skip_serializing_if = "Option::is_none")]
153 pub lightning_alias: Option<String>,
154 pub module_public_key: PublicKey,
157 pub send_fee_minimum: PaymentFee,
160 pub send_fee_default: PaymentFee,
164 pub expiration_delta_minimum: u64,
168 pub expiration_delta_default: u64,
173 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 pub const SEND_FEE_LIMIT: PaymentFee = PaymentFee {
198 base: Amount::from_sats(100),
199 parts_per_million: 15_000,
200 };
201
202 pub const TRANSACTION_FEE_DEFAULT: PaymentFee = PaymentFee {
205 base: Amount::from_sats(2),
206 parts_per_million: 3000,
207 };
208
209 pub const RECEIVE_FEE_LIMIT: PaymentFee = PaymentFee {
212 base: Amount::from_sats(50),
213 parts_per_million: 5_000,
214 };
215
216 pub fn is_within(&self, limit: &PaymentFee) -> bool {
224 self.base <= limit.base && self.parts_per_million <= limit.parts_per_million
225 }
226
227 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 msats
256 .saturating_mul(self.parts_per_million)
257 .saturating_div(1_000_000)
258 .saturating_add(self.base.msats)
259 }
260}
261
262#[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 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 #[test]
332 fn is_within_enforces_both_components() {
333 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 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 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 assert!(PaymentFee::SEND_FEE_LIMIT.is_within(&PaymentFee::SEND_FEE_LIMIT));
362
363 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 #[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 #[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 #[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}