X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=lightning-c-bindings%2Fsrc%2Flightning_invoice%2Fpayment.rs;h=5dd6f168f5a34d0e894bacfa60000019d0d34fde;hb=248512824464326291d7eb36a9d9890a2993a1e3;hp=f53e73e14a9ce77fafc835475cf92e893edb86b1;hpb=23b946be5cf633afdba94e12fd71380cafdf49be;p=ldk-c-bindings diff --git a/lightning-c-bindings/src/lightning_invoice/payment.rs b/lightning-c-bindings/src/lightning_invoice/payment.rs index f53e73e..5dd6f16 100644 --- a/lightning-c-bindings/src/lightning_invoice/payment.rs +++ b/lightning-c-bindings/src/lightning_invoice/payment.rs @@ -31,6 +31,9 @@ //! # extern crate lightning_invoice; //! # extern crate secp256k1; //! # +//! # #[cfg(feature = \"no-std\")] +//! # extern crate core2; +//! # //! # use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret}; //! # use lightning::ln::channelmanager::{ChannelDetails, PaymentId, PaymentSendFailure}; //! # use lightning::ln::msgs::LightningError; @@ -46,6 +49,11 @@ //! # use std::cell::RefCell; //! # use std::ops::Deref; //! # +//! # #[cfg(not(feature = \"std\"))] +//! # use core2::io; +//! # #[cfg(feature = \"std\")] +//! # use std::io; +//! # //! # struct FakeEventProvider {} //! # impl EventsProvider for FakeEventProvider { //! # fn process_pending_events(&self, handler: H) where H::Target: EventHandler {} @@ -77,11 +85,11 @@ //! # //! # struct FakeScorer {} //! # impl Writeable for FakeScorer { -//! # fn write(&self, w: &mut W) -> Result<(), std::io::Error> { unimplemented!(); } +//! # fn write(&self, w: &mut W) -> Result<(), io::Error> { unimplemented!(); } //! # } //! # impl Score for FakeScorer { //! # fn channel_penalty_msat( -//! # &self, _short_channel_id: u64, _send_amt: u64, _chan_amt: Option, _source: &NodeId, _target: &NodeId +//! # &self, _short_channel_id: u64, _send_amt: u64, _chan_amt: u64, _source: &NodeId, _target: &NodeId //! # ) -> u64 { 0 } //! # fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {} //! # fn payment_path_successful(&mut self, _path: &[&RouteHop]) {} @@ -124,11 +132,13 @@ //! as updates to the network graph or changes to channel scores should be applied prior to //! retries, typically by way of composing [`EventHandler`]s accordingly. -use std::str::FromStr; -use std::ffi::c_void; +use alloc::str::FromStr; +use core::ffi::c_void; use core::convert::Infallible; use bitcoin::hashes::Hash; use crate::c_types::*; +#[cfg(feature="no-std")] +use alloc::{vec::Vec, boxed::Box}; use lightning_invoice::payment::InvoicePayer as nativeInvoicePayerImport; @@ -181,7 +191,7 @@ impl InvoicePayer { pub(crate) fn take_inner(mut self) -> *mut nativeInvoicePayer { assert!(self.is_owned); let ret = ObjOps::untweak_ptr(self.inner); - self.inner = std::ptr::null_mut(); + self.inner = core::ptr::null_mut(); ret } } @@ -264,7 +274,7 @@ impl rustPayer for Payer { // We're essentially a pointer already, or at least a set of pointers, so allow us to be used // directly as a Deref trait in higher-level structs: -impl std::ops::Deref for Payer { +impl core::ops::Deref for Payer { type Target = Self; fn deref(&self) -> &Self { self @@ -290,7 +300,7 @@ pub struct Router { /// /// Note that first_hops (or a relevant inner pointer) may be NULL or all-0s to represent None #[must_use] - pub find_route: extern "C" fn (this_arg: *const c_void, payer: crate::c_types::PublicKey, params: &crate::lightning::routing::router::RouteParameters, payment_hash: *const [u8; 32], first_hops: *mut crate::c_types::derived::CVec_ChannelDetailsZ, scorer: &crate::lightning::routing::scoring::Score) -> crate::c_types::derived::CResult_RouteLightningErrorZ, + pub find_route: extern "C" fn (this_arg: *const c_void, payer: crate::c_types::PublicKey, route_params: &crate::lightning::routing::router::RouteParameters, payment_hash: *const [u8; 32], first_hops: *mut crate::c_types::derived::CVec_ChannelDetailsZ, scorer: &crate::lightning::routing::scoring::Score) -> crate::c_types::derived::CResult_RouteLightningErrorZ, /// Frees any resources associated with this object given its this_arg pointer. /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed. pub free: Option, @@ -308,9 +318,9 @@ pub(crate) extern "C" fn Router_clone_fields(orig: &Router) -> Router { use lightning_invoice::payment::Router as rustRouter; impl rustRouter for Router { - fn find_route(&self, mut payer: &secp256k1::key::PublicKey, mut params: &lightning::routing::router::RouteParameters, mut payment_hash: &lightning::ln::PaymentHash, mut first_hops: Option<&[&lightning::ln::channelmanager::ChannelDetails]>, mut scorer: &crate::lightning::routing::scoring::Score) -> Result { + fn find_route(&self, mut payer: &secp256k1::key::PublicKey, mut route_params: &lightning::routing::router::RouteParameters, mut payment_hash: &lightning::ln::PaymentHash, mut first_hops: Option<&[&lightning::ln::channelmanager::ChannelDetails]>, mut scorer: &crate::lightning::routing::scoring::Score) -> Result { let mut local_first_hops_base = if first_hops.is_none() { SmartPtr::null() } else { SmartPtr::from_obj( { let mut local_first_hops_0 = Vec::new(); for item in (first_hops.unwrap()).iter() { local_first_hops_0.push( { crate::lightning::ln::channelmanager::ChannelDetails { inner: unsafe { ObjOps::nonnull_ptr_to_inner(((*item) as *const lightning::ln::channelmanager::ChannelDetails<>) as *mut _) }, is_owned: false } }); }; local_first_hops_0.into() }) }; let mut local_first_hops = *local_first_hops_base; - let mut ret = (self.find_route)(self.this_arg, crate::c_types::PublicKey::from_rust(&payer), &crate::lightning::routing::router::RouteParameters { inner: unsafe { ObjOps::nonnull_ptr_to_inner((params as *const lightning::routing::router::RouteParameters<>) as *mut _) }, is_owned: false }, &payment_hash.0, local_first_hops, scorer); + let mut ret = (self.find_route)(self.this_arg, crate::c_types::PublicKey::from_rust(&payer), &crate::lightning::routing::router::RouteParameters { inner: unsafe { ObjOps::nonnull_ptr_to_inner((route_params as *const lightning::routing::router::RouteParameters<>) as *mut _) }, is_owned: false }, &payment_hash.0, local_first_hops, scorer); let mut local_ret = match ret.result_ok { true => Ok( { *unsafe { Box::from_raw((*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).take_inner()) } }), false => Err( { *unsafe { Box::from_raw((*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).take_inner()) } })}; local_ret } @@ -318,7 +328,7 @@ impl rustRouter for Router { // We're essentially a pointer already, or at least a set of pointers, so allow us to be used // directly as a Deref trait in higher-level structs: -impl std::ops::Deref for Router { +impl core::ops::Deref for Router { type Target = Self; fn deref(&self) -> &Self { self @@ -385,7 +395,7 @@ impl RetryAttempts { pub(crate) fn take_inner(mut self) -> *mut nativeRetryAttempts { assert!(self.is_owned); let ret = ObjOps::untweak_ptr(self.inner); - self.inner = std::ptr::null_mut(); + self.inner = core::ptr::null_mut(); ret } } @@ -409,7 +419,7 @@ pub extern "C" fn RetryAttempts_new(mut a_arg: usize) -> RetryAttempts { impl Clone for RetryAttempts { fn clone(&self) -> Self { Self { - inner: if <*mut nativeRetryAttempts>::is_null(self.inner) { std::ptr::null_mut() } else { + inner: if <*mut nativeRetryAttempts>::is_null(self.inner) { core::ptr::null_mut() } else { ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } @@ -438,11 +448,11 @@ pub extern "C" fn RetryAttempts_eq(a: &RetryAttempts, b: &RetryAttempts) -> bool #[no_mangle] pub extern "C" fn RetryAttempts_hash(o: &RetryAttempts) -> u64 { if o.inner.is_null() { return 0; } - // Note that we'd love to use std::collections::hash_map::DefaultHasher but it's not in core + // Note that we'd love to use alloc::collections::hash_map::DefaultHasher but it's not in core #[allow(deprecated)] let mut hasher = core::hash::SipHasher::new(); - std::hash::Hash::hash(o.get_native_ref(), &mut hasher); - std::hash::Hasher::finish(&hasher) + core::hash::Hash::hash(o.get_native_ref(), &mut hasher); + core::hash::Hasher::finish(&hasher) } /// An error that may occur when making a payment. #[must_use] @@ -574,9 +584,9 @@ pub extern "C" fn PaymentError_sending(a: crate::lightning::ln::channelmanager:: /// `retry_attempts` has been exceeded for a given [`Invoice`]. #[must_use] #[no_mangle] -pub extern "C" fn InvoicePayer_new(mut payer: crate::lightning_invoice::payment::Payer, mut router: crate::lightning_invoice::payment::Router, scorer: &crate::lightning::routing::scoring::MultiThreadedLockableScore, mut logger: crate::lightning::util::logger::Logger, mut event_handler: crate::lightning::util::events::EventHandler, mut retry_attempts: crate::lightning_invoice::payment::RetryAttempts) -> InvoicePayer { +pub extern "C" fn InvoicePayer_new(mut payer: crate::lightning_invoice::payment::Payer, mut router: crate::lightning_invoice::payment::Router, scorer: &crate::lightning::routing::scoring::MultiThreadedLockableScore, mut logger: crate::lightning::util::logger::Logger, mut event_handler: crate::lightning::util::events::EventHandler, mut retry_attempts: crate::lightning_invoice::payment::RetryAttempts) -> crate::lightning_invoice::payment::InvoicePayer { let mut ret = lightning_invoice::payment::InvoicePayer::new(payer, router, scorer.get_native_ref(), logger, event_handler, *unsafe { Box::from_raw(retry_attempts.take_inner()) }); - InvoicePayer { inner: ObjOps::heap_alloc(ret), is_owned: true } + crate::lightning_invoice::payment::InvoicePayer { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// Pays the given [`Invoice`], caching it for later use in case a retry is needed. @@ -586,7 +596,7 @@ pub extern "C" fn InvoicePayer_new(mut payer: crate::lightning_invoice::payment: /// for you. #[must_use] #[no_mangle] -pub extern "C" fn InvoicePayer_pay_invoice(this_arg: &InvoicePayer, invoice: &crate::lightning_invoice::Invoice) -> crate::c_types::derived::CResult_PaymentIdPaymentErrorZ { +pub extern "C" fn InvoicePayer_pay_invoice(this_arg: &crate::lightning_invoice::payment::InvoicePayer, invoice: &crate::lightning_invoice::Invoice) -> crate::c_types::derived::CResult_PaymentIdPaymentErrorZ { let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.pay_invoice(invoice.get_native_ref()); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::ThirtyTwoBytes { data: o.0 } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::payment::PaymentError::native_into(e) }).into() }; local_ret @@ -600,7 +610,7 @@ pub extern "C" fn InvoicePayer_pay_invoice(this_arg: &InvoicePayer, invoice: &cr /// for you. #[must_use] #[no_mangle] -pub extern "C" fn InvoicePayer_pay_zero_value_invoice(this_arg: &InvoicePayer, invoice: &crate::lightning_invoice::Invoice, mut amount_msats: u64) -> crate::c_types::derived::CResult_PaymentIdPaymentErrorZ { +pub extern "C" fn InvoicePayer_pay_zero_value_invoice(this_arg: &crate::lightning_invoice::payment::InvoicePayer, invoice: &crate::lightning_invoice::Invoice, mut amount_msats: u64) -> crate::c_types::derived::CResult_PaymentIdPaymentErrorZ { let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.pay_zero_value_invoice(invoice.get_native_ref(), amount_msats); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::ThirtyTwoBytes { data: o.0 } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::payment::PaymentError::native_into(e) }).into() }; local_ret @@ -613,7 +623,7 @@ pub extern "C" fn InvoicePayer_pay_zero_value_invoice(this_arg: &InvoicePayer, i /// been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so for you. #[must_use] #[no_mangle] -pub extern "C" fn InvoicePayer_pay_pubkey(this_arg: &InvoicePayer, mut pubkey: crate::c_types::PublicKey, mut payment_preimage: crate::c_types::ThirtyTwoBytes, mut amount_msats: u64, mut final_cltv_expiry_delta: u32) -> crate::c_types::derived::CResult_PaymentIdPaymentErrorZ { +pub extern "C" fn InvoicePayer_pay_pubkey(this_arg: &crate::lightning_invoice::payment::InvoicePayer, mut pubkey: crate::c_types::PublicKey, mut payment_preimage: crate::c_types::ThirtyTwoBytes, mut amount_msats: u64, mut final_cltv_expiry_delta: u32) -> crate::c_types::derived::CResult_PaymentIdPaymentErrorZ { let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.pay_pubkey(pubkey.into_rust(), ::lightning::ln::PaymentPreimage(payment_preimage.data), amount_msats, final_cltv_expiry_delta); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::ThirtyTwoBytes { data: o.0 } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::payment::PaymentError::native_into(e) }).into() }; local_ret @@ -624,7 +634,7 @@ pub extern "C" fn InvoicePayer_pay_pubkey(this_arg: &InvoicePayer, mut pubkey: c /// Should be called once a payment has failed or succeeded if not using [`InvoicePayer`] as an /// [`EventHandler`]. Otherwise, calling this method is unnecessary. #[no_mangle] -pub extern "C" fn InvoicePayer_remove_cached_payment(this_arg: &InvoicePayer, payment_hash: *const [u8; 32]) { +pub extern "C" fn InvoicePayer_remove_cached_payment(this_arg: &crate::lightning_invoice::payment::InvoicePayer, payment_hash: *const [u8; 32]) { unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.remove_cached_payment(&::lightning::ln::PaymentHash(unsafe { *payment_hash })) } @@ -633,7 +643,7 @@ impl From for crate::lightning::util::events::EventHandler { let mut rust_obj = InvoicePayer { inner: ObjOps::heap_alloc(obj), is_owned: true }; let mut ret = InvoicePayer_as_EventHandler(&rust_obj); // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn - rust_obj.inner = std::ptr::null_mut(); + rust_obj.inner = core::ptr::null_mut(); ret.free = Some(InvoicePayer_free_void); ret }