Skip to content

Commit 07b5471

Browse files
Restructure FFI bindings with conversion traits for Lightning types
This commit reorganizes the FFI architecture by introducing conversion traits for lightning types. Moves code from uniffi_types.rs to a dedicated ffi module for separation of concerns.
1 parent 7977b04 commit 07b5471

File tree

6 files changed

+89
-69
lines changed

6 files changed

+89
-69
lines changed

src/ffi/mod.rs

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// This file is Copyright its original authors, visible in version control history.
2+
//
3+
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5+
// http://opensource.org/licenses/MIT>, at your option. You may not use this file except in
6+
7+
#[cfg(feature = "uniffi")]
8+
mod types;
9+
10+
#[cfg(feature = "uniffi")]
11+
pub use types::*;
12+
13+
#[cfg(feature = "uniffi")]
14+
pub fn maybe_deref<T, R>(wrapped_type: &std::sync::Arc<T>) -> &R
15+
where
16+
T: AsRef<R>,
17+
{
18+
wrapped_type.as_ref().as_ref()
19+
}
20+
21+
#[cfg(feature = "uniffi")]
22+
pub fn maybe_try_convert_enum<T, R>(wrapped_type: &T) -> Result<R, crate::error::Error>
23+
where
24+
for<'a> R: TryFrom<&'a T, Error = crate::error::Error>,
25+
{
26+
R::try_from(wrapped_type)
27+
}
28+
29+
#[cfg(feature = "uniffi")]
30+
pub fn maybe_wrap<T>(ldk_type: impl Into<T>) -> std::sync::Arc<T> {
31+
std::sync::Arc::new(ldk_type.into())
32+
}
33+
34+
#[cfg(not(feature = "uniffi"))]
35+
pub fn maybe_deref<T>(value: &T) -> &T {
36+
value
37+
}
38+
39+
#[cfg(not(feature = "uniffi"))]
40+
pub fn maybe_try_convert_enum<T>(value: &T) -> Result<&T, crate::error::Error> {
41+
Ok(value)
42+
}
43+
44+
#[cfg(not(feature = "uniffi"))]
45+
pub fn maybe_wrap<T>(value: T) -> T {
46+
value
47+
}

src/uniffi_types.rs renamed to src/ffi/types.rs

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ use lightning::util::ser::Writeable;
6161
use lightning_invoice::{Bolt11Invoice as LdkBolt11Invoice, Bolt11InvoiceDescriptionRef};
6262

6363
use std::convert::TryInto;
64+
use std::ops::Deref;
6465
use std::str::FromStr;
6566
use std::sync::Arc;
6667
use std::time::Duration;
@@ -475,11 +476,6 @@ impl Bolt11Invoice {
475476
invoice_str.parse()
476477
}
477478

478-
/// Returns the underlying invoice [`LdkBolt11Invoice`]
479-
pub fn into_inner(self) -> LdkBolt11Invoice {
480-
self.inner
481-
}
482-
483479
/// The hash of the [`RawBolt11Invoice`] that was signed.
484480
///
485481
/// [`RawBolt11Invoice`]: lightning_invoice::RawBolt11Invoice
@@ -593,9 +589,16 @@ impl From<LdkBolt11Invoice> for Bolt11Invoice {
593589
}
594590
}
595591

596-
impl From<Bolt11Invoice> for LdkBolt11Invoice {
597-
fn from(wrapper: Bolt11Invoice) -> Self {
598-
wrapper.into_inner()
592+
impl Deref for Bolt11Invoice {
593+
type Target = LdkBolt11Invoice;
594+
fn deref(&self) -> &Self::Target {
595+
&self.inner
596+
}
597+
}
598+
599+
impl AsRef<LdkBolt11Invoice> for Bolt11Invoice {
600+
fn as_ref(&self) -> &LdkBolt11Invoice {
601+
self.deref()
599602
}
600603
}
601604

src/lib.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ mod data_store;
8484
mod error;
8585
mod event;
8686
mod fee_estimator;
87+
mod ffi;
8788
mod gossip;
8889
pub mod graph;
8990
mod hex_utils;
@@ -96,8 +97,6 @@ mod peer_store;
9697
mod sweep;
9798
mod tx_broadcaster;
9899
mod types;
99-
#[cfg(feature = "uniffi")]
100-
mod uniffi_types;
101100
mod wallet;
102101

103102
pub use bip39;
@@ -117,7 +116,7 @@ pub use event::Event;
117116
pub use io::utils::generate_entropy_mnemonic;
118117

119118
#[cfg(feature = "uniffi")]
120-
use uniffi_types::*;
119+
use ffi::*;
121120

122121
#[cfg(feature = "uniffi")]
123122
pub use builder::ArcedNodeBuilder as Builder;

src/liquidity.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1308,7 +1308,7 @@ type PaymentInfo = lightning_liquidity::lsps1::msgs::PaymentInfo;
13081308
#[derive(Clone, Debug, PartialEq, Eq)]
13091309
pub struct PaymentInfo {
13101310
/// A Lightning payment using BOLT 11.
1311-
pub bolt11: Option<crate::uniffi_types::Bolt11PaymentInfo>,
1311+
pub bolt11: Option<crate::ffi::Bolt11PaymentInfo>,
13121312
/// An onchain payment.
13131313
pub onchain: Option<OnchainPaymentInfo>,
13141314
}

src/payment/bolt11.rs

Lines changed: 25 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ use crate::config::{Config, LDK_PAYMENT_RETRY_TIMEOUT};
1313
use crate::connection::ConnectionManager;
1414
use crate::data_store::DataStoreUpdateResult;
1515
use crate::error::Error;
16+
use crate::ffi::{maybe_deref, maybe_try_convert_enum, maybe_wrap};
1617
use crate::liquidity::LiquiditySource;
1718
use crate::logger::{log_error, log_info, LdkLogger, Logger};
1819
use crate::payment::store::{
@@ -42,43 +43,12 @@ use std::sync::{Arc, RwLock};
4243
#[cfg(not(feature = "uniffi"))]
4344
type Bolt11Invoice = LdkBolt11Invoice;
4445
#[cfg(feature = "uniffi")]
45-
type Bolt11Invoice = Arc<crate::uniffi_types::Bolt11Invoice>;
46-
47-
#[cfg(not(feature = "uniffi"))]
48-
pub(crate) fn maybe_wrap_invoice(invoice: LdkBolt11Invoice) -> Bolt11Invoice {
49-
invoice
50-
}
51-
#[cfg(feature = "uniffi")]
52-
pub(crate) fn maybe_wrap_invoice(invoice: LdkBolt11Invoice) -> Bolt11Invoice {
53-
Arc::new(invoice.into())
54-
}
55-
56-
#[cfg(not(feature = "uniffi"))]
57-
pub fn maybe_convert_invoice(invoice: &Bolt11Invoice) -> &LdkBolt11Invoice {
58-
invoice
59-
}
60-
#[cfg(feature = "uniffi")]
61-
pub fn maybe_convert_invoice(invoice: &Bolt11Invoice) -> &LdkBolt11Invoice {
62-
&invoice.inner
63-
}
46+
type Bolt11Invoice = Arc<crate::ffi::Bolt11Invoice>;
6447

6548
#[cfg(not(feature = "uniffi"))]
6649
type Bolt11InvoiceDescription = LdkBolt11InvoiceDescription;
6750
#[cfg(feature = "uniffi")]
68-
type Bolt11InvoiceDescription = crate::uniffi_types::Bolt11InvoiceDescription;
69-
70-
macro_rules! maybe_convert_description {
71-
($description: expr) => {{
72-
#[cfg(not(feature = "uniffi"))]
73-
{
74-
$description
75-
}
76-
#[cfg(feature = "uniffi")]
77-
{
78-
&LdkBolt11InvoiceDescription::try_from($description)?
79-
}
80-
}};
81-
}
51+
type Bolt11InvoiceDescription = crate::ffi::Bolt11InvoiceDescription;
8252

8353
/// A payment handler allowing to create and pay [BOLT 11] invoices.
8454
///
@@ -125,7 +95,7 @@ impl Bolt11Payment {
12595
pub fn send(
12696
&self, invoice: &Bolt11Invoice, sending_parameters: Option<SendingParameters>,
12797
) -> Result<PaymentId, Error> {
128-
let invoice = maybe_convert_invoice(invoice);
98+
let invoice = maybe_deref(invoice);
12999
let rt_lock = self.runtime.read().unwrap();
130100
if rt_lock.is_none() {
131101
return Err(Error::NotRunning);
@@ -234,7 +204,7 @@ impl Bolt11Payment {
234204
&self, invoice: &Bolt11Invoice, amount_msat: u64,
235205
sending_parameters: Option<SendingParameters>,
236206
) -> Result<PaymentId, Error> {
237-
let invoice = maybe_convert_invoice(invoice);
207+
let invoice = maybe_deref(invoice);
238208
let rt_lock = self.runtime.read().unwrap();
239209
if rt_lock.is_none() {
240210
return Err(Error::NotRunning);
@@ -466,9 +436,9 @@ impl Bolt11Payment {
466436
pub fn receive(
467437
&self, amount_msat: u64, description: &Bolt11InvoiceDescription, expiry_secs: u32,
468438
) -> Result<Bolt11Invoice, Error> {
469-
let description = maybe_convert_description!(description);
470-
let invoice = self.receive_inner(Some(amount_msat), description, expiry_secs, None)?;
471-
Ok(maybe_wrap_invoice(invoice))
439+
let description = maybe_try_convert_enum(description)?;
440+
let invoice = self.receive_inner(Some(amount_msat), &description, expiry_secs, None)?;
441+
Ok(maybe_wrap(invoice))
472442
}
473443

474444
/// Returns a payable invoice that can be used to request a payment of the amount
@@ -489,10 +459,10 @@ impl Bolt11Payment {
489459
&self, amount_msat: u64, description: &Bolt11InvoiceDescription, expiry_secs: u32,
490460
payment_hash: PaymentHash,
491461
) -> Result<Bolt11Invoice, Error> {
492-
let description = maybe_convert_description!(description);
462+
let description = maybe_try_convert_enum(description)?;
493463
let invoice =
494-
self.receive_inner(Some(amount_msat), description, expiry_secs, Some(payment_hash))?;
495-
Ok(maybe_wrap_invoice(invoice))
464+
self.receive_inner(Some(amount_msat), &description, expiry_secs, Some(payment_hash))?;
465+
Ok(maybe_wrap(invoice))
496466
}
497467

498468
/// Returns a payable invoice that can be used to request and receive a payment for which the
@@ -502,9 +472,9 @@ impl Bolt11Payment {
502472
pub fn receive_variable_amount(
503473
&self, description: &Bolt11InvoiceDescription, expiry_secs: u32,
504474
) -> Result<Bolt11Invoice, Error> {
505-
let description = maybe_convert_description!(description);
506-
let invoice = self.receive_inner(None, description, expiry_secs, None)?;
507-
Ok(maybe_wrap_invoice(invoice))
475+
let description = maybe_try_convert_enum(description)?;
476+
let invoice = self.receive_inner(None, &description, expiry_secs, None)?;
477+
Ok(maybe_wrap(invoice))
508478
}
509479

510480
/// Returns a payable invoice that can be used to request a payment for the given payment hash
@@ -524,9 +494,9 @@ impl Bolt11Payment {
524494
pub fn receive_variable_amount_for_hash(
525495
&self, description: &Bolt11InvoiceDescription, expiry_secs: u32, payment_hash: PaymentHash,
526496
) -> Result<Bolt11Invoice, Error> {
527-
let description = maybe_convert_description!(description);
528-
let invoice = self.receive_inner(None, description, expiry_secs, Some(payment_hash))?;
529-
Ok(maybe_wrap_invoice(invoice))
497+
let description = maybe_try_convert_enum(description)?;
498+
let invoice = self.receive_inner(None, &description, expiry_secs, Some(payment_hash))?;
499+
Ok(maybe_wrap(invoice))
530500
}
531501

532502
pub(crate) fn receive_inner(
@@ -601,15 +571,15 @@ impl Bolt11Payment {
601571
&self, amount_msat: u64, description: &Bolt11InvoiceDescription, expiry_secs: u32,
602572
max_total_lsp_fee_limit_msat: Option<u64>,
603573
) -> Result<Bolt11Invoice, Error> {
604-
let description = maybe_convert_description!(description);
574+
let description = maybe_try_convert_enum(description)?;
605575
let invoice = self.receive_via_jit_channel_inner(
606576
Some(amount_msat),
607-
description,
577+
&description,
608578
expiry_secs,
609579
max_total_lsp_fee_limit_msat,
610580
None,
611581
)?;
612-
Ok(maybe_wrap_invoice(invoice))
582+
Ok(maybe_wrap(invoice))
613583
}
614584

615585
/// Returns a payable invoice that can be used to request a variable amount payment (also known
@@ -627,15 +597,15 @@ impl Bolt11Payment {
627597
&self, description: &Bolt11InvoiceDescription, expiry_secs: u32,
628598
max_proportional_lsp_fee_limit_ppm_msat: Option<u64>,
629599
) -> Result<Bolt11Invoice, Error> {
630-
let description = maybe_convert_description!(description);
600+
let description = maybe_try_convert_enum(description)?;
631601
let invoice = self.receive_via_jit_channel_inner(
632602
None,
633-
description,
603+
&description,
634604
expiry_secs,
635605
None,
636606
max_proportional_lsp_fee_limit_ppm_msat,
637607
)?;
638-
Ok(maybe_wrap_invoice(invoice))
608+
Ok(maybe_wrap(invoice))
639609
}
640610

641611
fn receive_via_jit_channel_inner(
@@ -742,7 +712,7 @@ impl Bolt11Payment {
742712
/// amount times [`Config::probing_liquidity_limit_multiplier`] won't be used to send
743713
/// pre-flight probes.
744714
pub fn send_probes(&self, invoice: &Bolt11Invoice) -> Result<(), Error> {
745-
let invoice = maybe_convert_invoice(invoice);
715+
let invoice = maybe_deref(invoice);
746716
let rt_lock = self.runtime.read().unwrap();
747717
if rt_lock.is_none() {
748718
return Err(Error::NotRunning);
@@ -775,7 +745,7 @@ impl Bolt11Payment {
775745
pub fn send_probes_using_amount(
776746
&self, invoice: &Bolt11Invoice, amount_msat: u64,
777747
) -> Result<(), Error> {
778-
let invoice = maybe_convert_invoice(invoice);
748+
let invoice = maybe_deref(invoice);
779749
let rt_lock = self.runtime.read().unwrap();
780750
if rt_lock.is_none() {
781751
return Err(Error::NotRunning);

src/payment/unified_qr.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,9 @@
1212
//! [BOLT 11]: https://github.com/lightning/bolts/blob/master/11-payment-encoding.md
1313
//! [BOLT 12]: https://github.com/lightning/bolts/blob/master/12-offer-encoding.md
1414
use crate::error::Error;
15+
use crate::ffi::maybe_wrap;
1516
use crate::logger::{log_error, LdkLogger, Logger};
16-
use crate::payment::{bolt11::maybe_wrap_invoice, Bolt11Payment, Bolt12Payment, OnchainPayment};
17+
use crate::payment::{Bolt11Payment, Bolt12Payment, OnchainPayment};
1718
use crate::Config;
1819

1920
use lightning::ln::channelmanager::PaymentId;
@@ -153,7 +154,7 @@ impl UnifiedQrPayment {
153154
}
154155

155156
if let Some(invoice) = uri_network_checked.extras.bolt11_invoice {
156-
let invoice = maybe_wrap_invoice(invoice);
157+
let invoice = maybe_wrap(invoice);
157158
match self.bolt11_invoice.send(&invoice, None) {
158159
Ok(payment_id) => return Ok(QrPaymentResult::Bolt11 { payment_id }),
159160
Err(e) => log_error!(self.logger, "Failed to send BOLT11 invoice: {:?}. This is part of a unified QR code payment. Falling back to the on-chain transaction.", e),

0 commit comments

Comments
 (0)