Skip to content

Commit 54f99b4

Browse files
committed
feat(wip): expose PaymentPreimage wrapper to FFI
Dirty implementation requiring cleanup of the ffg: - commented code - possibly unnecessary clones
1 parent 4f637b5 commit 54f99b4

11 files changed

Lines changed: 187 additions & 76 deletions

File tree

bindings/ldk_node.udl

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -450,6 +450,10 @@ dictionary PaymentDetails {
450450
u64 latest_update_timestamp;
451451
};
452452

453+
dictionary PaymentPreimage {
454+
bytes inner;
455+
};
456+
453457
dictionary SendingParameters {
454458
MaxTotalRoutingFeeLimit? max_total_routing_fee_msat;
455459
u32? max_total_cltv_expiry_delta;
@@ -833,9 +837,6 @@ typedef string PaymentId;
833837
[Custom]
834838
typedef string PaymentHash;
835839

836-
[Custom]
837-
typedef string PaymentPreimage;
838-
839840
[Custom]
840841
typedef string PaymentSecret;
841842

src/balance.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,16 @@
55
// http://opensource.org/licenses/MIT>, at your option. You may not use this file except in
66
// accordance with one or both of these licenses.
77

8+
use crate::ffi::maybe_wrap;
9+
use crate::payment::PaymentPreimage;
810
use crate::sweep::value_from_descriptor;
911

1012
use lightning::chain::channelmonitor::Balance as LdkBalance;
1113
use lightning::chain::channelmonitor::BalanceSource;
1214
use lightning::ln::types::ChannelId;
1315
use lightning::util::sweep::{OutputSpendStatus, TrackedSpendableOutput};
1416

15-
use lightning_types::payment::{PaymentHash, PaymentPreimage};
17+
use lightning_types::payment::PaymentHash;
1618

1719
use bitcoin::secp256k1::PublicKey;
1820
use bitcoin::{BlockHash, Txid};
@@ -263,7 +265,7 @@ impl LightningBalance {
263265
amount_satoshis,
264266
timeout_height,
265267
payment_hash,
266-
payment_preimage,
268+
payment_preimage: maybe_wrap(payment_preimage),
267269
},
268270
LdkBalance::MaybeTimeoutClaimableHTLC {
269271
amount_satoshis,

src/event.rs

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
// http://opensource.org/licenses/MIT>, at your option. You may not use this file except in
66
// accordance with one or both of these licenses.
77

8+
use crate::ffi::maybe_wrap;
89
use crate::types::{CustomTlvRecord, DynStore, PaymentStore, Sweeper, Wallet};
910

1011
use crate::{
@@ -22,6 +23,7 @@ use crate::logger::Logger;
2223
use crate::payment::store::{
2324
PaymentDetails, PaymentDetailsUpdate, PaymentDirection, PaymentKind, PaymentStatus,
2425
};
26+
use crate::payment::PaymentPreimage;
2527

2628
use crate::io::{
2729
EVENT_QUEUE_PERSISTENCE_KEY, EVENT_QUEUE_PERSISTENCE_PRIMARY_NAMESPACE,
@@ -39,7 +41,7 @@ use lightning::routing::gossip::NodeId;
3941
use lightning::util::errors::APIError;
4042
use lightning::util::ser::{Readable, ReadableArgs, Writeable, Writer};
4143

42-
use lightning_types::payment::{PaymentHash, PaymentPreimage};
44+
use lightning_types::payment::PaymentHash;
4345

4446
use lightning_liquidity::lsps2::utils::compute_opening_fee;
4547

@@ -740,7 +742,7 @@ where
740742
let quantity = payment_context.invoice_request.quantity;
741743
let kind = PaymentKind::Bolt12Offer {
742744
hash: Some(payment_hash),
743-
preimage: payment_preimage,
745+
preimage: payment_preimage.map(|preimage| maybe_wrap(preimage)),
744746
secret: Some(payment_secret),
745747
offer_id,
746748
payer_note,
@@ -785,7 +787,7 @@ where
785787
// Since it's spontaneous, we insert it now into our store.
786788
let kind = PaymentKind::Spontaneous {
787789
hash: payment_hash,
788-
preimage: Some(preimage),
790+
preimage: Some(maybe_wrap(preimage)),
789791
};
790792

791793
let payment = PaymentDetails::new(
@@ -871,7 +873,7 @@ where
871873
payment_secret,
872874
..
873875
} => PaymentDetailsUpdate {
874-
preimage: Some(payment_preimage),
876+
preimage: Some(payment_preimage.map(|preimage| maybe_wrap(preimage))),
875877
secret: Some(Some(payment_secret)),
876878
amount_msat: Some(Some(amount_msat)),
877879
status: Some(PaymentStatus::Succeeded),
@@ -880,7 +882,7 @@ where
880882
PaymentPurpose::Bolt12OfferPayment {
881883
payment_preimage, payment_secret, ..
882884
} => PaymentDetailsUpdate {
883-
preimage: Some(payment_preimage),
885+
preimage: Some(payment_preimage.map(|preimage| maybe_wrap(preimage))),
884886
secret: Some(Some(payment_secret)),
885887
amount_msat: Some(Some(amount_msat)),
886888
status: Some(PaymentStatus::Succeeded),
@@ -891,14 +893,14 @@ where
891893
payment_secret,
892894
..
893895
} => PaymentDetailsUpdate {
894-
preimage: Some(payment_preimage),
896+
preimage: Some(payment_preimage.map(|preimage| maybe_wrap(preimage))),
895897
secret: Some(Some(payment_secret)),
896898
amount_msat: Some(Some(amount_msat)),
897899
status: Some(PaymentStatus::Succeeded),
898900
..PaymentDetailsUpdate::new(payment_id)
899901
},
900902
PaymentPurpose::SpontaneousPayment(preimage) => PaymentDetailsUpdate {
901-
preimage: Some(Some(preimage)),
903+
preimage: Some(Some(maybe_wrap(preimage))),
902904
amount_msat: Some(Some(amount_msat)),
903905
status: Some(PaymentStatus::Succeeded),
904906
..PaymentDetailsUpdate::new(payment_id)
@@ -960,7 +962,7 @@ where
960962

961963
let update = PaymentDetailsUpdate {
962964
hash: Some(Some(payment_hash)),
963-
preimage: Some(Some(payment_preimage)),
965+
preimage: Some(Some(maybe_wrap(payment_preimage))),
964966
fee_paid_msat: Some(fee_paid_msat),
965967
status: Some(PaymentStatus::Succeeded),
966968
..PaymentDetailsUpdate::new(payment_id)
@@ -992,7 +994,7 @@ where
992994
let event = Event::PaymentSuccessful {
993995
payment_id: Some(payment_id),
994996
payment_hash,
995-
payment_preimage: Some(payment_preimage),
997+
payment_preimage: Some(maybe_wrap(payment_preimage)),
996998
fee_paid_msat,
997999
};
9981000

src/ffi/mod.rs

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,23 @@ where
1818
wrapped_type.as_ref().as_ref()
1919
}
2020

21+
// #[cfg(feature = "uniffi")]
22+
// pub fn maybe_extract_inner<T, R>(wrapped_type: T) -> Result<R, crate::error::Error>
23+
// where
24+
// R: TryFrom<T, Error = crate::error::Error>,
25+
// {
26+
// R::try_from(wrapped_type)
27+
// }
28+
29+
/// Extract inner type.
30+
#[cfg(feature = "uniffi")]
31+
#[macro_export]
32+
macro_rules! maybe_extract_inner {
33+
($value:expr) => {
34+
TryFrom::try_from($value)?
35+
};
36+
}
37+
2138
#[cfg(feature = "uniffi")]
2239
pub fn maybe_try_convert_enum<T, R>(wrapped_type: &T) -> Result<R, crate::error::Error>
2340
where
@@ -27,10 +44,15 @@ where
2744
}
2845

2946
#[cfg(feature = "uniffi")]
30-
pub fn maybe_wrap<T>(ldk_type: impl Into<T>) -> std::sync::Arc<T> {
47+
pub fn maybe_wrap_arc<T>(ldk_type: impl Into<T>) -> std::sync::Arc<T> {
3148
std::sync::Arc::new(ldk_type.into())
3249
}
3350

51+
#[cfg(feature = "uniffi")]
52+
pub fn maybe_wrap<T>(ldk_type: impl Into<T>) -> T {
53+
ldk_type.into()
54+
}
55+
3456
#[cfg(not(feature = "uniffi"))]
3557
pub fn maybe_deref<T>(value: &T) -> &T {
3658
value
@@ -41,7 +63,26 @@ pub fn maybe_try_convert_enum<T>(value: &T) -> Result<&T, crate::error::Error> {
4163
Ok(value)
4264
}
4365

66+
#[cfg(not(feature = "uniffi"))]
67+
pub fn maybe_wrap_arc<T>(value: T) -> T {
68+
value
69+
}
70+
4471
#[cfg(not(feature = "uniffi"))]
4572
pub fn maybe_wrap<T>(value: T) -> T {
4673
value
4774
}
75+
76+
// #[cfg(not(feature = "uniffi"))]
77+
// pub fn maybe_extract_inner<T>(value: T) -> T {
78+
// value
79+
// }
80+
81+
/// Extract inner type.
82+
#[cfg(not(feature = "uniffi"))]
83+
#[macro_export]
84+
macro_rules! maybe_extract_inner {
85+
($value:expr) => {
86+
$value
87+
};
88+
}

src/ffi/types.rs

Lines changed: 60 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -22,14 +22,18 @@ pub use crate::payment::store::{
2222
};
2323
pub use crate::payment::{MaxTotalRoutingFeeLimit, QrPaymentResult, SendingParameters};
2424

25+
use bitcoin::io::Read;
2526
pub use lightning::chain::channelmonitor::BalanceSource;
2627
pub use lightning::events::{ClosureReason, PaymentFailureReason};
28+
use lightning::ln::msgs::DecodeError;
2729
pub use lightning::ln::types::ChannelId;
2830
pub use lightning::offers::offer::OfferId;
2931
pub use lightning::routing::gossip::{NodeAlias, NodeId, RoutingFees};
3032
pub use lightning::util::string::UntrustedString;
3133

32-
pub use lightning_types::payment::{PaymentHash, PaymentPreimage, PaymentSecret};
34+
pub use lightning_types::payment::{
35+
PaymentHash, PaymentPreimage as LdkPaymentPreimage, PaymentSecret,
36+
};
3337

3438
pub use lightning_invoice::{Description, SignedRawBolt11Invoice};
3539

@@ -58,7 +62,7 @@ use lightning::ln::channelmanager::PaymentId;
5862
use lightning::offers::invoice::Bolt12Invoice as LdkBolt12Invoice;
5963
use lightning::offers::offer::{Amount as LdkAmount, Offer as LdkOffer};
6064
use lightning::offers::refund::Refund as LdkRefund;
61-
use lightning::util::ser::Writeable;
65+
use lightning::util::ser::{Readable, Writeable};
6266
use lightning_invoice::{Bolt11Invoice as LdkBolt11Invoice, Bolt11InvoiceDescriptionRef};
6367

6468
use std::convert::TryInto;
@@ -631,6 +635,60 @@ impl UniffiCustomTypeConverter for OfferId {
631635
}
632636
}
633637

638+
#[derive(Debug, Clone, PartialEq, Eq)]
639+
pub struct PaymentPreimage {
640+
pub(crate) inner: Vec<u8>,
641+
}
642+
643+
impl From<LdkPaymentPreimage> for PaymentPreimage {
644+
fn from(ldk_value: LdkPaymentPreimage) -> Self {
645+
PaymentPreimage { inner: ldk_value.0.to_vec() }
646+
}
647+
}
648+
649+
impl TryFrom<PaymentPreimage> for LdkPaymentPreimage {
650+
type Error = Error;
651+
652+
fn try_from(preimage: PaymentPreimage) -> Result<Self, Self::Error> {
653+
if preimage.inner.len() != 32 {
654+
return Err(Error::InvalidPaymentPreimage);
655+
}
656+
657+
let mut array = [0u8; 32];
658+
array.copy_from_slice(&preimage.inner);
659+
Ok(LdkPaymentPreimage(array))
660+
}
661+
}
662+
663+
impl FromStr for PaymentPreimage {
664+
type Err = Error;
665+
666+
fn from_str(s: &str) -> Result<Self, Self::Err> {
667+
if let Some(bytes) = hex_utils::to_vec(s) {
668+
if let Ok(array) = bytes.try_into() {
669+
return Ok(Self::from(LdkPaymentPreimage(array)));
670+
}
671+
}
672+
673+
Err(Error::InvalidPaymentPreimage)
674+
}
675+
}
676+
677+
impl Writeable for PaymentPreimage {
678+
fn write<W: lightning::util::ser::Writer>(
679+
&self, writer: &mut W,
680+
) -> Result<(), lightning::io::Error> {
681+
Ok(self.inner.write(writer)?)
682+
}
683+
}
684+
685+
impl Readable for PaymentPreimage {
686+
fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
687+
let buf: [u8; 32] = Readable::read(r)?;
688+
Ok(PaymentPreimage { inner: buf.to_vec() })
689+
}
690+
}
691+
634692
impl UniffiCustomTypeConverter for PaymentId {
635693
type Builtin = String;
636694

@@ -665,24 +723,6 @@ impl UniffiCustomTypeConverter for PaymentHash {
665723
}
666724
}
667725

668-
impl UniffiCustomTypeConverter for PaymentPreimage {
669-
type Builtin = String;
670-
671-
fn into_custom(val: Self::Builtin) -> uniffi::Result<Self> {
672-
if let Some(bytes_vec) = hex_utils::to_vec(&val) {
673-
let bytes_res = bytes_vec.try_into();
674-
if let Ok(bytes) = bytes_res {
675-
return Ok(PaymentPreimage(bytes));
676-
}
677-
}
678-
Err(Error::InvalidPaymentPreimage.into())
679-
}
680-
681-
fn from_custom(obj: Self) -> Self::Builtin {
682-
hex_utils::to_string(&obj.0)
683-
}
684-
}
685-
686726
impl UniffiCustomTypeConverter for PaymentSecret {
687727
type Builtin = String;
688728

0 commit comments

Comments
 (0)